使用管道时python子进程调用未终止

2024-04-26 07:14:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python2.6.5有一个奇怪的问题。如果我打电话

p = subprocess.Popen(["ifup eth0"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()

当接口eth0关闭时,python程序挂起。”p、 communicate()”需要一分钟或更长时间才能完成。如果之前接口打开,程序运行平稳。我从命令行手动测试了“ifupeth0”对于这两种情况,它的速度非常快。在

如果你知道问题出在哪里,我将非常感激。在

提前谢谢

编辑:

根据答案,我尝试了以下几点:

^{pr2}$

如果界面以前是启动的,则skcript运行平稳。但是,如果接口关闭,python将再次挂起。我也试过:

p = subprocess.Popen(["ifup", "eth0"], shell=False)
out, err = p.communicate()

一切都很快。因此,正如funktku所指出的,这可能确实与僵局有关。但是python文档中也提到python ref

Warning

This will deadlock when using stdout=PIPE and/or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that.

因此,不应该出现僵局。隐马尔可夫模型。。。以下是我在命令行上运行程序时的详细输出:

1例,接口eth0已启动:

ifup eth0
Interface eth0 already configured

2箱,前接口向下:

ifup eth0 
ssh stop/waiting
ssh start/running

因此,ifup命令生成两行输出,以防接口在之前关闭,否则生成一行输出。这是我注意到的唯一区别。但我怀疑这是问题的原因,因为“ls-ahl”会产生更多的输出行,并且运行得非常好。在

我还尝试过使用buffersize参数,但是没有成功,方法是将它设置为一些大值,比如4096。在

你有什么想法吗?原因是什么?或者这可能是python管道处理或ifup命令本身的一个bug?我真的要用旧的吗os.popen公司(cmd).read()????在

编辑2:

在os.popen公司(cmd).read()也遇到了同样的问题。你知道我如何在命令行上测试ifup的管道行为吗?在

我很感激你的每一个暗示,提前谢谢


Tags: to命令行程序编辑stderrstdoutshellout
3条回答

您应该查看subprocess.call方法下的warning。这可能是你问题的原因。在

警告

Like Popen.wait(), this will deadlock when using stdout=PIPE and/or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data.

/etc/network/if-up.d/ntpdate does not detach correctly

这就是为什么read()要等到fds(stdin/stdout/stderr)关闭。 您可以分离stdin/stderr/stdout(不要添加stdout=子流程.管道与Popen构造函数调用相同)。在

p = subprocess.Popen(["ifup", "eth0"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()

设置shell=False,您不需要它。在

试着运行这个代码,它应该可以工作。注意两个参数是如何在列表中独立的元素。在

相关问题 更多 >