简体   繁体   English

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

[英]How to call an external program in python and retrieve the output and return code?

How can I call an external program with a python script and retrieve the output and return code?如何使用 python 脚本调用外部程序并检索 output 并返回代码?

Look at the subprocess module: a simple example follows...查看subprocess模块:下面是一个简单的示例...

from subprocess import Popen, PIPE

process = Popen(["ls", "-la", "."], stdout=PIPE)
(output, err) = process.communicate()
exit_code = process.wait()

Following Ambroz Bizjak's previous comment, here is a solution that worked for me:在 Ambroz Bizjak 之前的评论之后,这里有一个对我有用的解决方案:

import shlex
from subprocess import Popen, PIPE

cmd = "..."
process = Popen(shlex.split(cmd), stdout=PIPE)
process.communicate()
exit_code = process.wait()

After some research, I have the following code which works very well for me.经过一些研究,我有以下代码对我来说效果很好。 It basically prints both stdout and stderr in real time.它基本上实时打印标准输出和标准错误。 Hope it helps someone else who needs it.希望它可以帮助其他需要它的人。

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

Check out the subprocess module here: http://docs.python.org/library/subprocess.html#module-subprocess .在此处查看子流程模块: http://docs.python.org/library/subprocess.html#module-subprocess It should get what you need done.它应该可以完成您需要的工作。

I've developed a little library ( py-execute ) that allows you to execute external programs, retrieve the output and the retcode and, at the same time get output in console in real time:我开发了一个小库( py-execute ),允许您执行外部程序,检索 output 和 retcode,同时在控制台中实时获取 output:

>>> from py_execute.process_executor import execute
>>> ret = execute('echo "Hello"')
Hello
>>> ret
(0, 'Hello\n')

You can avoid printing to console passing a mock user_io:您可以避免通过模拟 user_io 打印到控制台:

>>> from mock import Mock
>>> execute('echo "Hello"', ui=Mock())
(0, 'Hello\n')

I wrote it because with plain Popen (In Python 2.7) I was having trouble executing commands with a long output我写它是因为使用普通 Popen(在 Python 2.7 中)我在执行长 output 的命令时遇到问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM