[Tutor] python - files

Peter Otten __peter__ at web.de
Sun Jan 27 04:30:12 EST 2019


Cameron Simpson wrote:

> Mats has mentioned the modules getopt and argparse etc. These are
> primarily aimed at option parsing ("-v", "-o foo"). Your situation
> occurs _after_ the option parsing (in your case, there are no options).

Not argparse. The main advantage over optparse is its handling of positional 
arguments. Your custom logic 

>   def main(argv):
>     cmd = argv.pop(0)   # collect the command word
>     badopts = False
>     # mandatory first argument
>     if not argv:
>       print("%s: missing first argument" % cmd, file=sys.stderr)
>       badopts = True
>     else:
>       first = argv.pop(0)
>       # optional second argument
>       if argv:
>         second = argv.pop(0)    # explicit argument 2, use it
>       else:
>         second = None           # or some otherdefault
>       if argv:
>         print("%s: extra arguments: %r" % (cmd, argv), file=sys.stderr)
>         badopts = true
>     if badopts:
>       print("%s: invalid invocation, aborting" % cmd, file=sys.stderr)
>       return 2
>     ... work with first and second ...

can roughly be replicated with the two lines

parser.add_argument("first")
parser.add_argument("second", nargs="?")

A working script:

$ cat test.py
#!/usr/bin/python3
import argparse

def main():
    parser = argparse.ArgumentParser()

    parser.add_argument("first")
    parser.add_argument("second", nargs="?")

    args = parser.parse_args()

    print("first:", args.first)
    print("second:", args.second)

if __name__ == "__main__":
    main()

$ ./test.py
usage: test.py [-h] first [second]
test.py: error: the following arguments are required: first

$ ./test.py -h
usage: test.py [-h] first [second]

positional arguments:
  first
  second

optional arguments:
  -h, --help  show this help message and exit

$ ./test.py ONE
first: ONE
second: None

$ ./test.py ONE TWO
first: ONE
second: TWO

$ ./test.py ONE TWO THREE
usage: test.py [-h] first [second]
test.py: error: unrecognized arguments: THREE

Argparse makes a usable standard command line interface easy to set up (if 
you need non-standard behaviour it gets a bit harder).

There is also a companion module argcomplete (not in the stdlib) that 
enables autocompletion.




More information about the Tutor mailing list