![](/img/trans.png)
[英]Cannot get exit code when running subprocesses in python using Popen and start /wait
[英]Python: Popen - wait for main process, but not for background subprocesses
我在Unix上工作,我有一個“通用工具”,可在后台加載另一個進程(GUI實用程序)並退出。
我把我的“通用工具”從一個Python腳本,使用POPEN和proc.communicate()
方法。
我的“通用工具”運行了大約1秒鍾, 在后台加載了GUI進程並立即退出。
問題在於, proc.communicate()
已經終止,但它繼續等待該過程。 我必須手動關閉GUI(這是在BG上運行的子proc.communicate()
),因此proc.communicate()
返回。
如何解決呢?
一旦主進程終止,我需要proc.communicate()
返回,而不是等待在后台運行的子進程...
謝謝!!!
添加一些代碼片段:
我的“通用工具”最后的主線 (用Perl編寫):
if ($args->{"gui"}) {
my $script_abs_path = abs_path($0);
my $script_dir = dirname($script_abs_path);
my $gui_util_path = $script_dir . "/bgutil";
system("$gui_util_path $args->{'work_area'} &");
}
return 0;
我的Python腳本運行“常規工具” :
cmd = PATH_TO_MY_GENERAL_TOOL
proc = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
stdout, dummy = proc.communicate()
exit_code = proc.returncode
if exit_code != 0:
print 'The tool has failed with status: {0}. Error message is:\n{1}'.format(exit_code, stdout)
sys.exit(1)
print 'This line is printed only when the GUI process is terminated...'
不要使用communicate
。 明確設計了Communicate,以等待進程的標准輸出關閉。 大概perl不會關閉stdout,因為它正在打開以供其自己的子進程寫入。
您也不需要使用Popen
因為您實際上並沒有使用它的功能。 也就是說,您創建管道,然后使用您自己的消息將其重新打印到標准輸出。 而且看起來根本不需要外殼。
嘗試使用subprocess.call
甚至subprocess.check_call
。
例如。
subprocess.check_call(cmd)
如果進程返回的非零退出代碼,則check_call
會引發異常(包含退出代碼),因此無需檢查返回值。 流程的輸出直接寫入控制終端-無需重定向輸出。
最后,如果cmd
是可執行文件及其參數的路徑的組合,則使用shlex.split
。
例如。
cmd = "echo whoop" # or cmd = "ls 'does not exist'"
subprocess.check_call(shlex.split(cmd))
測試示例代碼:
mypython.py
import subprocess, shlex
subprocess.check_call(shlex.split("perl myperl.pl"))
print("finishing top level process")
myperl.pl
print "starting perl subprocess\n";
my $cmd = 'python -c "
import time
print(\'starting python subprocess\')
time.sleep(3);
print(\'finishing python subprocess\')
" &';
system($cmd);
print "finishing perl subprocess\n";
輸出為:
$ python mypython.py
starting perl subprocess
finishing perl subprocess
finishing top level process
$ starting python subprocess
finishing python subprocess
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.