我想使用argparse从读取或者 stdin 或输入文件。换句话说:
我要求的行为类似于此问题中描述的行为,但我想argparse将没有文件识别为失败的输入。
如何添加可选且不得多次指定的参数?
有效的:
$ ./my.py
$ ./my.py --arg MyArgValue
Run Code Online (Sandbox Code Playgroud)
无效的:
$ ./my.py --arg MyArgValue --arg ThisIsNotValid
Run Code Online (Sandbox Code Playgroud)
如果我添加一个参数,如:
parser.add_argument('--arg', type=str)
Run Code Online (Sandbox Code Playgroud)
无效示例产生一个字符串ThisIsNotValid。我预计会出现解析器错误。
我在 python 和 argparse 上有一些脚本,可选参数之一添加了音译:
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--text',
action='store_true',
help='display a text')
parser.add_argument('-s', '--search',
dest='string',
action='store',
type=str,
help='search in a text')
parser.add_argument('--translit',
action='store_true',
help='transliterate output; usage: prog [-t | -d STRING] --translit')
results = parser.parse_args()
if len(sys.argv) == 1:
parser.print_help()
elif results.text and results.translit::
translit(display_text())
elif results.text and results.translit::
display_text()
elif results.string and results.translit:
translit(search(results.string))
elif results.string:
search(results.string)
Run Code Online (Sandbox Code Playgroud)
输出:
usage: prog [-h] [-t] [-s STRING] [--translit]
optional arguments:
-h, --help show this help message and exit
-t, --text …Run Code Online (Sandbox Code Playgroud) 我尝试使用此语句:
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--music', nargs='*', default=False, const=True)
args = parser.parse_args()
print(args.music)
Run Code Online (Sandbox Code Playgroud)
但是得到了这个错误:
`builtins.ValueError: nargs must be '?' to supply const`
Run Code Online (Sandbox Code Playgroud)
我想做的是:
-m在 args 列表中但没有任何值,args.music 会给我 True-m在 args 列表中并且有“N”个值,args.music 会给我一个所有值的列表-m不在 args 列表中,args,music 将返回 False第二个和最后一个有效,但是当我尝试使用 const 时出现错误
我想实现以下命令行参数解析场景:
我有4个参数:-g,-wid,-w1,和-w2。
-w1并且-w2总是一起出现
-wid和(-w1 -w2)是互斥的,但需要一个或另一个
-g是可选的;如果它没有被指定(-w1 -w2)出现,但不能出现-wid
有没有一种优雅的方法来使用 argparse 实现这一点,但没有子命令(我已经在子命令中了)?
我正在考虑自定义操作,但是在操作的主体中,我需要知道最后一次调用它的时间(即解析最后一个参数的时间),自从参数的数量和顺序可能会有所不同。
一些更多的解释以防万一:我正在编写的工具使用小部件和小工具参数创建小工具-g。小部件要么是现有的小部件,然后通过其 id 引用-wid,要么是使用参数-w1和创建的新小部件-w2。如果-g未指定,则该工具将仅使用(-w1 -w2)而不创建小工具来创建和存储新的小部件。
先感谢您。
我一直在我正在编写的程序中使用 argparse,但它似乎没有创建指定的输出文件。
我的代码是:
parser.add_argument("-o", "--output", action='store', dest='output', help="Directs the output to a name of your choice")
with open(output, 'w') as output_file:
output_file.write("%s\n" % item)
Run Code Online (Sandbox Code Playgroud)
我也试过:
parser.add_argument("-o", "--output", action='store', type=argparse.FileType('w'), dest='output', help="Directs the output to a name of your choice")
output_file.write("%s\n" % item)
Run Code Online (Sandbox Code Playgroud)
发生的错误是:
output_file.write("%s\n" % item)
NameError: name 'output_file' is not defined
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么我会发生这个错误以及我如何解决它?
我所有的代码:
from __future__ import print_function
from collections import defaultdict
from itertools import groupby
import argparse #imports the argparse module so it can be used
from itertools import …Run Code Online (Sandbox Code Playgroud) 我在 python 2.7 中有一个程序,它使用 接受命令行参数argparse,但是如果我尝试输入包含与号的字符串,我会丢失该与号之后的字符。
例如:
我有一个简单的 python 程序只是为了测试命令行参数的输入,并简单地打印出为单个命令行参数输入的内容。
本质上: print args.where
当我用这样的参数运行程序时:
$ python args.py -a http://www.website.com?optionone=one&numbertwo=two
Run Code Online (Sandbox Code Playgroud)
打印到屏幕上的唯一文本是:http : //www.website.com?optionone=one
使用 sys 和 printIng 使用 Argv 时,我有类似的结果
我怎样才能输入完整的字符串?
我想实现 Argparse 介绍中的示例:
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
Run Code Online (Sandbox Code Playgroud)
但就我而言,我希望有更多可能的函数名称可供选择。
def a(): ...
def b(): ...
def c(): ...
parser.add_argument('-f', '--func',
choices=[a, b, c],
required=True,
help="""Choose one of the specified function to be run.""")
parser.func()
Run Code Online (Sandbox Code Playgroud)
像那样使用它不能按预期工作,我明白了
$ python program.py -f=a
program.py: error: argument -f/--func: invalid choice: 'a' (choose from
<function a at 0x7fa15f32f5f0>,
<function …Run Code Online (Sandbox Code Playgroud) 如何检查特定的子解析器?
import argparse
if __name__ == "__main__":
mainparser = argparse.ArgumentParser()
submainadder = mainparser.add_subparsers(title='subcommands')
parser_ut = submainadder.add_parser('unittest')
stuff = mainparser.parse_args()
# if 'unittest' was selected:
# do_things()
Run Code Online (Sandbox Code Playgroud) I'm trying to do mathematical operations between images. I have defined (simplified version of my real code):
parser = argparse.ArgumentParser(description='Arithmetic operations on images')
parser.add_argument("input1", metavar='input1', action='store',
help='list of input images to operate with', nargs="+", type=str)
parser.add_argument("operation", metavar='operation', action='store', type=str,
help='type of operation (+,-,*,/) to be done', nargs=1)
parser.add_argument("input2",metavar='input2', action='store', nargs="+",
type=str, help='image (or value) with which to perform the operation on input1')
Run Code Online (Sandbox Code Playgroud)
This code, produces:
arith.py -h
usage: arith.py [-h] input1 [input1 ...] operation input2 [input2 ...]
Run Code Online (Sandbox Code Playgroud)
so it does …