python – 使用argparse,传递一个任意字符串作为参数,以便在脚本中使用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 使用argparse,传递一个任意字符串作为参数,以便在脚本中使用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2197字,纯文字阅读大概需要4分钟。
内容图文
![python – 使用argparse,传递一个任意字符串作为参数,以便在脚本中使用](/upload/InfoBanner/zyjiaocheng/826/ce2b82c75d0e48198adcd0ea3cc2b30b.jpg)
如何使用argparse将任意字符串定义为可选参数?
例:
[user@host]$./script.py FOOBAR -a -b
Running "script.py"...
You set the option "-a"
You set the option "-b"
You passed the string "FOOBAR"
理想情况下,我认为论点的立场无关紧要.即:
./script.py -a FOOBAR -b == ./script.py -a -b FOOBAR == ./script.py FOOBAR -a -b
在BASH中,我可以在使用getopts时完成此任务.在处理case循环中的所有所需开关之后,我有一行读取shift $((OPTIND-1)),从那里我可以使用标准的$1,$2,$3等访问所有剩余的参数…
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.
内容总结
以上是互联网集市为您收集整理的python – 使用argparse,传递一个任意字符串作为参数,以便在脚本中使用全部内容,希望文章能够帮你解决python – 使用argparse,传递一个任意字符串作为参数,以便在脚本中使用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。