cfi*_*her 51 python external-process return-value
如何使用python脚本调用外部程序并检索输出并返回代码?
jkp*_*jkp 68
查看子进程模块:一个简单的例子如下......
from subprocess import Popen, PIPE
process = Popen(["ls", "-la", "."], stdout=PIPE)
(output, err) = process.communicate()
exit_code = process.wait()
Run Code Online (Sandbox Code Playgroud)
Jab*_*bba 17
继Ambroz Bizjak先前的评论之后,这是一个对我有用的解决方案:
import shlex
from subprocess import Popen, PIPE
cmd = "..."
process = Popen(shlex.split(cmd), stdout=PIPE)
process.communicate()
exit_code = process.wait()
Run Code Online (Sandbox Code Playgroud)
经过一番研究,我得到了以下代码,它对我来说非常有效。它基本上实时打印标准输出和标准错误。希望它能帮助其他有需要的人。
stdout_result = 1
stderr_result = 1
def stdout_thread(pipe):
global stdout_result
while True:
out = pipe.stdout.read(1)
stdout_result = pipe.poll()
if out == '' and stdout_result is not None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
def stderr_thread(pipe):
global stderr_result
while True:
err = pipe.stderr.read(1)
stderr_result = pipe.poll()
if err == '' and stderr_result is not None:
break
if err != '':
sys.stdout.write(err)
sys.stdout.flush()
def exec_command(command, cwd=None):
if cwd is not None:
print '[' + ' '.join(command) + '] in ' + cwd
else:
print '[' + ' '.join(command) + ']'
p = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd
)
out_thread = threading.Thread(name='stdout_thread', target=stdout_thread, args=(p,))
err_thread = threading.Thread(name='stderr_thread', target=stderr_thread, args=(p,))
err_thread.start()
out_thread.start()
out_thread.join()
err_thread.join()
return stdout_result + stderr_result
Run Code Online (Sandbox Code Playgroud)