argparse当我混合位置参数,可选参数和时,我遇到了一个问题argparse.REMAINDER
parser = argparse.ArgumentParser()
parser.add_argument('verbose', action="store")
parser.add_argument('--config', '-c', nargs="?", dest="config_file")
parser.add_argument('--dry-run', action="store_true", dest="dryrun")
parser.add_argument('args', nargs=argparse.REMAINDER, action="store")
Run Code Online (Sandbox Code Playgroud)
样品运行:
python test.py verose="5" --config config.xml graph --dry-run
Run Code Online (Sandbox Code Playgroud)
预期产量:
verbose = "5"
config_file = config.xml
dryrun = True
args = ['graph']
Run Code Online (Sandbox Code Playgroud)
实际产量:
verbose = "5"
config_file = config.xml
dryrun = False
args = ['graph', '--dry-run']
Run Code Online (Sandbox Code Playgroud)
我的要求是我有verbose,-c,--config并--dry-run作为命令行选项,在命令行提供的任何其他选项应存放在列表中args,不论在命令行的参数出现的顺序的.请帮助我做错了.另外还有其他更好的python命令行解析器吗?
我使用argparse来处理命令行参数.代码工作正常.但是,只要我在main中添加unittest.main(),它就无法正常工作.
我正进入(状态:
I am here
option -i not recognized
Usage: testing.py [options] [test] [...]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
-f, --failfast Stop on first failure
-c, --catch Catch control-C and display results
-b, --buffer Buffer stdout and stderr during test runs
Examples:
testing.py - run default set of tests
testing.py MyTestSuite - run suite 'MyTestSuite'
testing.py MyTestCase.testSomething - run MyTestCase.testSomething
testing.py MyTestCase - run all 'test*' test methods
in MyTestCase
Run Code Online (Sandbox Code Playgroud)
我这样做: …
首先,我很抱歉这个糟糕的头衔.我无法正确制定摘要的事实可能是我当前问题的80%.
我正在编写一个命令行程序来包装其他命令行程序,如下所示:
my_wrapper.py --some options -for --the wrapper original_program --and its -options
Run Code Online (Sandbox Code Playgroud)
在某些情况下,此命令将替换原始程序的调用:
original_program --and its -options
Run Code Online (Sandbox Code Playgroud)
我想提取包装器所需的选项,但保持原始程序名称和参数不变,顺序完全相同.我不能对包装程序的参数做出任何假设.
用argparse可以做到吗?如何?
我认为使用(已弃用)optparse模块就像args从行中读取一样简单
(options, args) = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)
对于好奇的,包装器的目标是帮助用户在HPC群集上提交作业.它的职责是照顾我们编写自定义脚本,启动它和检索结果的所有特殊要求.
我有一个谷歌协议缓冲区定义,看起来像跟随:
message Foo {
required string Name = 1;
optional string Address = 2;
optional string NickName = 3;
optional int32 height = 4;
}
Run Code Online (Sandbox Code Playgroud)
现在在python中,我想列出上面的所有属性,但只列出那些属性.但是,交互式python,我看到谷歌定义了更多的字段.所以这似乎有问题.
我已经看了一些关于内省的stackoverflow帖子.有一个看起来不错的检查模块,但问题是谷歌协议缓冲区为我定义的其他成员.
有办法吗?
这就是我想做的事情.我有一个python实用程序,从命令行填写上述字段.我使用argparse,我会:
parser = argparse.ArgumentParser(...)
parser.add_argument( "--attribute_name", blah)
Run Code Online (Sandbox Code Playgroud)
我想将add_argument()放在循环中,并根据proto文件定义使其动态化.基本上,每次我更改proto文件时,我都不想继续修改实用程序的代码.好像我应该能够在python中做到这一点.我只是不知道如何.
有人有建议吗?
谢谢.
有关其他信息,我采用上面的示例,并使用protoc编译它.这是交互式输出:
>>> import hello_pb2
>>> h = hello_pb2.Foo()
>>> dir(h)
['ADDRESS_FIELD_NUMBER', 'Address', 'ByteSize', 'Clear', 'ClearExtension', 'ClearField', 'CopyFrom', 'DESCRIPTOR', 'FindInitializationErrors', 'FromString', 'HEIGHT_FIELD_NUMBER', 'HasExtension', 'HasField', 'IsInitialized', 'ListFields', 'MergeFrom', 'MergeFromString', 'NAME_FIELD_NUMBER', 'NICKNAME_FIELD_NUMBER', 'Name', 'NickName', 'ParseFromString', 'RegisterExtension', 'SerializePartialToString', 'SerializeToString', 'SetInParent', '_InternalParse', '_InternalSerialize', '_Modified', '_SetListener', '__class__', '__deepcopy__', …Run Code Online (Sandbox Code Playgroud) 基本用途:
my_framework create Project_title /path/to/project
要么
my_framework create Project_title (即使用当前工作目录)
要么
my_framework update (即更新my_framework而不是创建新项目)
我知道我可以name通过提供默认值来使其成为可选项,但实际上,如果用户输入了第一个参数,name则不是可选的create.
我想出的最佳解决方案是使用默认值name,然后,如果参数name等于其默认值,则抛出错误.但如果有办法让argparse为我做这项工作,我宁愿学会这样做.
写两个剧本, my_framework_create并my_framework_update不会从审美角度吸引我.
#!/usr/bin/env python
import argparse
import os
import shutil
from subprocess import call
template_path = "/usr/local/klibs/template"
parser = argparse.ArgumentParser("MY_FRAMEWORK CLI", description='Creates a new MY_FRAMEWORK project or updates MY_FRAMEWORK')
parser.add_argument('action', choices=['create', 'update'], type=str, help='<help text>')
parser.add_argument('name', type=str, help='<help text>')
parser.add_argument('path', default=os.getcwd(), nargs="?", type=str, help='<help text>')
args = parser.parse_args()
if …Run Code Online (Sandbox Code Playgroud) 目前--resize我创建的标志是boolean,意味着我的所有对象都将被调整大小:
parser.add_argument("--resize", action="store_true", help="Do dictionary resize")
# ...
# if resize flag is true I'm re-sizing all objects
if args.resize:
for object in my_obects:
object.do_resize()
Run Code Online (Sandbox Code Playgroud)
有没有办法实现argparse参数,如果传递为boolean flag(--resize)将返回true,但如果传递value(--resize 10),将包含值.
例:
python ./my_script.py --resize # Will contain True that means, resize all the objectspython ./my_script.py --resize <index> # Will contain index, that means resize only specific object是否有一种简单的方法来使用--toggle和--no-toggle使用Python的argparse标记?
现在我正在使用类似于以下内容的东西:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--toggle',
action='store_true',
dest='toggle')
parser.add_argument('--no-toggle',
action='store_true',
default=True,
dest='notoggle')
options = parser.parse_args([])
Run Code Online (Sandbox Code Playgroud)
我只是手动解析long if链中的可能性,但如果有一种方法可以整理它并且状态由解析器立即存储在一个目标中,那将会很好,例如options.toggle.这是可行的,如果可行,怎么样?
一个有点相关的答案是Python argparse切换标志但是我有兴趣使用--no-longopts store_false切换前缀(类似于-前面提到的链接中概述的shortopts切换前缀).
我有一个CLI工具,并且想测试是否提示用户确认选择input()。这等同raw_input()于在Python 2中使用。
测试的(释义)代码如下所示:
import sys
import argparse
def confirm():
notification_str = "Please respond with 'y' or 'n'"
while True:
choice = input("Confirm [Y/n]?").lower()
if choice in 'yes' or not choice:
return True
if choice in 'no':
return False
print(notification_str)
def parse_args(args):
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--destructive', action='store_true')
return parser.parse_args()
def main():
args = parse_args(sys.argv[1:])
if args.destructive:
if not confirm():
sys.exit()
do_stuff(args)
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
我正在使用pytest作为我的框架。我该如何做才能测试CLI中是否显示确认提示?如果我尝试比较,则会stdout收到错误:OSError: reading from stdin while …
我正在尝试编写一个脚本,用户可以从中选择三个不同的选项:
python foo.py
python foo.py -a
python foo.py -b address_arg data_arg
Run Code Online (Sandbox Code Playgroud)
如果用户选择了最后一个选项,我需要它们为地址和数据提供两个额外的参数.
我目前有它工作,所以它需要一个参数,比如这里的地址:
parser.add_argument('-b', '--boo', dest='address', type=str, help="Help message")
Run Code Online (Sandbox Code Playgroud)
如果我跑,哪个有效
python foo.py -b 0x00
Run Code Online (Sandbox Code Playgroud)
但是,我如何要求用户提供数据的第二个参数?
我将Python3 argparse用于复杂的命令行界面。为了避免误解,有很多论点,其中一些是“冗长的”。
parser = argparse.ArgumentParser(description='Command-line interface')
parser.add_argument('--long-param-one',
help='Long param one description',
dest='lond_param_one',
required=True)
parser.add_argument('--long-param-two',
help='Long param two description',
dest='lond_param_two',
required=True)
Run Code Online (Sandbox Code Playgroud)
当参数名称足够长而目标变量也足够长时,当您使用以下命令调用脚本时,它将导致格式难看 --help
Command-line interface
optional arguments:
-h, --help show this help message and exit
--long-param-one LONG_PARAM_ONE
Long param one description
--long-param-two LONG_PARAM_TWO
Long param two description
Run Code Online (Sandbox Code Playgroud)
我的意思是,参数和值在一个字符串上,描述在另一个字符串上,即使控制台右侧有足够的空间将其放在一行中。就像第一个参数--help一样。当您有30-40个参数时,命令行帮助的可读性确实变差了