2012-02-14 47 views
1

我想知道如何以這樣的方式調用外部程序,以便在Python程序運行時允許用戶繼續與我的程序的UI(使用tkinter構建,如果它很重要)進行交互。程序等待用戶選擇要複製的文件,因此在外部程序運行時,它們仍應能夠選擇和複製文件。外部程序是Adobe Flash Player。在Python中同時運行外部程序

也許一些困難是由於我有一個線程「工人」類的事實?它在複製時更新進度條。即使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])    
    
  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?如果是這樣,有沒有更好的方法來調用外部程序?提前致謝。

回答

7

你只需要繼續閱讀關於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)進行交互。

+0

太好了,'child = subprocess.Popen'確實有效。我必須更熟悉模塊的方法,但感謝使用'wait'的信息。 – gary 2012-02-14 16:27:13