2012-10-11 89 views
1

由于某些原因,在调用Powershell脚本并且命令的输出不是动态后,Popen无法退出。Python Popen冻结

我思念的东西代码:

sCmd = "powershell -file somefile.ps1" 
process = subprocess.Popen(sCmd.strip(), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 

while True: 
    p = process.communicate() 
    sys.stdout.write(p[0]) 
    sys.stderr.write(p[1]) 

    sys.stdout.flush() 
    if(len(p[0]) == 0 and isinstance(process.poll(), int)): 
     break 

if(process.wait() != 0): 
    os._exit(1) 
+0

出于好奇,你为什么在这里使用'os._exit()'而不是'sys.exit()'? –

+0

没有理由只是习惯性的恐惧。我知道我应该使用sys.exit()的正确方式,但我用来退出脚本的第一个例子是os._exit()。 –

+1

那么,使用'_exit()'不*清理东西了。它不会刷新缓冲区等。通常情况下,您希望清理所有内容,因此改为调用'sys.exit()'更好。 –

回答

2

确认您的PowerShell命令实际上是退出正确。一个悬而未决的powershell过程很容易成为这个原因。

另外你也不应该有shell=True。这是一个巨大的安全风险。这也可能是为什么这个过程悬而未决。如果你的PowerShell脚本不能运行,除非shell=True然后修复这将是一个重点的好地方。