3

How to capture the standard output of command in python script

for example , I want to check if tar command success or not and results will be return in stndStatus value

import commands

def runCommandAndReturnValue():

      status,output = commands.getstatusoutput("  tar xvf Test.tar ")
      return stndStatus

other example - its like $? in shell scripts so stndStatus will be the value of $?

6
  • 2
    Take a look at the subprocess module docs.python.org/2/library/subprocess.html Commented Aug 17, 2015 at 21:44
  • Your code doesn't make sense because stndStatus is not defined anywhere. Linux commands typically return 0 if successful and an 8-bit signed integer corresponding to an error code otherwise. There is no standard definition of the other error codes, really. Only that zero indicates success. Commented Aug 17, 2015 at 21:45
  • i think this modul not support in python 2.X ( this is the version on my linux ) Commented Aug 17, 2015 at 21:45
  • @Eytan i am using 2.7 and it works very well. Commented Aug 17, 2015 at 21:46
  • @Eytan Those are the Python 2 docs and right at the top of the page it says New in Python 2.4 Commented Aug 17, 2015 at 21:46

2 Answers 2

2

I need to redirect the output to DEVNULL:

import subprocess
import os

FNULL = open(os.devnull, 'w')
retcode = subprocess.call(['tar', 'xvf', 'test.tar'],
                          stdout=FNULL,
                          stderr=subprocess.STDOUT)
print retcode
Sign up to request clarification or add additional context in comments.

Comments

0

Here this should work:

with open('output.txt','w') as f:
  retcode = subprocess.call('tar xvd Test.tar', stdout=f, stderr=f)

Retcode will have the return value of the command. 0 if success, and something else if not. The output from the command will go to the file, which you can read later.

11 Comments

is it ok to not write to a file and only to stay with the second line?
@Eytan what do you mean? You don’t want the output from the command?
I want the output in the var - retcode but not write to send it to afile
@Eytan from the docs: "stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None."
@Eytan no thnx. Make some effort yourself.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.