Python subprocess.Popen 用于多个 python 脚本
Python subprocess.Popen for multiple python scripts
我正在尝试了解 Popen 方法。我目前在同一目录中有三个 python 文件:test.py、hello.py 和 bye.py。 test.py 是包含 subprocess.Popen 方法的文件,而 hello 和 bye 是简单的 hello world 和 goodbye world 文件,即它们只包含一个打印。
如果我这样做:
import subprocess
from subprocess import PIPE
tst = subprocess.Popen(["python", "hello.py"], stdout=PIPE, stderr=PIPE)
(out,err) = tst.communicate()
一切似乎都工作正常,在 shell 中为 hello.py 获取正确的 "Hello World" 打印并为 bye.py 和 shell 执行相同的操作按原样打印 "GoodBye World"。
当我想 运行 这两个文件时,问题就开始了,
import subprocess
from subprocess import PIPE
tst = subprocess.Popen(["python", "hello.py", "python", "bye.py"], stdout=PIPE, stderr=PIPE)
(out,err) = tst.communicate()
这只会 return 打印第一个 .py 文件,然后 return
[WinError 2 ] The system cannot find the file specified
如果我也删除第二个 "python",就会发生这种情况。为什么会这样?
This will happen if I also remove the second "python". Why is this happening?
运行
subprocess.Popen(["python", "hello.py", "python", "bye.py"]
类似于运行
$ python hello.py python bye.py
这并没有多大意义,因为这被解释为将参数 hello.py python bye.py
传递给 python
。
这是第 1 部分,关于您的问题 "I am trying to understand the Popen method."
在不知道您实际想要做什么的情况下,通过这个概念验证,您有几个选择;按顺序调用多个 Popen()
,或使用带有 shell=True
的分号,但请务必考虑其中的 security implications:
# This will also break on Windows
>>> import subprocess as sp
>>> sp.check_output("python -V ; python -V", shell=True)
b'Python 3.8.2\nPython 3.8.2\n'
我正在尝试了解 Popen 方法。我目前在同一目录中有三个 python 文件:test.py、hello.py 和 bye.py。 test.py 是包含 subprocess.Popen 方法的文件,而 hello 和 bye 是简单的 hello world 和 goodbye world 文件,即它们只包含一个打印。
如果我这样做:
import subprocess
from subprocess import PIPE
tst = subprocess.Popen(["python", "hello.py"], stdout=PIPE, stderr=PIPE)
(out,err) = tst.communicate()
一切似乎都工作正常,在 shell 中为 hello.py 获取正确的 "Hello World" 打印并为 bye.py 和 shell 执行相同的操作按原样打印 "GoodBye World"。
当我想 运行 这两个文件时,问题就开始了,
import subprocess
from subprocess import PIPE
tst = subprocess.Popen(["python", "hello.py", "python", "bye.py"], stdout=PIPE, stderr=PIPE)
(out,err) = tst.communicate()
这只会 return 打印第一个 .py 文件,然后 return
[WinError 2 ] The system cannot find the file specified
如果我也删除第二个 "python",就会发生这种情况。为什么会这样?
This will happen if I also remove the second "python". Why is this happening?
运行
subprocess.Popen(["python", "hello.py", "python", "bye.py"]
类似于运行
$ python hello.py python bye.py
这并没有多大意义,因为这被解释为将参数 hello.py python bye.py
传递给 python
。
这是第 1 部分,关于您的问题 "I am trying to understand the Popen method."
在不知道您实际想要做什么的情况下,通过这个概念验证,您有几个选择;按顺序调用多个 Popen()
,或使用带有 shell=True
的分号,但请务必考虑其中的 security implications:
# This will also break on Windows
>>> import subprocess as sp
>>> sp.check_output("python -V ; python -V", shell=True)
b'Python 3.8.2\nPython 3.8.2\n'