Skip to main content
 首页 » 编程设计

python之在 Python 中并发运行外部程序

2025年05月04日13me-sa

我想知道如何以允许用户在 Python 程序运行时继续与我的程序的 UI(使用 tkinter 构建,如果重要的话)进行交互的方式调用外部程序。该程序等待用户选择要复制的文件,因此当外部程序运行时,他们应该仍然能够选择和复制文件。外部程序是 Adob​​e Flash Player。

也许有些困难是因为我有一个线程化的“worker”类?它在复制时更新进度条。即使 Flash Player 打开,我也希望进度条能够更新。

  1. 我尝试了 subprocess 模块。该程序运行,但它会阻止用户使用 UI,直到 Flash Player 关闭。此外,复制似乎仍在后台进行,只是进度条在 Flash Player 关闭之前不会更新。

    def run_clip(): 
        flash_filepath = "C:\\path\\to\\file.exe" 
     
        # halts UI until flash player is closed... 
        subprocess.call([flash_filepath])               
    
  2. 接下来,我尝试使用 concurrent.futures 模块(反正我使用的是 Python 3)。由于我仍在使用 subprocess 来调用应用程序,因此这段代码的行为与上面的示例完全一样也就不足为奇了。

    def run_clip(): 
        with futures.ProcessPoolExecutor() as executor: 
        flash_filepath = "C:\\path\\to\\file.exe" 
        executor.submit(subprocess.call(animate_filepath)) 
    

问题是否在于使用subprocess?如果是这样,有没有更好的方法来调用外部程序?提前致谢。

请您参考如下方法:

您只需要继续阅读 subprocess模块,特别是关于Popen。

要同时运行后台进程,您需要使用subprocess.Popen:

import subprocess 
 
child = subprocess.Popen([flash_filepath]) 
# At this point, the child process runs concurrently with the current process 
 
# Do other stuff 
 
# And later on, when you need the subprocess to finish or whatever 
result = child.wait() 

您还可以通过 Popen 对象(在本例中为 child)的成员与子进程的输入和输出流进行交互。