Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using argparse in conjunction with sys.argv in Python

I currently have a script, which uses file globbing via the sys.argv variable like this:

if len(sys.argv) > 1:
        for filename in sys.argv[1:]:

This works great for processing a bunch of files; however, I would like to use this with the argparse module as well. So, I would like my program to be able to handle something like the following:

foo@bar:~$ myScript.py --filter=xyz *.avi

Has anyone tried to do this, or have some pointers on how to proceed?

like image 788
mevatron Avatar asked Dec 07 '11 23:12

mevatron


People also ask

Does Argparse use SYS argv?

The argparse module makes it easy to write user-friendly command-line interfaces. It parses the defined arguments from the sys. argv . The argparse module also automatically generates help and usage messages, and issues errors when users give the program invalid arguments.

How do I parse SYS argv in Python?

Parsing Command Line options and argumentsPython provides a module named as getopt which helps to parse command line options and arguments. It provides a function – getopt, which is used for parsing the argument sequence:sys. argv. argv: argument list to be passed.

How do you pass arguments to Argparse?

After importing the library, argparse. ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser. add_argument() .

Why click instead of Argparse?

Click actually implements its own parsing of arguments and does not use optparse or argparse following the optparse parsing behavior. The reason it's not based on argparse is that argparse does not allow proper nesting of commands by design and has some deficiencies when it comes to POSIX compliant argument handling.


1 Answers

If I got you correctly, your question is about passing a list of files together with a few flag or optional parameters to the command. If I got you right, then you just must leverage the argument settings in argparse:

File p.py

import argparse

parser = argparse.ArgumentParser(description='SO test.')
parser.add_argument('--doh', action='store_true')
parser.add_argument('files', nargs='*')  # This is it!!
args = parser.parse_args()
print(args.doh)
print(args.files)

The commented line above inform the parser to expect an undefined number >= 0 (nargs ='*') of positional arguments.

Running the script from the command line gives these outputs:

$ ./p.py --doh *.py
True
['p2.py', 'p.py']
$ ./p.py *.py
False
['p2.py', 'p.py']
$ ./p.py p.py
False
['p.py']
$ ./p.py 
False
[]

Observe how the files will be in a list regardless of them being several or just one.

HTH!

like image 74
mac Avatar answered Sep 27 '22 23:09

mac