18

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
Dag
  • 1,101
  • 4
  • 11
  • 13
  • Duplicate of all of these: http://stackoverflow.com/search?q=%5Bpython%5D+subprocess+capture – S.Lott Oct 20 '10 at 16:04
  • possible duplicate of [Capture subprocess output](http://stackoverflow.com/questions/2525263/capture-subprocess-output) – S.Lott Oct 20 '10 at 16:04
  • why are you not using Python's builtin `mkdir()` ? – ghostdog74 Oct 20 '10 at 16:08
  • I am doing this for a command I can not post here, but it has similar characteristics as mkdir. – Dag Oct 20 '10 at 16:16
  • @S.Lott, it's *almost* a duplicate. The difference would be `Popen` vs `call` (which I agree is subtle), and the desire to write to a file rather than capturing the output within the program. Even though it seems the questioner would rather capture the output, it's useful to answer the question as-is. – Mark Ransom Oct 20 '10 at 16:28

3 Answers3

17

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
btubbs
  • 1,845
  • 1
  • 16
  • 19
15
import subprocess
f = open(r'c:\temp\temp.txt','w')
subprocess.call(['dir', r'c:\temp'], shell=True, stdout=f)
f.close()
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • 1
    Any reason why you used 'shell=True' in this case? Cause I read using that is a bad idea (on *nix at least). – user225312 Oct 20 '10 at 17:41
  • @PulpFiction, two reasons: first it was included in the original question, second I was using a Windows shell command for testing. – Mark Ransom Oct 20 '10 at 17:42
12
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 :)

Jatin Kumar
  • 2,635
  • 9
  • 36
  • 46