如何使用python脚本调用外部程序并检索输出并返回代码?
答案 0 :(得分:62)
查看subprocess模块:一个简单的例子如下......
from subprocess import Popen, PIPE
process = Popen(["ls", "-la", "."], stdout=PIPE)
(output, err) = process.communicate()
exit_code = process.wait()
答案 1 :(得分:15)
按照Ambroz Bizjak之前的评论,这是一个对我有用的解决方案:
import shlex
from subprocess import Popen, PIPE
cmd = "..."
process = Popen(shlex.split(cmd), stdout=PIPE)
process.communicate()
exit_code = process.wait()
答案 2 :(得分:2)
在此处查看子流程模块:http://docs.python.org/library/subprocess.html#module-subprocess。它应该得到你需要做的。
答案 3 :(得分:2)
经过一些研究,我有以下代码,对我来说效果很好。它基本上实时打印stdout和stderr。希望它可以帮助其他需要它的人。
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
答案 4 :(得分:2)
我开发了一个小库(py-execute),它允许您执行外部程序,检索输出和重新编码,同时实时在控制台中输出:
>>> from py_execute.process_executor import execute
>>> ret = execute('echo "Hello"')
Hello
>>> ret
(0, 'Hello\n')
您可以避免通过模拟user_io打印到控制台:
>>> from mock import Mock
>>> execute('echo "Hello"', ui=Mock())
(0, 'Hello\n')
我写的是因为普通的Popen(在Python 2.7中)我在执行长输出的命令时遇到了麻烦