Skip to content

Instantly share code, notes, and snippets.

@aric49
Last active September 26, 2019 16:27
Show Gist options
  • Select an option

  • Save aric49/bf6d07cb18ab0944182b9ed2a2d17c75 to your computer and use it in GitHub Desktop.

Select an option

Save aric49/bf6d07cb18ab0944182b9ed2a2d17c75 to your computer and use it in GitHub Desktop.
Use Python instead of Shell Scripts
#!/usr/bin/env python3
import subprocess
import sys
#Use Python instead of shell scripts!
#Broken out into classes to create nice object oriented code.
#Using Sys and subprocess modules to execute shell commands, checking each exit code and doing the things!
class ExecutePrograms:
def __init__(self, userinput):
self.input = userinput
if self.input.lower() == "program1":
ExecutePrograms.program1(self)
elif self.input.lower() == "program2":
ExecutePrograms.program2(self)
else:
print("You need to specify program1 or program2!")
sys.exit(1)
def program1(self):
print("Executing Program 1.....")
commands = ["echo 'hello world, I am program1!!!'", "sleep 10", "echo 'The contents of your TMP directory is:'", "ls -la /tmp/"]
for command in commands:
execute = subprocess.run(command, shell=True)
if execute.returncode != 0:
print(f"ERROR! the command: `{command}` did not finish as expected! ")
sys.exit(1)
else:
print(f"{command} SUCCESS!")
def program2(self):
print("Executing Program 2...... This one will always fail!")
commands = ["echo 'hello world, I am program2!!!'", "sleep 10", "echo 'The contents of your HOME directory is:'", "ls -la ~/", "/bin/false"]
for command in commands:
execute = subprocess.run(command, shell=True)
if execute.returncode != 0:
print(f"ERROR! the command: `{command}` did not finish as expected! ")
sys.exit(1)
else:
print(f"{command} SUCCESS!")
def main():
print("Welcome to the program! This will execute shell commands in python instead of standard bash!")
input1 = input("What commands would you like to execute? Program1 or Program2 ? ")
ExecutePrograms(input1)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment