149

我需要从 Python 脚本异步运行 shell 命令。我的意思是我希望我的 Python 脚本在外部命令关闭并执行它需要做的任何事情时继续运行。

我读了这篇文章:

在 Python 中调用外部命令

然后我开始进行一些测试,看起来os.system()可以完成我在命令末尾使用的工作,&这样我就不必等待它返回。我想知道这是否是完成此类事情的正确方法?我试过commands.call()了,但它对我不起作用,因为它阻止了外部命令。

请让我知道是否os.system()建议使用此方法,或者我是否应该尝试其他路线。

4

10 回答 10

159

subprocess.Popen做你想要的。

from subprocess import Popen
p = Popen(['watch', 'ls']) # something long running
# ... do other stuff while subprocess is running
p.terminate()

(编辑以完成评论中的答案)

Popen 实例可以执行各种其他操作,例如poll()查看它是否仍在运行,您可以communicate()使用它在标准输入上向其发送数据,并等待它终止。

于 2009-03-11T22:05:32.613 回答
58

如果您想并行运行多个进程,然后在它们产生结果时处理它们,您可以使用轮询,如下所示:

from subprocess import Popen, PIPE
import time

running_procs = [
    Popen(['/usr/bin/my_cmd', '-i %s' % path], stdout=PIPE, stderr=PIPE)
    for path in '/tmp/file0 /tmp/file1 /tmp/file2'.split()]

while running_procs:
    for proc in running_procs:
        retcode = proc.poll()
        if retcode is not None: # Process finished.
            running_procs.remove(proc)
            break
        else: # No process is done, wait a bit and check again.
            time.sleep(.1)
            continue

    # Here, `proc` has finished with return code `retcode`
    if retcode != 0:
        """Error handling."""
    handle_results(proc.stdout)

那里的控制流有点复杂,因为我试图让它变小——你可以根据自己的喜好进行重构。:-)

这具有首先服务于早期完成请求的优点。如果您调用communicate第一个正在运行的进程并且结果证明它运行时间最长,那么当您本可以处理它们的结果时,其他正在运行的进程将一直处于空闲状态。

于 2009-03-11T22:15:50.373 回答
21

这在“等待命令异步终止”下的Python 3 子进程示例中有所介绍。IPython使用or运行此代码python -m asyncio

import asyncio

proc = await asyncio.create_subprocess_exec(
   'ls','-lha',
   stdout=asyncio.subprocess.PIPE,
   stderr=asyncio.subprocess.PIPE)

# do something else while ls is working

# if proc takes very long to complete, the CPUs are free to use cycles for 
# other processes
stdout, stderr = await proc.communicate()

该过程将在await asyncio.create_subprocess_exec(...)完成后立即开始运行。如果在您调用时它还没有完成await proc.communicate(),它将在那里等待以便为您提供输出状态。如果已经完成,proc.communicate()将立即返回。

这里的要点类似于Terrels 的答案,但我认为 Terrels 的答案似乎使事情过于复杂。

有关asyncio.create_subprocess_exec更多信息,请参阅。

于 2020-04-16T15:52:47.670 回答
14

我想知道的是,这 [os.system()] 是否是完成此类事情的正确方法?

os.system(),不是正确的方法。这就是为什么每个人都说使用subprocess.

有关更多信息,请阅读http://docs.python.org/library/os.html#os.system

subprocess 模块提供了更强大的工具来生成新进程并检索它们的结果;使用该模块优于使用此功能。使用子流程模块。尤其要检查用子流程模块替换旧功能部分。

于 2009-03-11T22:24:32.567 回答
9

接受的答案老了。

我在这里找到了一个更好的现代答案:

https://kevinmccarthy.org/2016/07/25/streaming-subprocess-stdin-and-stdout-with-asyncio-in-python/

并做了一些改动:

  1. 让它在windows上工作
  2. 使其与多个命令一起使用
import sys
import asyncio

if sys.platform == "win32":
    asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())


async def _read_stream(stream, cb):
    while True:
        line = await stream.readline()
        if line:
            cb(line)
        else:
            break


async def _stream_subprocess(cmd, stdout_cb, stderr_cb):
    try:
        process = await asyncio.create_subprocess_exec(
            *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
        )

        await asyncio.wait(
            [
                _read_stream(process.stdout, stdout_cb),
                _read_stream(process.stderr, stderr_cb),
            ]
        )
        rc = await process.wait()
        return process.pid, rc
    except OSError as e:
        # the program will hang if we let any exception propagate
        return e


def execute(*aws):
    """ run the given coroutines in an asyncio loop
    returns a list containing the values returned from each coroutine.
    """
    loop = asyncio.get_event_loop()
    rc = loop.run_until_complete(asyncio.gather(*aws))
    loop.close()
    return rc


def printer(label):
    def pr(*args, **kw):
        print(label, *args, **kw)

    return pr


def name_it(start=0, template="s{}"):
    """a simple generator for task names
    """
    while True:
        yield template.format(start)
        start += 1


def runners(cmds):
    """
    cmds is a list of commands to excecute as subprocesses
    each item is a list appropriate for use by subprocess.call
    """
    next_name = name_it().__next__
    for cmd in cmds:
        name = next_name()
        out = printer(f"{name}.stdout")
        err = printer(f"{name}.stderr")
        yield _stream_subprocess(cmd, out, err)


if __name__ == "__main__":
    cmds = (
        [
            "sh",
            "-c",
            """echo "$SHELL"-stdout && sleep 1 && echo stderr 1>&2 && sleep 1 && echo done""",
        ],
        [
            "bash",
            "-c",
            "echo 'hello, Dave.' && sleep 1 && echo dave_err 1>&2 && sleep 1 && echo done",
        ],
        [sys.executable, "-c", 'print("hello from python");import sys;sys.exit(2)'],
    )

    print(execute(*runners(cmds)))

示例命令不太可能在您的系统上完美运行,并且它不会处理奇怪的错误,但此代码确实演示了一种使用 asyncio 运行多个子进程并流式传输输出的方法。

于 2019-07-24T16:07:32.233 回答
8

我在asyncproc模块上取得了很好的成功,它很好地处理了进程的输出。例如:

import os
from asynproc import Process
myProc = Process("myprogram.app")

while True:
    # check to see if process has ended
    poll = myProc.wait(os.WNOHANG)
    if poll is not None:
        break
    # print any new output
    out = myProc.read()
    if out != "":
        print out
于 2009-03-11T23:04:44.390 回答
7

pexpect与非阻塞 readlines 一起使用是另一种方法。Pexpect 解决了死锁问题,允许您轻松地在后台运行进程,并提供简单的方法来在您的进程吐出预定义的字符串时进行回调,并且通常使与进程的交互更加容易。

于 2010-07-06T14:30:28.793 回答
6

考虑到“我不必等待它返回”,最简单的解决方案之一是:

subprocess.Popen( \
    [path_to_executable, arg1, arg2, ... argN],
    creationflags = subprocess.CREATE_NEW_CONSOLE,
).pid

但是...从我读到的内容来看,这不是“完成此类事情的正确方法”,因为subprocess.CREATE_NEW_CONSOLE标志会带来安全风险。

这里发生的关键事情是subprocess.CREATE_NEW_CONSOLE用于创建新的控制台和.pid(返回进程 ID,以便您以后可以根据需要检查程序),以便不等待程序完成其工作。

于 2017-08-06T11:53:19.057 回答
3

我在尝试使用 Python 中的 s3270 脚本软件连接到 3270 终端时遇到了同样的问题。现在我正在用我在这里找到的一个 Process 子类来解决这个问题:

http://code.activestate.com/recipes/440554/

这是从文件中获取的样本:

def recv_some(p, t=.1, e=1, tr=5, stderr=0):
    if tr < 1:
        tr = 1
    x = time.time()+t
    y = []
    r = ''
    pr = p.recv
    if stderr:
        pr = p.recv_err
    while time.time() < x or r:
        r = pr()
        if r is None:
            if e:
                raise Exception(message)
            else:
                break
        elif r:
            y.append(r)
        else:
            time.sleep(max((x-time.time())/tr, 0))
    return ''.join(y)

def send_all(p, data):
    while len(data):
        sent = p.send(data)
        if sent is None:
            raise Exception(message)
        data = buffer(data, sent)

if __name__ == '__main__':
    if sys.platform == 'win32':
        shell, commands, tail = ('cmd', ('dir /w', 'echo HELLO WORLD'), '\r\n')
    else:
        shell, commands, tail = ('sh', ('ls', 'echo HELLO WORLD'), '\n')

    a = Popen(shell, stdin=PIPE, stdout=PIPE)
    print recv_some(a),
    for cmd in commands:
        send_all(a, cmd + tail)
        print recv_some(a),
    send_all(a, 'exit' + tail)
    print recv_some(a, e=0)
    a.wait()
于 2009-06-06T10:07:22.427 回答
1

这里有几个答案,但没有一个能满足我的以下要求:

  1. 我不想等待命令完成或用子进程输出污染我的终端。

  2. 我想使用重定向运行 bash 脚本。

  3. 我想在我的 bash 脚本中支持管道(例如find ... | tar ...)。

满足上述要求的唯一组合是:

subprocess.Popen(['./my_script.sh "arg1" > "redirect/path/to"'],
                 stdout=subprocess.PIPE, 
                 stderr=subprocess.PIPE,
                 shell=True)
于 2020-01-15T08:43:47.263 回答