Python can't parse command line arguments

66 views Asked by At

I'm trying to get the arguments by using getopt

import sys
import getopt
import time
from datetime import timedelta
start_time = time.monotonic()


filename = ''
startIndex = 1
debug = False
outputFile = 'output.csv'

try:
    opts, args = getopt.getopt(sys.argv[1:], "hc:o:", ["help","counter=", "output="])
except getopt.GetoptError as err:
        # print help information and exit:
        print(err)  # will print something like "option -a not recognized"
        sys.exit(2)
 
for opt, arg in opts:
   if opt == '-h':
      print ('help info')
      sys.exit()
   elif opt in ("-o", "--output"):
      outputfile = arg
   elif opt in ("-c", "--counter"):
      startIndex = arg

filename = sys.argv[1]

print(outputFile)
print(startIndex)
print(debug)
print(opts)
print(args)

Output:

 python pSRA.py rs.txt -o out.csv -c 3 
output.csv
1
False
[]
['rs.txt', '-o', 'out.csv', '-c', '3']

when printing the args they are all there, however opts is an empty list. What am I doing wrong?

1

There are 1 answers

0
user2357112 On

From the docs:

Note: Unlike GNU getopt(), after a non-option argument, all further arguments are considered also non-options. This is similar to the way non-GNU Unix systems work.

rs.txt is a non-option argument, so everything after it is also considered a non-option argument.

If you want GNU-style behavior, you can use getopt.gnu_getopt(), or if you aren't particularly attached to getopt, you can use a different argument parser, like argparse.