Reputation: 65
I have the following snippet where i am checking for first argument and runninginto following error..can anyone help on how to make the first argument optional?
SNIPPET CODE:-
branch = ''
if sys.argv[1]:
branch = sys.argv[1]
ERROR:-
Traceback (most recent call last):
File "test.py", line 102, in <module>
main()
File "test.py", line 66, in main
if sys.argv[1]:
IndexError: list index out of range
Upvotes: 1
Views: 958
Reputation: 1095
For inputting parameters into python you can use the getopt module. Here parameters can be optional and can be inputted in any order as long at the correct flag is present.
In the example below the user has two optional parameters to set, the input-file name and the database name. The code can be called using
python example.py -f test.txt -d HelloWorld
or
python example.py file=test.txt database=HelloWorld
or a mix and match of both. The flags and names can be changed to reflect your needs.
import getopt
def main(argv):
inputFileName = ''
databaseName = ''
try:
opts, args = getopt.getopt(argv,"f:d:",["file=","database="])
except getopt.GetoptError:
print('-f <inputfile> -d <databasename> -c <collectionname>')
sys.exit()
for opt, arg in opts:
if opt in ('-f','--file'):
inputFileName = arg
elif opt in ('-d','--database'):
databaseName = arg
if __name__ == "__main__":
main(sys.argv[1:])
Upvotes: 1
Reputation: 191
You can use:
branch = sys.argv[1] if len(sys.argv) >= 2 else ''
Upvotes: 0
Reputation: 250951
Use exception handling(EAFP):
try:
branch = sys.argv[1]
except IndexError:
branch = ''
Upvotes: 0