Python: subprocess not writing output files
<p>Using Python's <code>subprocess.call</code>, 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 <code>subprocess.call</code> does not.</p>

<p>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 &amp; output files are hardcoded into the C program.</p>

<pre><code>import subprocess


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

<p>This returns:</p>

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

<p>What am I doing wrong?</p>

<p>Using <code>subprocess.check_output</code>, I see no errors. </p>

<p>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 <code>subprocess.call()</code> invocation required paths <em>relative to the python script</em>, not the exe. This is unexpected, and produces very different results from invoking the exe from the terminal.</p>

<pre><code>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')
</code></pre>

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

<p>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.</p>

python subprocess