i have code https://pymotw.com/2/subprocess/
i'm not sure how interpret code, in check_output
1>&2
output redirected stderr, in parameter, stderr stdout stderr=subprocess.stdout
.
output = subprocess.check_output( 'echo stdout; echo stderr 1>&2; exit 1', shell=true, stderr=subprocess.stdout, ) print "*****************" print 'have %d bytes in output' % len(output) print output
running code, print commands not executed meaning nothing captured.
what code trying accomplish?
edit
from answer , comment, run code
try: output = subprocess.check_output( 'echo stdout; echo stderr 1>&2; exit 1', shell=true, # no such file or directory error without, maybe 1>&2 requires shell=true stderr=subprocess.stdout, ) except subprocess.calledprocesserror e: print "*****************" print 'have %d bytes in output' % len(e.output) print e.output
this output:
***************** have 20 bytes in output stdout stderr
however, when commented out stderr=subprocess.stdout
line, got instead
to stderr ***************** have 10 bytes in output stdout
edit2
i tested more stderr library (https://github.com/sickill/stderred) helps shell show characters stderr in red color.
when execute code (comment out redirection), can see to stderr
in black color implies uses stdout.
output = subprocess.check_output( 'echo stdout; echo stderr 1>&2; exit 1', shell=true, #stderr=subprocess.stdout, )
from this, guess (correct me if i'm wrong) python's check_output
method prints out data stderr redirect stdout prints out error message stderr.
the 1 >&2
shell code applies (echo) command appears on. how tell shell direct output of echo shell's stderr stream.
the python code stderr=subprocess.stdout
tells subprocess module want process's stderr stream same file descriptor stdout stream read whatever process writes either stream interleaved in 1 stream.
the exit 1
in shell command means shell exits error (non-zero) status.
the purpose of code demonstrate python function subprocess.check_output
check exit status , raise exception when non-zero.
if exit code non-zero raises calledprocesserror. calledprocesserror object have return code in returncode attribute , output in output attribute.
your description of:
running code, print commands not executed
is bit misleading since neglect mention output occur:
traceback (most recent call last): file "t.py", line 6, in <module> stderr=subprocess.stdout, file "/usr/lib/python2.7/subprocess.py", line 573, in check_output raise calledprocesserror(retcode, cmd, output=output) subprocess.calledprocesserror: command 'echo stdout; echo stderr 1>&2; exit 1' returned non-zero exit status 1
Comments
Post a Comment