Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture the output from "subprocess.call" to a file?

In my code I have a line similar to this:

rval = subprocess.call(["mkdir",directoryName], shell=True)

and I can check rval to see if it is 0 or 1, but if it is 1, I would like to have the text from the command "A subdirectory or file ben already exists." in a file format, so I can compare it to another file if I want to make sure the text is the same.

Is it possible to have a line like this, but I know this does not work

rval = subprocess.call(["mkdir",directoryName], shell=True) >> filename

so no matter what happens with the command, the text is captured in filename, and rval still has the return code?

like image 579
Dag Avatar asked Oct 20 '10 16:10

Dag


People also ask

How do I capture the output of a subprocess run?

To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.

How do you check subprocess output?

The subprocess. check_output() is used to get the output of the calling program in python. It has 5 arguments; args, stdin, stderr, shell, universal_newlines. The args argument holds the commands that are to be passed as a string.

How do you end a subprocess call in Python?

Popen(args) with args as a sequence of program arguments or a single string to execute a child program in a new process with the supplied arguments. To terminate the subprocess, call subprocess. Popen. terminate() with subprocess.

How does subprocess run get return value?

subprocess. check_output() is the one that runs the command and returns the return value. If you want the output write your value to STDOUT and use check_output() to get the value.


3 Answers

The subprocess module has a built in 'check_output' function for doing this:

In [11]: result = subprocess.check_output(['pwd'])

In [12]: print result
/home/vagrant
like image 182
btubbs Avatar answered Sep 30 '22 09:09

btubbs


import subprocess
f = open(r'c:\temp\temp.txt','w')
subprocess.call(['dir', r'c:\temp'], shell=True, stdout=f)
f.close()
like image 22
Mark Ransom Avatar answered Sep 30 '22 08:09

Mark Ransom


import subprocess

try:
    result = subprocess.check_output(['dir', r'c:\temp'], shell=True)
    print result
except subprocess.CalledProcessError as e:
    return_code = e.returncode

You anyway need to use try catch because it throws exception if return code is non zero :)

like image 34
Jatin Kumar Avatar answered Sep 30 '22 09:09

Jatin Kumar