[英]Run external program concurrently in Python
我想知道如何以這樣一種方式調用外部程序,即允許用戶在Python程序運行時繼續與我的程序的UI(使用tkinter構建,如果需要的話)進行交互。 該程序等待用戶選擇要復制的文件,因此在外部程序運行時,他們仍然應該能夠選擇和復制文件。 外部程序是Adobe Flash Player。
也許有些困難是由於我有一個線程化的“工人”課? 復制時,它會更新進度條。 即使Flash Player打開,我也希望進度條能夠更新。
我嘗試了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])
接下來,我嘗試使用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
? 如果是這樣,是否有更好的方法來調用外部程序? 提前致謝。
您只需要繼續閱讀有關子流程模塊的信息,尤其是有關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
-object的成員(在本例中為child
)與子流程的輸入和輸出流進行交互。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.