在Python运行脚本的同时执行可执行GUI

0 投票
3 回答
769 浏览
提问于 2025-04-18 16:53

我遇到了一个可能很简单的问题需要解决。简单来说,我想打开一个 .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 文件被关闭。我希望代码能够在 .exe 文件打开的时候就开始运行。

提前谢谢你们的帮助。

3 个回答

0

感谢大家的帮助。其实,问题还是存在的,最后我改用了os.startfile这个命令。之前用subprocess.call和os.system的时候,Python程序一直卡住,甚至用了线程命令也没用。这可能是因为我想打开的那个图形界面(GUI)比较特殊。

总之,我用了os.startfile,然后在里面加了一个测试命令,用来检查那个程序是否还在运行。当这个函数判断程序不再运行时,就调用sys.exit()来关闭脚本。

再次感谢大家!

0

你可以试着在Windows系统上使用DETACHED_PROCESS这个标志。

DETACHED_PROCESS = 0x00000008

process_id = subprocess.Popen([sys.executable, "software.exe"],creationflags=DETACHED_PROCESS).pid
1

我在这个示例代码中看到的唯一错误是,你没有在 run_spm 函数里把 SPM_RUNNING 声明为全局变量:

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 函数里把 SPM_RUNNING 设置为 False 时,这个变量只是在局部范围内创建;全局的 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

这正是你所期待的结果。

撰写回答