Using argparse in conjunction with sys.argv in Python

不问归期 提交于 2019-12-04 23:54:21

问题


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?


回答1:


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!




回答2:


Alternatively you may use both in the following way:

import sys
import argparse
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--verbose", help="increase verbosity", action="store_true")
    args, unknown = parser.parse_known_args()
    for file in sys.argv:
        if not file.startswith("-"):
            print(file)

However this will work only for standalone parameters, otherwise the argument values would be treated as file arguments (unless you'll not separate them with space or you'll improve the code further more).



来源:https://stackoverflow.com/questions/8423895/using-argparse-in-conjunction-with-sys-argv-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!