如何在python中调用外部程序并检索输出并返回代码?

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)

  • 我编辑了上面的答案,以反映Ambroz的建议,以防有人不读取评论并使用以前不正确的代码. (10认同)
  • 看来[上面的解决方案](/sf/answers/49490101/)可以用简单的调用代替[`subprocess.run()`](https://docs.python.org/dev /library/subprocess.html#subprocess.run)(需要 Python >= 3.5)。 (2认同)

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)

  • 这是迄今为止最好的答案. (4认同)
  • 我有一个类似的帖子[这里](/sf/ask/139756291/#21000308),它展示了如何从流程中获取三件事:exitcode, stdout,stderr. (3认同)

Jak*_*e W 5

经过一番研究,我得到了以下代码,它对我来说非常有效。它基本上实时打印标准输出和标准错误。希望它能帮助其他有需要的人。

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)