在Python中结合使用argparse和sys.argv [英] Using argparse in conjunction with sys.argv in Python

查看:307
本文介绍了在Python中结合使用argparse和sys.argv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个脚本,该脚本通过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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆