在 Python 中将 argparse 与 sys.argv 结合使用 [英] Using argparse in conjunction with sys.argv in Python
问题描述
我目前有一个脚本,它通过 sys.argv
变量使用文件通配符,如下所示:
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:]:
这非常适合处理一堆文件;但是,我也想将它与 argparse
模块一起使用.所以,我希望我的程序能够处理如下内容:
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?
推荐答案
如果我没猜错的话,您的问题是将文件列表和一些标志或可选参数一起传递给命令.如果我猜对了,那么您只需要利用 argparse 中的参数设置:
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:
文件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)
上面的注释行通知解析器期望一个未定义数量 >= 0 (nargs ='*'
) 的位置参数.
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!
这篇关于在 Python 中将 argparse 与 sys.argv 结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!