1

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
1
  • Use the argparse module Commented Oct 29, 2013 at 5:56

3 Answers 3

1

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:])
Sign up to request clarification or add additional context in comments.

Comments

0

Use exception handling(EAFP):

try:
    branch = sys.argv[1]
except IndexError:
    branch = ''

Comments

0

You can use:

branch = sys.argv[1] if len(sys.argv) >= 2 else ''

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.