Python:不写入输出文件的子进程

2024-04-18 00:41:46 发布

您现在位置:Python中文网/ 问答频道 /正文

使用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/输入文件'),但是subprocess.call()调用需要相对于python脚本的路径,而不是exe。这是意外的,并产生与从终端调用exe截然不同的结果。在


Tags: 文件路径程序txt文件夹终端编码input
1条回答
网友
1楼 · 发布于 2024-04-18 00:41:46
import os

subprocess.call('bin/program.exe') # parses input file 'scratch/input.txt'
if not os.path.isfile('scratch'):
    os.mkdir('scratch')
with open(os.path.join('scratch','output.txt'), 'w') as f:
    f.write('Your message')

你必须以模式打开文件。例如阅读。你需要加入os.path.join操作系统(). 在

如果文件夹和文件不存在,可以创建它们。但是没有什么可读的。如果你愿意的话,可以写在上面。在

相关问题 更多 >

    热门问题