Reputation: 1188
I would like to define a function that checks whether any argv were give to a command line, otherwise would print a string or return two strings. Here is the code:
import sys
def get_input():
if len(sys.argv) > 1:
path_input_text = sys.argv[1]
path_basic_conf = sys.argv[2]
return path_input_text, path_basic_conf
elif len(sys.argv) == 1:
print "Takes at least two arguments"
else:
print "No arguments entered"
return 'file.txt', 'file.xml'
I try to call the function like this:
a,b = get_input()
It works when I give two arguments but it fails in the other two cases, i.e. the elif and else statements. How can I make it work? Should I be using the try/except statement? thanks
EDIT 1
when I try 1 args only:
IndexError: list index out of range
when I try with no args:
TypeError: 'NoneType' object is not iterable
In the case of 1 args given I would like to raise an error rather then returning None,None.
Upvotes: 0
Views: 3480
Reputation: 7268
argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string. (reference : https://docs.python.org/2/library/sys.html)
Try this :
import sys
def get_input():
if len(sys.argv) > 2:
#print (sys.argv[0])
path_input_text = sys.argv[1]
path_basic_conf = sys.argv[2]
return path_input_text, path_basic_conf
elif len(sys.argv) ==2:
#print (sys.argv[0])
print ("Takes at least two arguments")
return None,None
else:
#print (sys.argv[0])
print ("No arguments entered")
return 'file.txt', 'file.xml'
a,b = get_input()
print (a)
print (b)
Output :
D:\>python so.py 1
Takes at least two arguments
None
None
D:\>python so.py
No arguments entered
file.txt
file.xml
D:\>python so.py 1 2
1
2
Upvotes: 2
Reputation: 2134
In one case you return nothing, you should return something: None for example.
elif len(sys.argv) ==1:
print "Takes at least two arguments"
Should be:
elif len(sys.argv) ==1:
print "Takes at least two arguments"
return None,None
Your length should start at 2 not 1
if len(sys.argv) > 2:
Upvotes: 0