【发布时间】:2014-04-14 18:56:57
【问题描述】:
我的 python 代码使用子进程通过 shell 调用“ifconfig”并使用“>”将输出写入文本文件。当子进程完成并返回成功时,我读取了输出文件。我定期执行此操作以监视网络状态,但有时我无法打开输出文件。我刚刚读到 Popen 有 stdout 和 stderr 的可选参数,这可能更安全/更好地支持,但我很好奇为什么我当前的版本失败。我的代码如下。我的库中有一些对象和宏没有解释,但我认为代码对于这个问题仍然足够清晰。
为什么打开输出文件偶尔会失败?子进程返回时文件是否可能尚未准备好?有什么方法可以保证它可以打开?
# Build command line expression.
expr = 'ifconfig' + ' >' + outputFile + ' 2>&1'
try:
# Execute command line expression.
p = subprocess.Popen(expr, shell=True)
except:
Error("Unable to open subprocess.")
if(p is None):
Error("Unable to create subprocess.")
# Wait until command line expression has been executed.
wait = Wait.Wait(Constants.MIN_TIME_TO_QUERY_NETWORK_INFO, Constants.MAX_TIME_TO_QUERY_NETWORK_INFO)
#Execute command then wait for timeout.
if (wait.StopUntilCondition(operator.ne, (p.poll,), None, True)):
p.kill()
Error("Get subnet mask subprocess timed out.")
if(not p.poll() == 0):
Error("Failed to get network information from operating system.")
Warning("About to read output file from get subnet mask...")
# Read temporary output file.
f = open(outputFile, "r")
networkInfo = f.read()
f.close()
【问题讨论】:
-
我想知道:对
Popen的调用是等待ifconfig退出,还是等待重定向完成? -
不相关:不要:
if(not p.poll() == 0):,不要使用if p.poll() != 0:,尽管您应该在这里使用p.wait() -
@J.F.Sebastian 感谢关于“not ==" vs "!=" 的注释。我从来没有考虑过,现在知道有区别。关于“if(p.poll() != 0)”,文档说“p.poll()”检查进程是否已终止(在完成之前返回 None,我的 wait.StopUntilCondition 正在等待)和“p.poll()”。 wait()" 等待直到进程终止。看起来一样,但无论如何我可能会选择你的“check_output”答案。谢谢!
-
请不要使用不必要的括号(Python 不是 C)。
p.wait()(与p.poll()不同)断言该过程已完成。 -
@J.F.Sebastian 会在括号里做...很难改掉这个习惯。至于 p.poll() 与 p.wait(),文档似乎没有具体说明,但我相信你的话,某处埋藏着一个断言。 p.wait 的文档说“等待子进程终止。”和 p.poll “检查子进程是否已终止。”。
标签: python subprocess