gpt4 book ai didi

Python:Popen - 等待主进程,但不等待后台子进程

转载 作者:行者123 更新时间:2023-12-01 05:02:08 27 4
gpt4 key购买 nike

我在 Unix 中工作,我有一个“通用工具”,可以在后台加载另一个进程(GUI 实用程序),然后退出。

我使用 Popenproc.communicate() 方法从 Python 脚本调用我的“通用工具”。

我的“通用工具”运行约 1 秒,在后台加载 GUI 进程并立即退出。

问题是 proc.communicate() 继续等待进程,尽管它已经终止。我必须手动关闭 GUI(这是在 BG 上运行的子进程),因此 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...'

最佳答案

不要使用沟通。通信被明确设计为等待进程的标准输出关闭。据推测,perl 不会关闭标准输出,因为它将它保持打开状态以供其自己的子进程写入。

您也并不真正需要使用 Popen,因为您并没有真正使用它的功能。也就是说,您创建管道,然后使用您自己的消息重新打印到标准输出。而且看起来您根本不需要 shell。

尝试使用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

关于Python:Popen - 等待主进程,但不等待后台子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25848265/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com