Search code examples
pythonif-statementsys

Python execute if/else statement based on sys.argv passed on Command Line


I am new to Python and the syntax is really throwing me off. I need to execute a script in which I'd like to execute a function based on the arguments passed on Command Line. Following is the pseudo code:

import sys

...
Code
Authentication
Role Validation 
...

Arg[1]
Arg[2]
Arg[3]

if(Arg[3] !exist)
  execute Func1 with Arg[1] & Arg[2]
else if 
  execute Func 2 with Arg[1], [2] & [3]

Can someone guide me how to structure this in Python's world or if there is any other way to do it?


Solution

  • If you must use sys.argv, it's just a normal Python list, you can use len on it to check how many arguments were passed (remember, the 0th element is the program itself).

    if len(sys.argv) == 3:
        func1(*sys.argv[1:3])  # * unpacking removes repeated references to sys.argv
    elif len(sys.argv) == 4:
        func2(*sys.argv[1:4])
    

    I'd recommend looking at something like the argparse module though; it's more work to learn, but it means your scripts get -h/--help support automatically, which makes it much easier to use the script, without implementing a usage message separately, risking it getting out of sync.

    Alternatively, if you are up for using third party packages, docopt is generally praised as an alternative to argparse.