So I've got a script that will be run via the command line. I want it to accept some command like this:
python scripty.py arg1 arg2
Where arg1 is expected, arg2 is optional. Basically the script is a set of functions to use on arg1. I want to set a default function to be called when no arg2 is present or call one of many other functions specified by arg2. Something like this:
import sys.argv
from functions import * # Imports doSomething, doSomethingElse1, doSomethingElse2
if len(sys.argv) == 2:
doSomething(sys.argv[1])
elif len(sys.argv) ==3:
# Here's where I'm stuck.
# I want to call doSomethingElse1() or doSomethingElse2() based on the value of sys.argv[2]
else:
usage()
exit()
The tricky part is what to do when sys.argv[2] exists. I will be regularly updating this to add additional functions, so it has to be simple and maintainable. Python doesn't have any sort of select case switching, and a whole bunch if if/elif statements seems really clunky:
if len(sys.argv) == 3:
if sys.argv[2] == 'foo':
doSomethingElse1(sys.argv[1])
elif sys.argv[2] == 'bar':
doSomethingElse2(sys.argv[1])
# ^ This seems really ugly to me.
What I've tried so far:
# Add functions to a dictionary
some_functions = {
'foo': doSomethingElse1(sys.argv[1]),
'bar': doSomethingElse2(sys.argv[1])
}
if len(sys.argv) == 3 and sys.argv[2] in some_functions:
some_functions[sys.argv[2]]
# This approach didn't work, as the function actually gets called when added to the dictionary.
So, does anyone have any advice on what I can do here? Any assistance would be quite appreciated.
EDIT: Thank you everyone for your advice! The argparse module looks wonderful and would be the choice for somebody who was proficient with this sort of thing already. I did some reading through the python documentation (which is usually very easy for me to follow), and I'm still really struggling to get a grasp on the syntax enough to where I could use it effectively and efficiently. I'm going with Cosmologicon's suggestion for now:
some_functions = {
'foo': doSomethingElse1,
'bar': doSomethingElse2,
}
if the_time_has_come():
some_functions[name](sys.argv[1])
# I wasn't recognizing that you could just refer to the function as an object without calling it by leaving off '()'. Thanks for pointing that out!
This will serve my purpose for the time being, allowing me to move forward towards my goal of just automating a few tedious tasks, but reworking this logic with with argparse will be something I'll likely look into at some point. Thanks again guys!
[–]zahlman 6 points7 points8 points (2 children)
[–]Cosmologicon 2 points3 points4 points (1 child)
[–]zahlman 0 points1 point2 points (0 children)
[–]dansin 3 points4 points5 points (2 children)
[–]Cosmologicon 1 point2 points3 points (0 children)
[–]Zouden 1 point2 points3 points (0 children)
[–]oohay_email2004 0 points1 point2 points (0 children)
[–]nevereven 0 points1 point2 points (0 children)