在Python中并发运行外部程序

1 投票
1 回答
3121 浏览
提问于 2025-04-17 13:01

我想知道怎么调用一个外部程序,这样用户在我的程序界面(用tkinter做的,如果这有关系的话)运行时,仍然可以继续操作。我的程序需要用户选择要复制的文件,所以在外部程序运行时,他们应该还能选择和复制文件。这个外部程序是Adobe Flash Player。

也许问题的一部分是因为我有一个线程“工作者”类?它在复制文件时更新进度条。我希望即使Flash Player打开,进度条也能更新。

  1. 我试过使用subprocess模块。程序可以运行,但它会阻止用户在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上?如果是的话,有没有更好的方法来调用这个外部程序?提前谢谢!

1 个回答

8

你只需要继续阅读关于 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)与子进程的输入和输出流进行交互。

撰写回答