【问题标题】:Python subprocess.Popen for multiple python scriptsPython subprocess.Popen 用于多个 python 脚本
【发布时间】:2020-05-28 15:40:24
【问题描述】:

我正在尝试理解 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()

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

[WinError 2 ] The system cannot find the file specified

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

【问题讨论】:

  • 如果你知道一个作品为什么不把它分成两个连续的电话?
  • 如果你真的想同时调用两个"python",你可以尝试在第二个"python"之前添加一个分号。

标签: python subprocess


【解决方案1】:

如果我还删除第二个“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,但请务必考虑其中的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'

【讨论】:

    猜你喜欢
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    相关资源
    最近更新 更多