在Python中同时运行外部程序

gar*_*ary 1 python concurrency subprocess

我想知道如何以这样的方式调用外部程序,允许用户在Python程序运行时继续与我的程序的UI(使用tkinter构建,如果重要)进行交互.程序等待用户选择要复制的文件,因此在外部程序运行时,他们仍然可以选择和复制文件.外部程序是Adobe Flash Player.

也许一些困难是因为我有一个线程的"工人"类?它会在复制时更新进度条.即使Flash Player处于打开状态,我也希望更新进度条.

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

    def run_clip():
        flash_filepath = "C:\\path\\to\\file.exe"
    
        # halts UI until flash player is closed...
        subprocess.call([flash_filepath])              
    
    Run Code Online (Sandbox Code Playgroud)
  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))
    
    Run Code Online (Sandbox Code Playgroud)

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

Mag*_*off 8

您只需要继续阅读有关子进程模块的内容,特别是有关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()
Run Code Online (Sandbox Code Playgroud)

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