Last active
June 20, 2023 06:18
-
-
Save jlinoff/1170043a4d28a128b810 to your computer and use it in GitHub Desktop.
Python example that shows how to run non-interactive shell commands using two different subprocess implementations.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
''' | |
Python example that shows how to run non-interactive shell commands using | |
two different subprocess implementations. | |
Works in Python 2.7 and Python 3.x. | |
LICENSE (MIT Open Source) | |
Copyright (c) 2016 Joe Linoff | |
Permission is hereby granted, free of charge, to any person obtaining | |
a copy of this software and associated documentation files (the | |
"Software"), to deal in the Software without restriction, including | |
without limitation the rights to use, copy, modify, merge, publish, | |
distribute, sublicense, and/or sell copies of the Software, and to | |
permit persons to whom the Software is furnished to do so, subject to | |
the following conditions: | |
The above copyright notice and this permission notice shall be | |
included in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | |
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | |
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, | |
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE | |
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
''' | |
import subprocess | |
import sys | |
def __runcmd_long(cmd, show_output=True): | |
''' | |
Execute a long running shell command with no inputs. | |
Capture output and exit status. | |
For long running commands, this implementation displays output | |
information as it is captured. | |
For fast running commands it would be better to use | |
subprocess.check_output. | |
''' | |
proc = subprocess.Popen(cmd, | |
shell=True, | |
stdout=subprocess.PIPE, | |
stderr=subprocess.STDOUT) | |
# Read the output 1 character at a time so that it can be | |
# displayed in real time. | |
output = '' | |
while not proc.returncode: | |
char = proc.stdout.read(1) | |
if not char: | |
# all done, wait for returncode to get populated | |
break | |
else: | |
ascii_char = char.decode('ascii') # byte --> char in Python 3 | |
output += ascii_char | |
if show_output: | |
sys.stdout.write(ascii_char) | |
sys.stdout.flush() | |
proc.wait() | |
return proc.returncode, output | |
def __runcmd_short(cmd, show_output=True): | |
''' | |
Execute a short running shell command with no inputs. | |
Capture output and exit status. | |
''' | |
try: | |
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True) | |
status = 0 | |
except subprocess.CalledProcessError as obj: | |
output = obj.output.decode('ascii') | |
status = obj.returncode | |
output = output.decode('ascii') # byte --> char in Python 3 | |
if show_output: | |
sys.stdout.write(output) | |
return status, output | |
def __runcmd_interactive(cmd): | |
''' | |
Run an interactive command. | |
Return the status. | |
''' | |
try: | |
args = shlex.split(cmd) | |
status = subprocess.call(cmd, shell=True) | |
except subprocess.CalledProcessError as obj: | |
status = obj.returncode | |
return status | |
def test(): | |
''' | |
Treat each command line argument as a separate command. | |
The --long argument specifies the use of __runcmd_long. | |
It is modal so all subsequent commands use __runcmd_long until | |
--short is specified. | |
The --short argument specifies the use of __runcmd_short. | |
It is modal so all subsequent commands use __runcmd_short until | |
--long is specified. | |
The default is --short. | |
Here are some examples to show how it is used: | |
$ runcmd.py 'ls -l' 'hostname -f' | |
$ runcmd.py --long 'ls -l' 'hostname -f' | |
$ runcmd.py --long 'ls -l' --short 'hostname -f' | |
''' | |
runcmd = __runcmd_short | |
for i in range(1, len(sys.argv)): | |
arg = sys.argv[i] | |
if arg == '--short': | |
runcmd = __runcmd_short | |
elif arg == '--long': | |
runcmd = __runcmd_long | |
else: | |
print('Function: {}'.format(runcmd.__name__)) | |
print('Command: {}'.format(arg)) | |
status, _ = runcmd(arg) | |
print('Status: {}'.format(status)) | |
if __name__ == '__main__': | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment