Skip to content

Instantly share code, notes, and snippets.

@kyle-ilantzis
Last active October 9, 2015 21:37
Show Gist options
  • Save kyle-ilantzis/afdb88b6978686f6da84 to your computer and use it in GitHub Desktop.
Save kyle-ilantzis/afdb88b6978686f6da84 to your computer and use it in GitHub Desktop.
Little helper for shell commands from python
import unittest
from commander import *
class TestCommander(unittest.TestCase):
def test_run(self):
r = run("ping", "localhost")
self.assertIsNone(r)
def test_try_run(self):
r = try_run("ping", "localhost")
self.assertEqual(r, 0)
def test_try_run__bad_command(self):
r = try_run("ping", "--bad-option")
self.assertNotEqual(r, 0)
def test_run2(self):
out = run2("ping", "localhost")
self.assertTrue(out.strip().lower().startswith("pinging"))
def test_try_run2(self):
(r,out) = try_run2("ping", "localhost")
self.assertEqual(r, 0)
self.assertTrue(out.strip().lower().startswith("pinging"))
def test_try_run2__bad_command(self):
(r,_) = try_run2("ping", "--bad-option")
self.assertNotEqual(r, 0)
def test_cd(self):
pass
if __name__ == "__main__":
unittest.main()
#!/usr/bin/python3
"""
A collection of functions to run shell commands from python.
These functions are just simple wrappers to subprocess.run
but this interface favors convention over configuration for simple use cases
https://en.wikipedia.org/wiki/Convention_over_configuration
"""
import os
import subprocess
# "private" module functions
def _run(*args, shell=False, cwd=None):
subprocess.run(args, stdout=subprocess.DEVNULL, shell=shell, cwd=cwd, check=True)
def _try_run(*args, shell=False, cwd=None):
completedProcess = subprocess.run(args, stdout=subprocess.DEVNULL, shell=shell, cwd=cwd)
return completedProcess.returncode
def _run2(*args, shell=False, cwd=None):
completedProcess = subprocess.run(args, stdout=subprocess.PIPE, universal_newlines=True, shell=shell, cwd=cwd, check=True)
return completedProcess.stdout
def _try_run2(*args, shell=False, cwd=None):
completedProcess = subprocess.run(args, stdout=subprocess.PIPE, universal_newlines=True, shell=shell, cwd=cwd)
return (completedProcess.returncode,completedProcess.stdout)
class _Cwd:
def __init__(self, directory='.', shell=False):
self.directory = directory
self.shell = shell
def run(self, *args):
return _run(*args, shell=self.shell, cwd=self.directory)
def try_run(self, *args):
return _try_run(*args, shell=self.shell, cwd=self.directory)
def run2(self, *args):
return _run2(*args, shell=self.shell, cwd=self.directory)
def try_run2(self, *args):
return _try_run2(*args, shell=self.shell, cwd=self.directory)
def cd(self, directory):
normpath = os.path.normpath( os.path.join(self.directory, directory) )
return _Cwd(directory=normpath, shell=self.shell)
def shell(self):
return _Cwd(directory=self.directory, shell=True)
# public module functions
def run(*args):
"""
Run a command on the system.
ex: run("git","commit","-m","hello commit")
Fails if the command returns a non-zero exit status
"""
return _run(*args)
def try_run(*args):
"""
Try to run a command on the system. Returns the exit status.
ex:
exit_status = try_run("git","commit","-m","hello commit")
if exit_status == 0:
# success
else:
# failure
"""
return _try_run(*args)
def run2(*args):
"""
Run a command on the system. Returns the output as a string
ex:
msg = run2("echo", "hello")
print(msg, "world") # hello world
Fails if the command returns a non-zero exit status
"""
return _run2(*args)
def try_run2(*args):
"""
Try to run a command on the system. Returns the exit status and ouput in a tuple
ex:
(exit_status,msg) = try_run2("echo", "hello")
if exit_status == 0:
# success
print(msg, "world") # hello world
else:
# failure
...
"""
return _try_run2(*args)
def cd(directory):
"""
Returns an object with commander functions run, try_run, run2, try_run2, cd, shell
where the commands run with directory as the cwd
ex:
cmdA = cd("A") # commands run from directory A
dirAContents = cmdA.run2("ls")
cmdAB = cmd.cd("B") # commands run from directory A/B
dirBContents = cmdAB.run("ls")
"""
return _Cwd(directory=directory)
def shell():
"""
Returns an object with commander functions run, try_run, run2, try_run2, cd, shell
where the commands run in a shell
ex:
cmd = shell(True)
johndoe_password = cmd.run2("cat /etc/passwd | grep johndoe")
"""
return _Cwd(shell=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment