In Python 2 or 3, how to get the return code and return the system call string?

I know that I can do this to execute a system command, for example, make, and this will give me either 0 for success or a non-zero value for failure.

import os
result = os.system('make')

I also know that I can do this so that I can see the returned command line

import commands
result = commands.getoutput('make')

How can I do both, where I get both the return code and the result of the returned string, so I can

if return_code > 0:
  print(return_string)

Thank.

+4
source share
2 answers

Python - subprocess, , check_call check_output, " stdout = PIPE stderr = PIPE ", :

1: script

proc = subprocess.Popen(["your_command", "parameter1", "paramter2"],
                        stdout=subprocess.PIPE, stderr=subprocess.PIPE)

, .

EDIT: - , Python . , stdout stderr , communicate 2.

2:

stdout, sterr = proc.communicate()
return_code = proc.returncode

communicate -:

  • stdin ( input=)
  • , (timeout=)

, Popen communicate.


Python, subprocess.run, :

completed_process = subprocess.run(
    ['your_command', 'parameter'],
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE)
# this starts the process, waits for it to finish, and gives you...
completed_process.returncode
completed_process.stdout
completed_process.stderr

completed_process.check_returncode() check=True run.

+4

, , :

import subprocess
try:
 output = subprocess.check_output("make", stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
  print('return code =', e.returncode)
  print(e.output)
0

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


All Articles