Skip to content

Instantly share code, notes, and snippets.

@evgeni
Created August 7, 2017 06:43
Show Gist options
  • Save evgeni/3b2f8b5358c4eaa71a17dd845c9fd4f5 to your computer and use it in GitHub Desktop.
Save evgeni/3b2f8b5358c4eaa71a17dd845c9fd4f5 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# works fine on python2 ;-)
#
# Python2 had a `commands` module, which was long deprecated, but had a nice
# shorthand to get both the status and the output of a command:
# getstatusoutput [py2doc]
# This got ported to Python3's `subprocess` module [py3doc].
#
# Both versions prented: "The exit status for the command can be interpreted
# according to the rules for the C function wait()." [wait]
# The Python 3 documentation has even an example:
# >>> subprocess.getstatusoutput('ls /bin/ls')
# (0, '/bin/ls')
# >>> subprocess.getstatusoutput('cat /bin/junk')
# (256, 'cat: /bin/junk: No such file or directory')
# >>> subprocess.getstatusoutput('/bin/junk')
# (256, 'sh: /bin/junk: not found')
# Well, I think noone tried to execute those examples after porting the method
# to Windows [winpatch]
#
# $ python2 --version
# Python 2.7.13
# $ python2 getstatusoutputbug.py
# expected: 0
# 0
# expected: 256
# 256
# expected: 256
# 32512
# $ python3 --version
# Python 3.6.2
# $ python3 getstatusoutputbug.py
# expected: 0
# 0
# expected: 256
# 1
# expected: 256
# 127
#
# [py3doc]: https://docs.python.org/3/library/subprocess.html#subprocess.getstatusoutput
# [py2doc]: https://docs.python.org/2/library/commands.html#commands.getstatusoutput
# [wait]: https://linux.die.net/man/3/wait
# [winpatch]: https://github.com/python/cpython/commit/e004175c5694804c263f0f06e7a4e3bbc6852cc4
from __future__ import print_function
try:
from commands import getstatusoutput
except ImportError:
from subprocess import getstatusoutput
(status, output) = getstatusoutput('ls /bin/ls')
print("expected (by the docstring): 0")
print(status)
(status, output) = getstatusoutput('cat /bin/junk')
print("expected (by the docstring): 256")
print(status)
(status, output) = getstatusoutput('/bin/junk')
print("expected (by the docstring): 256")
print(status)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment