
import subprocess
def testMingLing(cmd):
subp = subprocess.Popen(cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding="utf-8")
subp.wait(2)
print(subp.pid)
print(subp.stdout.readlines())
#print(subp.stderr)
if subp.poll() == 0:
print(123)
print(subp.communicate()[1])
else:
print("失败")
if __name__ == '__main__':
cmd = 'cd ../oneCX;nohup python3 writeFile.py fenfa > fenfa.log &'
testMingLing(cmd)
import subprocess
def runcmd(command):
ret = subprocess.run(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf-8",timeout=1)
if ret.returncode == 0:
print("success:",ret)
else:
print("error:",ret)
runcmd(["dir","/b"])#序列参数
runcmd("exit 1")#字符串参数
总结:
- 如果你的应用使用的Python 2.4以上,但是是Python 3.5以下的版本,Python官方给出的建议是使用subprocess.call()函数。Python 2.5中新增了一个subprocess.check_call()函数,Python 2.7中新增了一个subprocess.check_output()函数,这两个函数也可以按照需求进行使用。
- 如果你的应用使用的是Python 3.5及以上的版本(目前应该还很少),Python官方给出的建议是尽量使用subprocess.run()函数。
- 当subprocess.call()、subprocess.check_call()、subprocess.check_output()和subprocess.run()这些高级函数无法满足需求时,我们可以使用subprocess.Popen类来实现我们需要的复杂功能。
实战实例
import subprocess
def main(exec_command):
# exec_command = 'python cloudChart_crond.py -k 01 001'
# exec_command = 'python cloudChart_crond.py -k 05'
p = subprocess.Popen(exec_command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8")
for line in p.stdout.readlines():
print(line.strip())
print('----------------')
etval = p.wait()
if etval == 0:
print('===========================成功===========================')
网友评论