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