我正在试验 argparse,该程序有效,但默认值无效。这是我的代码:
'''This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument.'''
import argparse
import sys
def calc(args):
#Enable variables within the function to take on values from 'args' object.
operation = args.operation
x = args.x
y = args.y
if (operation == "add"):
return x + y
elif (operation == "sub"):
return x - y
parser = argparse.ArgumentParser(description="This is a summing program") #parser is an object …Run Code Online (Sandbox Code Playgroud) 我将 argparse 与几个子解析器一起使用。我希望我的程序在 args 中的任何地方都采用详细程度的选项,包括子解析器。
from argparse import ArgumentParser
p = ArgumentParser()
p.add_argument('--verbose', '-v', action='count')
sub = p.add_subparsers()
a = sub.add_parser('a')
print(p.parse_args())
Run Code Online (Sandbox Code Playgroud)
默认情况下,如果用于子解析器,主解析器的选项将抛出错误:
$ python tmp.py -v a
Namespace(verbose=1)
$ python tmp.py a -v
usage: tmp.py [-h] [--verbose] {a} ...
tmp.py: error: unrecognized arguments: -v
Run Code Online (Sandbox Code Playgroud)
我从这个答案中查看了父解析器。
from argparse import ArgumentParser
parent = ArgumentParser(add_help=False)
parent.add_argument('--verbose', '-v', action='count')
main = ArgumentParser(parents=[parent])
sub = main.add_subparsers()
a = sub.add_parser('a', parents=[parent])
print(main.parse_args())
Run Code Online (Sandbox Code Playgroud)
但是由于某种原因,没有一个共享标志在主解析器上工作。
$ python tmp2.py a -vvv
Namespace(verbose=3)
$ python tmp2.py -vvv …Run Code Online (Sandbox Code Playgroud) 我一直在努力让 Google Assistant 在我的 Raspberry Pi 3 上工作。它正在工作,但我在让这个特定步骤工作时遇到问题:https : //developers.google.com/assistant/sdk/guides/library/蟒蛇/扩展/句柄设备命令
此步骤包括向 Pi 发送开/关命令以打开或关闭 LED 灯泡。我已经确认面包板和 LED 设置正确,因为我可以通过 python 脚本打开或关闭 LED。
但是,按照该页面中的步骤并尝试运行以下命令“python hotword.py --device_model_id my-model”(实际上是:python hotword.py --device_model_id assistantraspi-1d671-pigooglev2-8n98u3)后,我得到以下错误:ImportError: No module named pathlib2
我包含了该文件的副本 (hotword.py)
#!/usr/bin/env python
# Copyright (C) 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# …Run Code Online (Sandbox Code Playgroud) 我有通过命令行执行它时运行良好的 Python 脚本。我想要做的是将此脚本导入另一个 python 文件并从那里运行它。
问题是初始脚本需要参数。它们的定义如下:
#file one.py
def main(*args):
import argparse
parser = argparse.ArgumentParser(description='MyApp')
parser.add_argument('-o','--output',dest='output', help='Output file image', default='output.png')
parser.add_argument('files', metavar='IMAGE', nargs='+', help='Input image file(s)')
a = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)
我将此脚本导入另一个文件并传递了参数:
#file two.py
import one
one.main('-o file.png', 'image1.png', 'image2.png')
Run Code Online (Sandbox Code Playgroud)
但是虽然我将输入图像定义为参数,但仍然出现以下错误:
usage: two.py [-h] [-o OUTPUT]
IMAGE [IMAGE ...]
two.py: error: the following arguments are required: IMAGE
Run Code Online (Sandbox Code Playgroud) 我想获取传递给sys.argv具有格式的所有参数
someprogram.py --someparameter 23 -p 42 -anotherparam somevalue。
结果我正在寻找一个包含所有变量的命名空间,已经解析。
据我了解,argparse 期望用户定义他期望的参数。
有什么办法可以用 argparse 做到这一点?谢谢 !
我正在编写一个 python 程序,我想要一个以特定方式运行的命令行界面
命令行界面应接受以下调用:
my_prog test.svg foo
my_prog --font=Sans test.svg foo
Run Code Online (Sandbox Code Playgroud)
(它将生成一个 svg,其中包含foo以指定或默认字体编写的单词)
现在我希望也能够让这个命令接受以下调用...
my_prog --list-fonts
Run Code Online (Sandbox Code Playgroud)
这将列出--font由系统上可用的字体确定的所有有效选项。
我正在使用argparse,我有这样的事情:
parser = argparse.ArgumentParser()
parser.add_argument('output_file')
parser.add_argument('text')
parser.add_argument('--font', help='list options with --list-fonts')
parser.add_argument('--list-fonts', action='store_true')
args = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)
但是,这不会使该--list-fonts选项表现得像我希望的那样,因为仍然需要两个位置参数。
我也尝试过使用子解析器,但这些仍然需要一种解决方法来防止每次都需要其他选项。
如何使用 argparse 获得所需的行为。
我正在使用 Python 3 argparse 来获取命令行参数。我有一个带有默认值的可选参数。当我读取它的值时,是否可以知道用户是手动输入的值还是默认值?
早些时候,我设计了如上。现在,我想存储以前使用的首选项。因此,如果用户没有为可选参数输入任何值,我想从以前的使用中获取值(如果有)。所以,我想确定该值是作为默认值还是用户给定的值。
编辑 1:我有多个这样的参数。我知道我可以删除参数的默认值并稍后以编程方式分配它们。我只想知道是否有更简单的解决方案
我正在尝试使用 mypy 来检查我的程序。该程序使用 argparse 来解析命令行参数。我想为命令行参数添加类型提示。
import argparse
import typing
# define example types and a function that uses them
Seconds = typing.NewType("Seconds", float)
Minutes = typing.NewType("Minutes", float)
def sec_to_min(s: Seconds) -> Minutes:
return Minutes(s / 60)
# specify arguments and parse them
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--time", default=1., type=float,
help="time in seconds")
args = parser.parse_args()
try:
# mypy reveals type Any
reveal_type(args.time)
except NameError:
pass
# (1) passes type check
seconds: Seconds = args.time
# (2) passes type check
sec_to_min(args.time) …Run Code Online (Sandbox Code Playgroud) 我想访问 python 类函数中的 args 值。
例如,我在下面编写了一个示例测试程序。
#!/usr/bin/env python
import argparse
class Weather(object):
def __init__(self):
self.value = 0.0
def run(self):
print('in weather.run')
if (args.sunny == True):
print('It\'s Sunny')
else:
print('It\'s Not Sunny')
def main():
argparser = argparse.ArgumentParser(
description=__doc__)
argparser.add_argument(
'--sunny', action='store_true', dest='sunny', help='set if you want sunny weather')
args = argparser.parse_args()
print('args.sunny = ', args.sunny)
weather = Weather()
weather.run()
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
当我运行它(./test.py)时,出现以下错误。
('args.sunny = ', False)
in weather.run
Traceback (most recent call last):
File "./test.py", line 30, in …Run Code Online (Sandbox Code Playgroud) 我正在使用具有alias 的子解析器/子命令。
我正在使用dest子解析器的选项来存储子命令的名称,以便以后可以获取它。
目前,如果该子的名字是reallyLongName和别名是r(比方说),则dest选择专卖店或者reallyLongName 或 r确切-无论我输入囤积。这很烦人,因为我现在必须检查命令的名称或其任何别名才能识别命令。
有没有办法让 argparse 将子命令的名称以dest某种单一的、规范的文本字符串存储在字段中?
例如,给定以下代码:
import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='command', help='sub-command help')
parser_ag = subparsers.add_parser( 'mySubcommand',
aliases=['m'],
help='Subcommand help')
print(parser.parse_args('mySubcommand'.split()))
print(parser.parse_args('m'.split()))
Run Code Online (Sandbox Code Playgroud)
产生以下输出:
Namespace(command='mySubcommand')
Namespace(command='m')
Run Code Online (Sandbox Code Playgroud)
期望结果:command两者都具有单一的规范值,例如:
Namespace(command='mySubcommand')
Namespace(command='mySubcommand')
Run Code Online (Sandbox Code Playgroud)