python argparse 和opencv模块的组合使用,在Python中结合使用argparse和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:]:

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?

解决方案

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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值