【发布时间】:2016-09-28 08:00:15
【问题描述】:
使用 Python 的 subprocess.call,我正在尝试调用一个 C 程序来读取磁盘上的输入文件,并创建多个输出文件。从终端运行 C 程序会得到预期的结果,但 subprocess.call 不会。
在最小示例中,程序应读取临时文件夹中的输入文件,并在同一文件夹中创建输出文件。输入和输出文件的位置和名称被硬编码到 C 程序中。
import subprocess
subprocess.call('bin/program.exe') # parses input file 'scratch/input.txt'
with open('scratch/output.txt') as f:
print(f.read())
这会返回:
FileNotFoundError: [Errno 2] No such file or directory: 'scratch/output.txt'
我做错了什么?
使用subprocess.check_output,我看不到任何错误。
编辑:
所以我看到涉及子进程工作目录。 C 可执行文件具有相对于 exe 的输入/输出硬编码路径(即,'../scratch/input.txt'),但 subprocess.call() 调用需要路径相对于 python 脚本,不是exe。这是出乎意料的,并且从终端调用 exe 会产生非常不同的结果。
【问题讨论】:
-
我会建议使用“导入命令”;使用它,您还将获得 C 程序的输出(您可以在 gcc 中以正常方式运行它),如果失败,状态代码将更改。例如。输出 = commands.getstatusoutput("gcc test.c")
-
@abhijeetmote
commands模块已被subprocess模块淘汰。
标签: python subprocess