'Python execute if/else statement based on sys.argv passed on Command Line [closed]
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 1:[1]
I believe this is what you are looking for. sys.argv is the list containing your command line arguments. sys.argv[0] is typically the command you ran, so you're interested in the ones after that.
if len(sys.argv) == 4:
execute Func 2 with sys.argv[1], sys.argv[2] & sys.argv[3]
elif len(sys.argv) == 3:
execute Func1 with sys.argv[1] & sys.argv[2]
Solution 2:[2]
The simplest thing that does what you ask could looks at the length of the list given by sys.argv
import sys
def func1(a, b):
print "func1", a, b
def func2(a, b, c):
print "func2", a, b, c
if __name__ =='__main__':
if len(sys.argv) == 3:
func1(sys.argv[1], sys.argv[2])
elif len(sys.argv) == 4:
func2(sys.argv[1], sys.argv[2], sys.argv[3])
You seem to have noticed the first arg is the program itself.
Think about what should happen if the wrong number of arguments is passed.
Have a look at the argparse module
Solution 3:[3]
sys.argv will get you the arguments the script was called with e.g. if you run your script like this:
python script.py arg1 arg2
sys.argv will be:
["script.py", "arg1", "arg2"]
Also the builtin len function will return the length of an array. So for the above example len should be 3.
Knowing this you should be able to write your code.
If you struggle getting this to work here is a hint:
import sys
arg = sys.argv
if len(arg) == 3:
func1(arg[1], arg[2])
elif len(arg) == 4:
func2(arg[1], arg[2], arg[3])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cat |
| Solution 2 | doctorlove |
| Solution 3 | Ann Zen |
