Search code examples
pythoncommand-line-argumentsgetopt

How do get parameter without name in python


I am trying to write a python script which accepts optional input parameters plus an input file:

./script --lines 1 file.txt

should take 1 for the number of lines (--lines) and then take file.txt as an input file. However, getopt does not even see "file.txt" since it does not have a parameter name in front of it.

How can I get the filename? I already considered using sys.arv[-1], but this means when I run:

./script --lines 1

then 1 will be taken as the input filename. My script will then throw an error (if no file named 1 exists):

error: file '1' no found

This works, but is not a great solution. Is there a way around this?


Solution

  • Definitely use argparse -- It's included in python2.7+ and can easily be installed for older versions:

    parser = argparse.ArgumentParser()
    parser.add_argument('--lines', type=int, default=0, help='number of lines')
    parser.add_argument('file', help='name of file')
    namespace = parser.parse_args()
    print namespace.lines
    print namespace.file