python - 使用子进程启动 py.exe 的另一个实例 (Python)

标签 python subprocess

如何让 Python 使用子进程启动其自身的另一个实例?目前我有:

import subprocess
p = subprocess.Popen(["py.exe", "card game.py"])
returncode = p.wait()

但是,它只是在当前窗口中打开cardgame.py。

如何防止这种情况发生?

最佳答案

您可以通过使用 sys.executable 调用 subprocess.call 来启动另一个 python 实例

import sys
import subprocess

# this will block until the card game terminates
subprocess.call([sys.executable, 'card game.py'])

或使用subprocess.Popen

import sys
import subprocess

# this will not block
proc = subprocess.Popen(
    [sys.executable, 'card game.py'],
    stdout=subprocess.DEVNULL,  # if you skip these lines
    stderr=subprocess.DEVNULL,  # you must call `proc.communicate()`
)

# wait for the process to finish
proc.wait()

阅读subprocess文档。

关于python - 使用子进程启动 py.exe 的另一个实例 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49590684/

相关文章:

python - 从 pyobjc 2.2 降级到 pyobjc 2.0

python - 当在队列中启动多个线程时,哪个线程从堆栈中取出第一个

python - 如何在 Python 中启动一个独立运行的子进程,并在主进程关闭时继续运行?

python - 将变量传递给子流程调用

python - ffmpeg stdin 管道搜索

线程内的 Python 文件处理

python - 重置 python 解释器以进行日志记录

python - 使用 Raspberry Pi 和 Bluemix 的 IoT Python 应用程序 : Pushing the button doesn't work

Python子进程CREATE_NEW_CONSOLE Windows在kill()时未关闭

Python脚本,记录到屏幕和文件