[英]Running an executable GUI from Python while running script in background
我有一个潜在的简单问题需要解决。 本质上,我试图打开一个.exe文件(这是用于机器学习分析的统计软件包)。 当用户在包中创建模型和仿真时,我希望Python不断搜索输出文件以进行进一步的处理。
到目前为止,这是我的代码:
import threading
import subprocess
from time import sleep
SPM_RUNNING = False
def run_spm():
subprocess.call("SOFTWARE.EXE")
SPM_RUNNING = False # When SPM finished.
SPM_RUNNING = True
t = threading.Thread(target=run_spm)
t.start()
while SPM_RUNNING:
# This will be replaced with the actual manipulations
print "This program is running"
问题是.exe文件打开了,但是在关闭.exe文件之后,代码的下一部分才继续运行。 我希望代码在打开的情况下运行。
提前致谢。
我在示例代码中看到的唯一错误是,你没有申报SPM_RUNNING
作为内部全局run_spm
功能:
import threading
import subprocess
from time import sleep
SPM_RUNNING = False
def run_spm():
global SPM_RUNNING # You forgot this.
subprocess.call("SOFTWARE.EXE")
SPM_RUNNING = False # When SPM finished.
SPM_RUNNING = True
t = threading.Thread(target=run_spm)
t.start()
while SPM_RUNNING:
# This will be replaced with the actual manipulations
print "This program is running"
没有该声明,您在run_spm
设置为False
的SPM_RUNNING
变量仅在本地范围内创建; 全局SPM_RUNNING
不变。
除此之外,它看起来还不错。 我在Linux机器上制作了几乎相同的脚本:
import threading
import subprocess
from time import sleep
SPM_RUNNING = False
def run_spm():
global SPM_RUNNING
subprocess.call(["sleep", "10"])
SPM_RUNNING = False # When SPM finished.
SPM_RUNNING = True
t = threading.Thread(target=run_spm)
t.start()
while SPM_RUNNING:
print("running")
sleep(1)
print('done')
这是输出:
running
running
running
running
running
running
running
running
running
running
done
正是您所期望的。
在Windows上,您可以尝试传递DETACHED_PROCESS标志。
DETACHED_PROCESS = 0x00000008
process_id = subprocess.Popen([sys.executable, "software.exe"],creationflags=DETACHED_PROCESS).pid
感谢您的帮助。 实际上,问题仍然存在-最终工作是转移到os.startfile命令。 subprocess.call和os.system锁定了Python,即使使用threading命令也无法正常工作。 这可能是由于我试图打开的GUI的特殊性质。
无论如何-我使用了os.startfile,然后循环执行一个测试命令来查找正在运行的程序的实例。.当该函数确定该程序不再运行时,它将启动sys.exit()函数以关闭脚本。
再次感谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.