python字符串传参_python – 使用argparse,传递一个任意字符串作为参数,以便在脚本中使用...

要获得您正在寻找的内容,诀窍是使用parse_known_args()而不是parse_args():

#!/bin/env python

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-a', action="store_true")

parser.add_argument('-b', action="store_true")

opts = parser.parse_known_args()

# Print info about flags

if opts[0].a: print('You set the option "-a"')

if opts[0].b: print('You set the option "-b"')

# Collect remainder (opts[1] is a list (possibly empty) of all remaining args)

if opts[1]: print('You passed the strings %s' % opts[1])

编辑:

以上代码显示以下帮助信息:

./clargs.py -h

usage: clargs_old.py [-h] [-a] [-b]

optional arguments:

-h, --help show this help message and exit

-a

-b

如果你想告诉用户可选的任意参数,我能想到的唯一解决方案是继承ArgumentParser并自己编写.

例如:

#!/bin/env python

import os

import argparse

class MyParser(argparse.ArgumentParser):

def format_help(self):

help = super(MyParser, self).format_help()

helplines = help.splitlines()

helplines[0] += ' [FOO]'

helplines.append(' FOO some description of FOO')

helplines.append('') # Just a trick to force a linesep at the end

return os.linesep.join(helplines)

parser = MyParser()

parser.add_argument('-a', action="store_true")

parser.add_argument('-b', action="store_true")

opts = parser.parse_known_args()

# Print info about flags

if opts[0].a: print('You set the option "-a"')

if opts[0].b: print('You set the option "-b"')

# Collect remainder

if opts[1]: print('You passed the strings %s' % opts[1])

其中显示以下帮助信息:

./clargs.py -h

usage: clargs.py [-h] [-a] [-b] [FOO]

optional arguments:

-h, --help show this help message and exit

-a

-b

FOO some description of FOO

请注意在“使用”行中添加[FOO],在“可选参数”下添加帮助中的FOO.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值