如何从一个 subprocess.Popen 命令同步运行多个命令? [英] How to run multiple commands synchronously from one subprocess.Popen command?

查看:327
本文介绍了如何从一个 subprocess.Popen 命令同步运行多个命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用相同的子进程命令依次执行任意数量的命令?

Is it possible to execute an arbitrary number of commands in sequence using the same subprocess command?

我需要每个命令在执行之前等待前一个命令完成,并且我需要它们都在同一个会话/shell 中执行.我还需要它在 Python 2.6、Python 3.5 中工作.我还需要 subprocess 命令在 Linux、Windows 和 macOS 中工作(这就是为什么我在这里只使用 echo 命令作为示例).

I need each command to wait for the previous one to complete before executing and I need them all to be executed in the same session/shell. I also need this to work in Python 2.6, Python 3.5. I also need the subprocess command to work in Linux, Windows and macOS (which is why I'm just using echo commands as examples here).

请参阅下面的非工作代码:

import sys
import subprocess

cmds = ['echo start', 'echo mid', 'echo end']

p = subprocess.Popen(cmd=tuple([item for item in cmds]),
                     stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

for line in iter(p.stdout.readline, b''):
    sys.stdout.flush()
    print(">>> " + line.rstrip())

如果这是不可能的,我应该采用哪种方法来在同一个会话/shell 中以同步顺序执行我的命令?

If this is not possible, which approach should I take in order to execute my commands in synchronous sequence within the same session/shell?

推荐答案

如果你想在同一个 session/shell 中一个接一个地执行多个命令,你必须启动一个 shell 并喂它使用所有命令,一次一个,后跟一个新行,最后关闭管道.如果某些命令不是真正的进程而是 shell 命令,例如可以更改 shell 环境的命令,这是有道理的.

If you want to execute many commands one after the other in the same session/shell, you must start a shell and feed it with all the commands, one at a time followed by a new line, and close the pipe at the end. It makes sense if some commands are not true processes but shell commands that could for example change the shell environment.

在 Windows 下使用 Python 2.7 的示例:

Example using Python 2.7 under Windows:

encoding = 'latin1'
p = subprocess.Popen('cmd.exe', stdin=subprocess.PIPE,
             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for cmd in cmds:
    p.stdin.write(cmd + "\n")
p.stdin.close()
print p.stdout.read()

要在 Linux 下运行此代码,您必须将 cmd.exe 替换为 /bin/bash,并且可能将编码更改为 utf8.

To have this code run under Linux, you would have to replace cmd.exe with /bin/bash and probably change the encoding to utf8.

对于 Python 3,您必须对命令进行编码并可能对它们的输出进行解码,并在打印时使用括号.

For Python 3, you would have to encode the commands and probably decode their output, and to use parentheses with print.

注意:这只适用于很少的输出.如果在关闭 stdin 管道之前有足够的输出来填充管道缓冲区,则此代码将死锁.更可靠的方法是让第二个线程读取命令的输出以避免该问题.

Beware: this can only work for little output. If there was enough output to fill the pipe buffer before closing the stdin pipe, this code would deadlock. A more robust way would be to have a second thread to read the output of the commands to avoid that problem.

这篇关于如何从一个 subprocess.Popen 命令同步运行多个命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆