gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:56:12 24 4
gpt4 key购买 nike

如何让 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com