为什么我的Perl脚本没有做任何事情,如果我用Popen立即调用,然后从Python调用wait或sleep?

2024-09-30 02:19:14 发布

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

我用Popen调用一个Perl脚本。以下代码有效:

command = "ldapadder " + filename  
args = shlex.split(command)
with open(os.devnull, 'w') as proc:
   popen_result = Popen(args, stdout=proc)

“ldapadder”是一个可执行的Perl脚本。(是的,我知道Python的LDAP模块,现在还不是我们的选择)

但是,如果我试图使用波彭,等等(), 大众传播(),甚至时间。睡觉()在Popen调用之后,Perl脚本不会立即执行。例如:

^{pr2}$

上面的代码不执行任何操作——Perl脚本不执行,即使我通过管道打印Popen的stderr和stdout,内容也是空的。做了同样的事没有德夫努尔操作系统为了确保我能得到输出,但什么也没发生。在

我尝试过至少10种其他的变体,包括:

command = "ldapadder " + filename  
args = shlex.split(command)
popen_result = Popen(args, stdout=PIPE, stderr=PIPE)
stdout, stderr = popen_result.communicate()
print stdout;
print stderr;

以及:

command = "ldapadder " + filename  
args = shlex.split(command)
popen_result = Popen(args)
popen_result.wait()

对于以上两个片段,什么都不会发生。Perl脚本似乎根本不执行。考虑到Perl脚本在被Popen调用并等待一段时间时不会输出标准输出或错误,我不确定如何才能获得更多关于出错的信息。澄清一下,Perl脚本在独立运行时确实会抛出消息和错误。在

这是Python2.6,我已经用subprocess.call()——同样的事情。在


Tags: 代码脚本stderrstdoutargsprocresultfilename
1条回答
网友
1楼 · 发布于 2024-09-30 02:19:14

Popen()启动新的子进程。如果返回,则进程已启动。检查是否在代码中静默忽略异常。在

#!/usr/bin/env python
import logging
import subprocess

# log to a file in case `ldapadder` corrupts terminal
logging.basicConfig(format="%(asctime)-15s %(message)s", datefmt="%F %T",
                    filename='logfile', level=logging.DEBUG)
p = logging.getLogger(__name__).info

p("before ldapadder")
try:
    proc = subprocess.Popen(["ldapadder", filename], close_fds=True)
    p("after Popen")
    proc.wait()
    p("after wait")
finally:
    p("after ldappedder")

运行它:

^{pr2}$

然后检查logfile。您可以在the_script.py仍在运行时执行此操作。在

相关问题 更多 >

    热门问题