【问题标题】:Python Popen freezingPython Popen 冻结
【发布时间】: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


【解决方案1】:

验证您的 powershell 命令实际上是否正确退出。挂起的 powershell 进程很容易导致此问题。

你也不应该有shell=True。这是一个巨大的安全风险。它也可能是为什么进程挂起的原因。如果您的 powershell 脚本除非shell=True 否则无法运行,那么修复它将是一个很好的关注点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-20
    • 2017-05-16
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    相关资源
    最近更新 更多