Running a shell command from a Python script

I am trying to run a shell command from a python script that needs to do a few things 1. The shell command is "hspice tran.deck>! Tran.lis'
2. the script should wait for the shell command to complete before continuing 3. I need to check the return code from the command and 4. Capture STDOUT, if it completes successfully, write STDERR

I went through the subprocess module and tried a couple of things, but could not find a way to do all of the above.
- with subprocess.call () I can check the return code, but not capture the output.
- with subprocess.check_output () I could capture the output, but not the code.
- with subprocess.Popen () and Popen.communicate (), I could capture STDOUT and STDERR, but not the return code.
I'm not sure how to use Popen.wait () or the returncode attribute. I also could not get Popen to accept ">!" or '|' as arguments.

Can anyone point me in the right direction? I am using Python 2.7.1

EDIT: You have things working with the following code

process = subprocess.Popen('ls | tee out.txt', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = process.communicate() if(process.returncode==0): print out else: print err 

Also, should you use process.wait () after the line process = or wait by default?

+4
source share
3 answers

Just use .returncode after .communicate() . Also, tell Popen that what you are trying to run is a shell command , not a raw command line:

 p = subprocess.Popen('ls | tee out.txt', shell=True, ...) p.communicate() print p.returncode 
+10
source

From the docs :

Popen. returncode

The child return code set by poll() and wait() (and indirectly on communicate() ). A value of None indicates that the process has not yet completed.

A negative value of -N indicates that the child was interrupted by signal N (Unix only).

+3
source

Here is an example of shell interaction:

 >>> process = subprocess.Popen(['/bin/bash'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE) >>> process.stdin.write('echo it works!\n') >>> process.stdout.readline() 'it works!\n' >>> process.stdin.write('date\n') >>> process.stdout.readline() 'wto, 13 mar 2012, 17:25:35 CET\n' >>> 
-1
source

Source: https://habr.com/ru/post/1401734/


All Articles