I want to check whether Python's subprocess su

2020-04-18 07:41发布

问题:

I am trying to create a code making code with python subprocess.

#code = 'print("hey")' #OK
code = 'print"hey")'   #SyntaxError
with open(filename, 'w') as f:
    f.write(code)

proc = s.Popen(['python',filename], stdout=s.PIPE, stderr=s.STDOUT)
stdout_v, stderr_v = proc.communicate('')
print(stdout_v.decode('utf8'))

It is roughly like this.

Currently, the return value from the subprocess is included in stdout_v even if it operates normally or when a syntax error occurs, and it can not tell them apart.

Can I receive the output if it is executed normally, and can receive an error message from the subprocess if an error occurs?

回答1:

The recommended way to use subprocess in Python 3.5+ is with the run function.

proc = s.run(['python',filename], stdout=s.PIPE, stderr=s.PIPE, check=False)
stdout_v, stderr_v, = proc.stdout, proc.stderr
return_code = proc.return_code

Set check=True to throw an error if the return code is non-zero (which is an indication of some error happening).

In older versions of Python, I usually preferred to use the check_output or call functions. Check_output will throw an error if it detects a non-zero exit code, whereas the call function will continue normally.



回答2:

From the documents

https://docs.python.org/2/library/subprocess.html

You can check for command validity by

subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

Run command with arguments. Wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute.

Return code 0= Sucess

If you wish to see the output of command

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

Run command with arguments and return its output as a byte string.