2016-09-17 114 views
1

我想做一個後臺進程,顯示file與外部viewer。當進程停止時,它應該刪除文件。 下面這段代碼做我想做的事情,但它很醜,我想有一種更習慣的方式。 如果它甚至與操作系統無關,那將是完美的。popen完成後做些什麼

subprocess.Popen(viewer + ' ' + file + ' && rm ' + file, shell=True) 

回答

2

使用subprocess.call()打開瀏覽器並查看文件究竟會做到這一點。隨後,運行命令刪除該文件。

如果您希望腳本,而正在運行的進程繼續進行,使用threading

一個例子:

from threading import Thread 
import subprocess 
import os 

def test(): 
    file = "/path/to/somefile.jpg" 
    subprocess.call(["eog", file]) 
    os.remove(file) 

Thread(target = test).start() 
# the print command runs, no matter if the process above is finished or not 
print("Banana") 

這將不正是你的描述:

  • 打開文件與eog(查看器),等待它完成(關閉eog)並刪除該文件。
  • 在此期間繼續劇本並打印「香蕉」。
+0

非常感謝您的回答。但在這種情況下,它不會放在後臺,我無法工作。 – mcocdawc

+0

背景是什麼意思?如果您希望腳本繼續,請使用'Threading' –

+0

是的,我希望腳本繼續。我可能錯過了精確的詞彙來嚴格定義它。如果我要在Linux終端上工作,我需要''''nohup bash -c'command1 && command2'&''的行爲。 「Threading」真的有必要嗎? – mcocdawc

相關問題