[英]Why does my Perl script not do anything if I invoke with Popen immediately followed by wait or sleep from 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調用之后立即使用Popen.wait(),Popen.communicate()或什至time.sleep(),則不會執行Perl腳本。 例如:
command = "ldapadder " + filename
args = shlex.split(command)
with open(os.devnull, 'w') as proc:
popen_result = Popen(args, stdout=proc)
time.sleep(5)
上面的代碼不執行任何操作--- Perl腳本未執行,即使我通過PIPE打印了Popen的stderr和stdout,內容也為空/空白。 在沒有os.devnull的情況下也做了同樣的事情,以確保獲得輸出,但是什么也沒有發生。
我已經嘗試了至少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腳本在獨立運行時確實會拋出消息和錯誤。
這是Python 2.6,我已經用subprocess.call()嘗試了相同類型的變體---一樣。
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")
運行:
$ python2.6 the_script.py
並檢查logfile
。 您可以在the_script.py
仍在運行時執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.