我试图在新窗口中运行.bat文件(充当模拟器),因此它必须始终在后台运行.我认为创建一个新流程是我唯一的选择.基本上,我希望我的代码做这样的事情:
def startSim:
# open .bat file in a new window
os.system("startsim.bat")
# continue doing other stuff here
print("Simulator started")
我在Windows上,所以我不能做os.fork.
解决方法:
使用subprocess.Popen(未在Windows上测试,但应该有效).
import subprocess
def startSim():
child_process = subprocess.Popen("startsim.bat")
# Do your stuff here.
# You can terminate the child process after done.
child_process.terminate()
# You may want to give it some time to terminate before killing it.
time.sleep(1)
if child_process.returncode is None:
# It has not terminated. Kill it.
child_process.kill()
编辑:您也可以使用os.startfile(仅限Windows,未经过测试).
import os
def startSim():
os.startfile("startsim.bat")
# Do your stuff here.
标签:python,subprocess,process,batch-file,background
来源: https://codeday.me/bug/20190530/1186894.html