Skip to content
Advertisement

Automation of tasks with argparse Python3

Hi is anyone able to help. I am learning to use argparse and i want to use the command to call the school.py as school start for example. I have this so far but struggling to handle the arguments. Am i doing this right or what am i doing totally wrong?

if __name__ == '__main__':


parser = argparse.ArgumentParser(description="This allows quick opening of applications used within the school day")

parser.add_argument("start", help="This will open all the standard applications used within the school day.")
parser.add_argument("engine", help="This will show the Engineering folder within Documents")
parser.add_argument("bus", help="This will show the Business folder within Documents")
parser.add_argument("cs", help="This will show the Computer Science folder within Documents")
parser.add_argument("python", help="This will open the PyCharm application")

args = parser.parse_args()

try:
    if len(sys.argv) > 1:
        if sys.argv[1] == "engine":
            engineering()
        elif sys.argv[1] == "cs":
            computer_science()
        elif sys.argv[1] == "python":
            python()
        elif sys.argv[1] == "bus":
            business()
        elif sys.argv[1] == "start":
            std_day()
except:
    print("An error has occurred")

My error is

usage: autoSchoolDay.py [-h] start engine bus cs python

autoSchoolDay.py: error: the following arguments are required: engine, bus, cs, python

Advertisement

Answer

parser = argparse.ArgumentParser(description="This allows quick opening of applications used within the school day")

parser.add_argument('command', choices=['start', 'engine', 'bus', 'cs', 'python'])

args = parser.parse_args()

try:
    if args.command:
        if args.command == "engine":
            engineering()
        elif args.command == "cs":
            computer_science()
        elif args.command == "python":
            python()
        elif args.command == "bus":
            business()
        elif args.command == "start":
            std_day()
except Exception as e:
    print("An error has occurred", e)
Advertisement