Skip to content

Instantly share code, notes, and snippets.

@rahulremanan
Last active August 8, 2021 10:35
Show Gist options
  • Save rahulremanan/cc73ff3437aec9c25b4c4cdf2fde6999 to your computer and use it in GitHub Desktop.
Save rahulremanan/cc73ff3437aec9c25b4c4cdf2fde6999 to your computer and use it in GitHub Desktop.
Shell commands in Python using subprocess
import subprocess
def execute_in_shell(command, verbose=False):
"""
command -- keyword argument, takes a list as input
verbsoe -- keyword argument, takes a boolean value as input
This is a function that executes shell scripts from within python.
Keyword argument 'command', should be a list of shell commands.
Keyword argument 'versboe', should be a boolean value to set verbose level.
Example usage: execute_in_shell(command = ['ls ./some/folder/',
ls ./some/folder/ -1 | wc -l'],
verbose = True )
This command returns dictionary with elements: Output and Error.
Output records the console output,
Error records the console error messages.
"""
error = []
output = []
if isinstance(command, list):
for i in range(len(command)):
try:
process = subprocess.Popen(command[i], shell=True, stdout=subprocess.PIPE)
process.wait()
out, err = process.communicate()
error.append(err)
output.append(out)
if verbose:
print ('Success running shell command: {}'.format(command[i]))
except Exception as e:
print ('Failed running shell command: {}'.format(command[i]))
if verbose:
print(type(e))
print(e.args)
print(e)
print(logging.error(e, exc_info=True))
else:
raise ValueError('Expects a list input ...')
return {'Output': output, 'Error': error }
if __name__ == "__main__":
command = ['mkdir ~/Desktop/New_photos/'
'cd ~/Desktop/My_folder/Photos/ ; shuf -n 10 -e *.jpg | xargs -i cp {} ../../New_photos/',
'ls ~/Desktop/New_photos/ -1 | wc -l']
print ((execute_in_shell(command)).get('Output'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment