目前我的代码看起来像这样.它允许我解析程序脚本获得的多个参数.是否有更接近"最佳实践"的方式?我还没有看到实际使用输出的代码argparse,只是如何设置它.
def useArguments():
x = 0
while x <= 5:
if x == 0:
if args.getweather != None:
getWeather(args.getweather)
if x == 1:
if args.post != None:
post(args.post)
if x == 2:
if args.custompost != None:
custompost(args.custompost)
if x == 3:
if args.list != None:
listAccounts(args.list)
if x == 4:
if args.add != None:
addAccount(args.add[0])
if x == 5:
if args.edit != None:
editAccount(args.edit[0])
x = x + 1
if __name__ == '__main__':
updateConfig()
parser = argparse.ArgumentParser(description='Post Yahoo …Run Code Online (Sandbox Code Playgroud) 使用argparse,有没有办法接受一系列数字并将它们转换成列表?
例如:
python example.py --range 0-5
Run Code Online (Sandbox Code Playgroud)
是否有某种方式输入该表单中的命令行参数,最终得到:
args.range = [0,1,2,3,4,5]
Run Code Online (Sandbox Code Playgroud)
还有可能输入--range 2 = [2]吗?
我已经测试过optcomplete使用该optparse模块.它的例子是一个简单的文件,所以我可以让它工作.我也使用该argparse模块对其进行了测试,因为之前的模块已被弃用.但我真的不明白python程序是如何以及由谁在tab press上调用的.我怀疑bash与shebang线和argparse(或optparse)模块一起涉及某种方式.我一直试图解决这个问题(现在要阅读源代码).
我有一个更复杂的程序结构,其中包含处理参数的代码片段的包装器.它的argparse.ArgumentParser()实例化和调用add_argument()- 它被超级映射到另一个中间模块以避免重复代码,以及被调用的包装 - 在函数内部.
我想了解这个标签完成在bash和python之间的工作方式(或者就任何其他解释器而言perl).
注意:我对bash完成有一个公平的理解(我刚刚学到了),我想我理解bash(仅)自定义完成.
注意:我已经阅读了其他类似的SO问题,并且没有人真正回答这个问题.
编辑:这是bash函数.
我已经理解了python模块如何通过读取os.environ变量值 来了解在命令行中输入的单词
$COMP_WORDS
$COMP_CWORD
$COMP_LINE
$COMP_POINT
$COMPREPLY
Run Code Online (Sandbox Code Playgroud)
这些变量仅在按Tab键上具有值.我的问题是如何触发python模块?
class StartAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
print "Hello"
start.add_argument('-s', '--start', action=StartAction)
Run Code Online (Sandbox Code Playgroud)
我知道通常让行为像'store_true'会阻止参数的要求,但是有没有办法使用自定义动作并且仍然不需要传递参数?
所以我想要的是:
python example.py -s
你好
我正在查看内置argparse._AppendAction的源代码,它实现了"append"操作,并对它的实现方式感到困惑:
def __call__(self, parser, namespace, values, option_string=None):
items = _copy.copy(_ensure_value(namespace, self.dest, []))
items.append(values)
setattr(namespace, self.dest, items)
Run Code Online (Sandbox Code Playgroud)
要打破它:
_ensure_value就像dict.setdefault属性一样.也就是说,如果namespace有一个带有名称的属性,self.dest则返回它,如果没有,则将其设置为[]并返回._copy.copy(x)返回一个浅表副本.什么x是列表,它就像list(x)(但更慢).namespace.self.dest属性namespace被副本覆盖,这应该导致旧列表被垃圾收集.为什么会以这样一种迂回而低效的方式,为每个附加物扔掉一个完整的清单?为什么这不够?
def __call__(self, parser, namespace, values, option_string=None):
items = _ensure_value(namespace, self.dest, [])
items.append(values)
Run Code Online (Sandbox Code Playgroud) 我正在尝试学习argparse以便在我的程序中使用它,语法应该是这样的:
-a --aLong <String> <String>
-b --bLong <String> <String> <Integer>
-c --cLong <String>
-h --help
Run Code Online (Sandbox Code Playgroud)
我有这个代码:
#!/usr/bin/env python
#coding: utf-8
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Lorem Ipsum')
parser.add_argument('-a','--aLong', help='Lorem Ipsum', required=False)
parser.add_argument('-b','--bLong', help='Lorem Ipsum', required=False)
parser.add_argument('-c','--cLong', help='Lorem Ipsum', required=False)
parser.add_argument('-h','--help', help='Lorem Ipsum', required=False)
parser.parse_args()
Run Code Online (Sandbox Code Playgroud)
问题是,我在官方文档中看过,看过YouTube视频等,但我无法理解如何确定"主要参数"的"子参数"的数量?
示例:myApp.py -b Foobar 9000,如何设置-b必须有两个"子参数",如何获取值,Foobar和9000?
还有一个疑问,我知道我可以设置一个参数是否存在required,但是我想让我的程序只在至少传递一个参数时才执行,所提到的四个参数中的任何一个.
也许这是一个愚蠢的问题,但对不起,我无法理解,希望有人在这里有"老师的力量"来解释它.
我正在尝试使用 argparse 的输出(简单的 argparse 只有 4 个位置参数,函数的每次启动都取决于设置为 True 的变量)
Namespace(battery=False, cache=True, health=False, hotspare=False)
Run Code Online (Sandbox Code Playgroud)
目前,我正在尝试找出如何最好地要求 python 查看这些变量之一何时设置为 True;不必像我现在那样进行硬编码:
if args.battery is True:
do_something()
elif args.cache is True:
do_something_else()
etc ...
Run Code Online (Sandbox Code Playgroud)
我宁愿只使用一个命令来检查命名空间中是否存在变量以及它是否设置为 True;但我一生都无法弄清楚如何以有效的方式做到这一点。
我正在尝试解析命令行参数,以便下面的三种可能性是可能的:
script
script file1 file2 file3 …
script -p pattern
Run Code Online (Sandbox Code Playgroud)
因此,文件列表是可选的.如果-p pattern指定了一个选项,则命令行上不能有任何其他选项.以"用法"格式表示,它可能看起来像这样:
script [-p pattern | file [file …]]
Run Code Online (Sandbox Code Playgroud)
我认为用Python的argparse模块做到这一点的方法是这样的:
parser = argparse.ArgumentParser(prog=base)
group = parser.add_mutually_exclusive_group()
group.add_argument('-p', '--pattern', help="Operate on files that match the glob pattern")
group.add_argument('files', nargs="*", help="files to operate on")
args = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)
但Python抱怨我的位置参数需要是可选的:
Traceback (most recent call last):
File "script", line 92, in <module>
group.add_argument('files', nargs="*", help="files to operate on")
…
ValueError: mutually exclusive arguments must be optional
Run Code Online (Sandbox Code Playgroud)
但argparse文档说该"*"参数 …
我有一些按组分类的命令行参数如下:
cmdParser = argparse.ArgumentParser()
cmdParser.add_argument('mainArg')
groupOne = cmdParser.add_argument_group('group one')
groupOne.add_argument('-optA')
groupOne.add_argument('-optB')
groupTwo = cmdParser.add_argument_group('group two')
groupTwo.add_argument('-optC')
groupTwo.add_argument('-optD')
Run Code Online (Sandbox Code Playgroud)
我如何解析上面的内容,以便最终得到三个不同的Namespace对象?
global_args - containing all the arguments not part of any group
groupOne_args - containing all the arguments in groupOne
groupTwo_args - containing all the arguments in groupTwo
Run Code Online (Sandbox Code Playgroud)
谢谢!
我使用argparse来处理输入参数,并使用parser.print_help()输出以下内容:
optional arguments:
-h, --help show this help message and exit
-t TEMPLATES, --templates TEMPLATES
template names to make, should be defined as section
name in conf, and have related file in templates/
folder
-c CONFPATH, --confpath CONFPATH
configuration path for template detail info
Run Code Online (Sandbox Code Playgroud)
我的代码如下所示:
import argparse
parser = argparse.ArgumentParser(prog='base_maker', description='template maker')
parser.add_argument('-t', '--templates', help='template names to make, should be defined as section name in conf, and have related file in templates/ folder', type=str)
parser.add_argument('-c', '--confpath', help='configuration path for template …Run Code Online (Sandbox Code Playgroud) argparse ×10
python ×10
arguments ×1
autocomplete ×1
bash ×1
command-line ×1
namespaces ×1
parameters ×1
python-3.x ×1
shebang ×1