如何在 Python 3.7 中向子进程添加新的 shell 命令?

How to add new shell commands to a subprocess in Python 3.7?

我正在尝试找到一种方法来将命令添加到 Python 3.7 中已打开的 shell 进程的标准输入。但我似乎找不到解决方案。

我尝试了很多解决方案都没有成功。

p1 = subprocess.Popen('pwd > test', shell=True, stdin=PIPE, text=True) # works

p1.communicate('pwd > test1')                                    # doesn't work
p1.communicate(input='pwd > test2')                              # doesn't work
p1.communicate('pwd > test3\n')                                  # doesn't work
p1.stdin.write('pwd > test4')                                    # doesn't work
p1.stdin.write('pwd > test5\n')                                  # doesn't work

如有任何帮助,我们将不胜感激。

如果你的命令本身是一个 shell,你可以实现这一点,但如果它是一个退出的命令(如 pwd 所做的),或者将 stdin 作为自己的输入获取的命令,则不能.以下应该有效 - 请注意,您不需要 shell=True,并且您需要将写入刷新到 stdin:

from subprocess import Popen, PIPE

p1 = subprocess.Popen('bash', stdin=PIPE, text=True)

p1.stdin.write("xeyes\n")
p1.stdin.flush()

您可以通过以下操作更密切地跟踪这一点:

p1 = subprocess.Popen('pwd', shell=True, stdin=PIPE, text=True)
p1.pid

然后查看shell中的进程id:

ps -ef |grep <PID>

你会看到:sh <defunct> 这表明该进程已停止并且不再可以与之通信(但仍然显示为 python 持有对它的引用,当python 退出)。

如果您尝试写入标准输入,您将得到:

BrokenPipeError: [Errno 32] Broken pipe