【问题标题】:Python popen wait command not behaving as expectedPython popen 等待命令未按预期运行
【发布时间】:2017-02-24 08:24:57
【问题描述】:

我有一个 PowerShell 脚本,它调用 API 并根据 POST 请求是否通过返回 0 或 99。我的 PowerShell 代码:

try
{
    Invoke-RestMethod -uri $url -Method Post -Body $body -ContentType 'application/json' -ErrorAction Stop

    return 0
}
catch
{
    return 99
}

这就是我从 Python 脚本调用脚本的方式:

req =    subprocess.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
                             '-ExecutionPolicy',
                             'Unrestricted',
                             './call.ps1',
                             param1, param2], cwd=os.getcwd())

    print("^^^^^^^")
    result = req.wait() #something is going wrong here
    print("****************")
    print(result)
  
    if result == 0:
        # do something
    else:
        # do something else

现在这就是问题所在。即使 POST 请求失败,“result”变量仍然是“0”而不是“99”。当我单独运行 PowerShell 脚本时,我可以看到它在 POST 请求失败时返回 99。所以问题似乎不在于 PowerShell 文件。

在调试 Python 文件时,这是我在控制台上看到的:(注意 Python 代码中打印语句的顺序)

^^^^^^^
99
****************
0

我不明白的一件事是,“99”在输出中做了什么?我什至没有打印“^^^^^”和“*****”之间的结果。那么如果PowerShell脚本返回99,为什么在“*****”之后变成0呢?

【问题讨论】:

    标签: python powershell popen


    【解决方案1】:

    req.wait() 将返回您运行的程序的退出代码。在这种情况下,power shell 返回正确的退出代码 0。它似乎只是打印出“99”,这就是您在输出中看到的。

    您可能想使用:

    out = subprocess.check_output(...)
    print out
    

    【讨论】:

      【解决方案2】:

      99 是 PowerShell 创建的输出,因为您使用了 return 而不是 exit。因此,脚本打印 99 并以退出代码 0 退出(这是 req.wait() 收到的内容)。此外,您的 PowerShell 命令行不是以实际从脚本返回正确退出代码的方式构建的,因此即使您使用 exit 而不是 return,该进程也只会在成功时返回 0 或在万一时返回 1一个错误。

      要让 PowerShell 返回脚本的退出代码,您需要自己返回退出代码

      powershell.exe -Command "&{.\call.ps1; exit $LASTEXITCODE}"
      

      或使用-File 参数调用脚本

      powershell.exe -File .\call.ps1
      

      要解决此问题,请将您的 PowerShell 代码更改为:

      try {
          Invoke-RestMethod -uri $url -Method Post -Body $body -ContentType 'application/json' -ErrorAction Stop
          exit 0
      } catch {
          exit 99
      }
      

      和你的 Python 代码:

      req = subprocess.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
            '-ExecutionPolicy', 'Unrestricted',
            '-File', './test.ps1',
            param1, param2], cwd=os.getcwd())
      
      print("^^^^^^^")
      result = req.wait()
      print("****************")
      print(result)
      

      【讨论】:

      • 非常感谢您的详细解释,Ansgar。现在我的文件完全按预期工作。老实说,我自己无法解决这个问题。再次感谢你:)
      猜你喜欢
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多