Valarauko
Valarauko

Reputation: 111

Python: subprocess not writing output files

Using Python's subprocess.call, I am trying to invoke a C program that reads an input file on disk, and creates multiple output files. Running the C program from terminal gives the expected results, though subprocess.call does not.

In the minimal example, the program should read the input file in a scratch folder, and create an output file in the same folder. The locations and names of the input & output files are hardcoded into the C program.

import subprocess


subprocess.call('bin/program.exe') # parses input file 'scratch/input.txt'
with open('scratch/output.txt') as f:
    print(f.read())

This returns:

FileNotFoundError: [Errno 2] No such file or directory: 'scratch/output.txt'

What am I doing wrong?

Using subprocess.check_output, I see no errors.

EDIT: So I see the subprocess working directory is involved. The C executable has hardcoded paths for input/output relative to the exe (ie, '../scratch/input.txt'), but the subprocess.call() invocation required paths relative to the python script, not the exe. This is unexpected, and produces very different results from invoking the exe from the terminal.

Upvotes: 1

Views: 3157

Answers (1)

Daniel Lee
Daniel Lee

Reputation: 8011

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')

You have to open the file in a mode. Read for example. You will need to join the path with os.path.join().

You can create a folder and a file if they don't exist. But there will bo nothing to read from. If you want to write to them, that can be acheived like shown above.

Upvotes: 1

Related Questions