python - Python:subprocess.call 和变体对于特定应用程序从执行的 .py 中失败,但不是从 CLI 中的 python
问题描述
我在这里有一个奇怪的问题 - 我有一个尝试从 python 启动的应用程序,但是从 .py 脚本中启动它的所有尝试都失败了,没有任何可辨别的输出。在 VSCode 调试器中进行测试。这里有一些额外的奇怪之处:
- 当我将 notepad.exe 换成 .py 而不是我的目标应用程序路径时,记事本启动正常。
- 当我从 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))
什么原因可能值得追究,或者尝试捕捉错误的其他方法可能在这里起作用?我不知道如何将“`”解释为错误结果。
解决方案
推荐阅读
- php - 如何验证该值是否已存在。PHP
- php - 使用 ZendServer 连接到外部 DB2
- python - 如何向networkx散景图添加分类图例
- python -
- python - Python - 单个 for 循环,计算以下 to_analyze 中每行的最大、最小和平均字数
- html - 文字太小而无法阅读(移动设计)
- xamarin.forms - Xamarin 表单:点击和双击
- mysql - sqoop如何在增量导入中导入固定数量的行?
- php - Bootstrap 无法在 Laravel Blade 中正确显示
- python - 没有名为“资源”的模块在 Windows 上安装 Apache Spark