Syed Tamoor ul Hassan
Syed Tamoor ul Hassan

Reputation: 11

subprocess.Popen help needed

I need to execute a command using subprocess.Popen. The command which I need to run is:

./Test -t -1

Test is an executable file while the other arguments -t and -1 are for enabling the outputs (logs) to the shell. I want to write the output to a log file.

Unfortunately I am unable to do it.

I tried like this:

output = open("outputlog.log", "a")
subprocess.Popen(["./Test", "-t", "-1"], stdout = output)

Please help me in this regard.

Regards Tamoor

Upvotes: 1

Views: 100

Answers (2)

unutbu
unutbu

Reputation: 879749

Two things might be going wrong:

  1. Test -t -1 may be writing to stderr, not stdout.
  2. output may need to be flushed or closed before the buffer is written to disk.

Try:

with open("outputlog.log", "a") as output:
    subprocess.Popen(["./Test", "-t", "-1"], stdout=output, stderr=output)

This will write both stdout and stderr to output, and close (and flush) output when the with-suite ends.

Upvotes: 0

Jonathan Rom
Jonathan Rom

Reputation: 83

try this:

output = open("outputlog.log", "a")
p = subprocess.Popen(["./Test", "-t", "-1"], stdout=subprocess.PIPE)
output.writelines(p.stdout.readlines())

Upvotes: 1

Related Questions