0

I have a python program that calls a subprocess using Popen(). This python program is called from a C program, using the Python/C API. Everything works fine except for the fact that the subprocess doesn't redirect the output to a file. If I use just the Python program, it works as it's supposed to do. If I call the same program from C, it doesn't.

Any clue?

fout = open('fout.txt','w+')
self.process = Popen(starting_cmd,stdout=fout)

1 Answers1

1

With this minimum information I can't help you a lot but I'll suggest you do something like this :

with open("fout.txt","a") as out:
    subprocess.Popen("starting_cmd",stdout=out)
  • The process don't need to read info so we don't need to open the file in reading mode (and it's a best practice to restrain the access to a file to only what's necessary). You could therefore replace w+ with just w or a (to append fout.txt).
  • The with is for context managing to be sure the file is closed when out goes out of scope, which can potentially help to make the result visible in the file.

Here's a working example (in python3) :

import subprocess
with open("fout.txt", "a") as out:
    subprocess.Popen("ls", stdout=out)
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
Brice Harismendy
  • 113
  • 1
  • 12