首页 > 解决方案 > Python:subprocess.call 和变体对于特定应用程序从执行的 .py 中失败,但不是从 CLI 中的 python

问题描述

我在这里有一个奇怪的问题 - 我有一个尝试从 python 启动的应用程序,但是从 .py 脚本中启动它的所有尝试都失败了,没有任何可辨别的输出。在 VSCode 调试器中进行测试。这里有一些额外的奇怪之处:

  1. 当我将 notepad.exe 换成 .py 而不是我的目标应用程序路径时,记事本启动正常。
  2. 当我从 CLI 逐行运行脚本时(首先启动 python,然后键入接下来的 4-5 行 Python),脚本按预期工作。

例子:

#This works in the .py, and from the CLI

import subprocess

cmd = ['C:\\Windows\\system32\\notepad.exe', 'C:\\temp\\myfiles\\test_24.xml']
pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
pipe.wait()
print(pipe)
#This fails in the .py, but works ok when pasted in line by line from the CLI

import subprocess

cmd = ['C:\\temp\\temp_app\\target_application.exe', 'C:\\temp\\myfiles\\test_24.xml']
pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
pipe.wait()
print(pipe)

运行 .py 时结果是没有输出

我尝试了其他几种变体,包括以下几种:

import subprocess

tup = 'C:\\temp\\temp_app\\target_application.exe C:\temp\test\test_24.xml'

proc = subprocess.Popen(tup)
proc.wait()
(stdout, stderr) = proc.communicate()

print(stdout)
if proc.returncode != 0:
    print("The error is: " + str(stderr))
else:
    print("Executed: " + str(tup))

结果:

None
The error is: None
1.082381010055542

现在这个方法表明存在错误,因为我们返回的不是 0 并打印“错误是:无”,这是因为 stderror 是“无”。那么 - 它是否抛出错误而不给出错误?标准输出也报告“无”。

所以,让我们试试 check_call 看看会发生什么:

print("Trying check_call")
    try:
        subprocess.check_call('C:\\temp\\temp_app\\target_application.exe C:\\temp\\test\\test_24.xml', shell=True)
    except subprocess.CalledProcessError as error:
        print(error)

结果:

Trying check_call
Command 'C:\temp\temp_app\target_application.exe C:\temp\test\test_24.xml' returned non-zero exit status 1.

我还尝试了 subprocess.run,尽管它缺少我希望使用的等待过程。

import subprocess

tup = 'C:\\temp\\temp_app\\target_application.exe C:\temp\test\test_24.xml'

proc = subprocess.run(tup, check=True)
proc.wait()
(stdout, stderr) = proc.communicate()

print(stdout)
if proc.returncode != 0:
    print("The error is: " + str(stderr))
else:
    print("Executed: " + str(tup))

什么原因可能值得追究,或者尝试捕捉错误的其他方法可能在这里起作用?我不知道如何将“`”解释为错误结果。

标签: pythonpython-3.xsubprocess

解决方案


推荐阅读