Skip to content

Instantly share code, notes, and snippets.

@IlmariKu
Last active June 4, 2021 11:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save IlmariKu/37e8c78ddfebe4e27ba9f7ee1337eb61 to your computer and use it in GitHub Desktop.
Save IlmariKu/37e8c78ddfebe4e27ba9f7ee1337eb61 to your computer and use it in GitHub Desktop.
run.py - Python command-line runner for repeated repository tasks
#!/usr/bin/env python3
import os
import datetime
import sys
import subprocess
"""
Command line tool to run simple commands from repository root
Simple way to run commands, beats listing them in README or having multiple .sh-scripts
I've used this in multiple projects and find that I always copy it over, since I like it that much
Created to be modified and extended
HOW TO SETUP: Copy script contents to run.py file and chmod +x for executable permissions
HOW TO INVOKE: Write: ./run.py in command-line
Ilmari Kumpula, 10.9.2020
"""
commands = {
"first_command": "echo 'This would be the first command-line command. Enter your code here' ",
"second_command": "echo 'This would be the second command, change code as you please' ",
}
command_names = {
"first_command": "Print a simple echo",
"second_command": "Run second command, does nothing"
}
def check_input_for_errors(select):
if len(commands.keys()) >= select:
return select
print(str(select) + " is not in the list to be selected")
sys.exit(1)
def get_option_argument(commands):
if len(sys.argv) < 2:
return None
option = sys.argv[1]
if option not in commands.keys():
print(option + " is not an option!")
sys.exit(1)
return option
def get_additional_arguments():
return "".join(sys.argv[2:])
def get_user_input():
try:
user_input = input()
if not user_input:
sys.exit(1)
return int(user_input)
except ValueError:
print(user_input + " is not an integer!")
sys.exit(1)
except KeyboardInterrupt:
sys.exit(1)
def make_user_select_from_menu():
print("\nPass ./run.py command_name - to directly execute options without menu")
command_list = [""]
for c, option in enumerate(commands.keys(), 1):
command_list.append(option)
print(str(c) + ") " + command_names.get(option,
option) + " (" + option + ")")
print("Select operation (number): ")
user_selection = get_user_input()
check_input_for_errors(user_selection)
return command_list[user_selection]
selection = get_option_argument(commands)
additional_commands = get_additional_arguments()
if not selection:
selection = make_user_select_from_menu()
response = subprocess.run(
commands[selection] + " " + additional_commands,
shell=True,
cwd=os.getcwd(),
executable="/bin/bash"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment