本篇探讨python中调用p4命令行执行p4命令的各种写发,其中大多数是异曲同工只是python调用进程的写法不同,但是其中有些差异也是能给你的工作带来一些影响的,可根据自己的需要选择相应的写法。具体perforce命令行文档:Commands
1.check_output
import subprocess
output = subprocess.check_output("p4 info", shell=True)
text = output.decode(encoding='UTF-8')
print(text)
2.Popen(可获取输出信息的数组)
output= subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
outPutLines = output.stdout.readlines()
for outPutLine in outPutLines:
lineInfo = outPutLine.decode('UTF-8')
print("lineInfo :" + lineInfo )
3.Popen
def run_p4_cmd(cmds, print_result=True):
print(f"P4 cmd: {' '.join(cmds)}")
proc = subprocess.Popen(cmds, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
commit_msg, err = proc.communicate()
msg = commit_msg.decode("utf-8", "ignore")
if print_result:
print(msg)
if err:
print(err.decode('utf-8', "ignore"))
return msg, proc.returncode
4.p4python(Programming with P4Python)
from P4 import P4,P4Exception # Import the module
p4 = P4() # Create the P4 instance
p4.port = "Test_1666"
p4.user = "dzk"
p4.client = "dzk-ws" # Set some environment variables
try: # Catch exceptions with try/except
p4.connect() # Connect to the Perforce server
info = p4.run( "fstat","//JF_UEProj/BR_PTest_Dev/Common//CustomMgr.lua") # Run "p4 fstat" (returns a dict)
for key in info[0]: # and display all key-value pairs
print key, "=", info[0][key]
p4.run( "edit", "file.txt" ) # Run "p4 edit file.txt"
p4.disconnect() # Disconnect from the server
except P4Exception:
for e in p4.errors: # Display errors
print e
for e in p4.warnings: # Display warnings
print e