【发布时间】:2012-10-11 20:28:07
【问题描述】:
由于某种原因,Popen 在调用 Powershell 脚本后无法退出并且命令的输出不是动态的。
我是否在代码中遗漏了什么:
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)
【问题讨论】:
-
出于好奇,您为什么在这里使用
os._exit()而不是sys.exit()? -
恐怕没有理由只是习惯的力量。我知道我应该使用正确的 sys.exit() 方式,但我用来退出脚本的第一个示例是 os._exit()。
-
好吧,使用
_exit()确实不清理东西。它不会刷新缓冲区等。您通常确实希望清理一些东西,因此最好调用sys.exit()。
标签: python powershell subprocess popen