Python 子进程.Popen 用于多个 python 脚本



我正在尝试理解Popen方法。我目前在同一个目录中有三个python文件:test.py,hello.py 和 bye.py。test.py 是包含子进程的文件。Popen 方法虽然 hello 和 bye 是简单的 hello 世界和再见世界文件,即它们只包含一个打印。

如果我这样做:

import subprocess
from subprocess import PIPE
tst = subprocess.Popen(["python", "hello.py"], stdout=PIPE, stderr=PIPE)
(out,err) = tst.communicate()

一切似乎都很好,在外壳中为 hello.py 获得正确的"Hello World"打印,并为外壳打印"GoodBye World"bye.py 做同样的事情。

当我想运行这两个文件时,问题就开始了,

import subprocess
from subprocess import PIPE
tst = subprocess.Popen(["python", "hello.py", "python", "bye.py"], stdout=PIPE, stderr=PIPE)
(out,err) = tst.communicate()

这将仅返回第一个.py文件的打印,然后返回

[WinError 2 ] The system cannot find the file specified

如果我也删除第二个"蟒蛇",就会发生这种情况。为什么会这样?

如果我也删除第二个"python",就会发生这种情况。为什么会这样?

运行

subprocess.Popen(["python", "hello.py", "python", "bye.py"]

类似于跑步

$ python hello.py python bye.py

这并没有多大意义,因为这被解释为将参数hello.py python bye.py传递给python

所以这是第 1 部分,关于你的问题"我试图理解 Popen 方法"。

在不知道你真正想用这个概念证明做什么的情况下,你有几个选择;按顺序调用多个Popen(),或者使用带有shell=True的分号,但一定要考虑它的安全隐患:

# This will also break on Windows
>>> import subprocess as sp
>>> sp.check_output("python -V ; python -V", shell=True)
b'Python 3.8.2nPython 3.8.2n'

最新更新