我正在开发一个包含多个 python 脚本的工具箱。对于其中的一些参数,某些参数可能是数值。根据脚本的不同,有些可能要求值 v 介于 -1 和 1 之间,或者 0 和 1 之间,或者 1 和 10 之间,或者...一个例子是输出图表中的页面宽度,它应该始终为正值。
我可以随时检查 v 是否在要求的范围内。我还可以使用 argparse 为每个范围定义一个操作或类型。给出了使用新类型的示例:
def positive_num(a_value):
"""Check a numeric positive."""
if not a_value > 0:
raise argparse.ArgumentTypeError("Should be positive.")
return a_value
Run Code Online (Sandbox Code Playgroud)
稍后将其添加到解析器中:
parser_grp.add_argument('-pw', '--page-width',
help='Output pdf file width (e.g. 7 inches).',
type=positive_num,
default=None,
required=False)
Run Code Online (Sandbox Code Playgroud)
现在,如果该值是相关系数(或范围内的任何值),则可以使用操作或类型来编写更通用的内容:
def ranged_num(a_value, lowest=-1, highest=1):
"""Check a numeric is in expected range."""
if not (a_value >= lowest and a_value <= highest):
raise argparse.ArgumentTypeError("Not in range.")
return a_value
Run Code Online (Sandbox Code Playgroud)
稍后可以添加如下内容: …
我处于一种奇怪的情况,我需要一个 Python 函数从脚本中运行,然后从我的主代码中调用该脚本。
我想使用该subprocess模块,并知道如何使用它来将参数传递给纯脚本,但问题是,我需要将参数传递给其中的嵌套 Python 函数,其中大部分是可选的并且具有默认值。
我想arparse会以某种方式帮助我做到这一点。
这是我正在尝试的示例:
## Some Argparse, which will hopefully help
import argparse
parser = argparse.ArgumentParser()
## All arguments, with only "follow" being required
parser.add_argument('file_name', help='Name of resulting csv file')
parser.add_argument('sub_name', help='Sub-name of resulting csv file')
parser.add_argument('follow', help='Account(s) to follow', required=True)
parser.add_argument('locations', help='Locations')
parser.add_argument('languages', help='Languages')
parser.add_argument('time_limit', help='How long to keep stream open')
args = parser.parse_args()
## Actual Function
def twitter_stream_listener(file_name=None,
sub_name='stream_',
auth = api.auth,
filter_track=None,
follow=None,
locations=None,
languages=None,
time_limit=20):
... function code …Run Code Online (Sandbox Code Playgroud) 当多次指定相同的参数时,默认的 argparse 行为是最后指定的值“获胜”,覆盖先前的值。我希望 argparse 在多次指定同一参数时显示错误,而不是默默地覆盖第一个指定的值。
那怎么办呢?
我当前的代码:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'-t', '--test', # either of this switches
type=str, # parameter is string
dest='test', # store in 'test'.
required=True # required
)
Run Code Online (Sandbox Code Playgroud)
调用脚本:
myscript.py -t hello -t world
Run Code Online (Sandbox Code Playgroud)
没有错误,test才有价值世界。我希望 argparse 在这种情况下显示错误,因为从我的角度来看,默认行为很容易出错。
我有一个 python 程序,它接受许多参数并运行。使用argparse,我可以定义参数、它们的默认值、它们的解释,并且它可以用作一个方便的容器。所以这对于从命令行传递参数来说都是很好的。
但我也可以使用它来传递代码中的参数以进行 API 调用吗?
我有以下辅助函数用于使用以下方法解析参数argparse:
def get_cli_arguments():
parser = argparse.ArgumentParser(prog='Xtrayce')
parser.add_argument(
"-o", "--output",
default=get_default_output_path(),
help="Supply an output path.",
type=argparse.FileType('wb'),
)
parser.add_argument(
"-d", "--dry",
help="Don't save a file with the output.",
action="store_true",
)
parser.add_argument(
"-s", "--standard",
help="Also scan standard library and modules.",
action="store_true",
)
Run Code Online (Sandbox Code Playgroud)
我希望每当用户指定该--dry标志时,就不会从该参数创建任何文件--output。
当用户指定--dry,同时仍然使用default=和时,“取消”文件创建的最佳方法是什么type=argparse.FileType("wb")?
我正在努力寻找一种将参数传递给docker container基于ubuntu. 我正在与docker-compose.yml.
请看下面的例子!
docker-compose.yml
version: "3"
services:
bcp:
image: ubuntu:18.04
restart: always
tty: true
entrypoint: ["/bin/bash", "/ingestion/bcp-entrypoint.sh"]
volumes:
- ./services/bcp:/ingestion/services/bcp
- ./bcp-entrypoint.sh:/ingestion/bcp-entrypoint.sh
Run Code Online (Sandbox Code Playgroud)
bcp-入口点.sh
apt-get update
apt-get upgrade -y
apt-get clean -y
apt-get install -y python3-pip
...
Run Code Online (Sandbox Code Playgroud)
蟒蛇脚本
required_args.add_argument("--database", metavar="str", type=str, help="database from where to extract", required=True)
Run Code Online (Sandbox Code Playgroud)
我在容器中和主机上调用脚本的方式是python3 -m services.bcp --database foo,它运行得非常完美。问题是,如何在 docker 容器上的主机上实现相同的目标?
基本上,我正在寻找类似的东西docker-compose exec services.bcp --database foo。
我不想用dockerfile!理想情况下,一切都基于docker-compose.
我刚刚在单元测试中添加了一个图形实用程序——基本上,测试的全自动版本只是进行数值比较,但我希望人们能够要求绘图。
如果我使用我的新参数,仅仅使用 argparseunittest.main()就会令人窒息。我目前正在做的是检查该参数,然后从中删除它sys.argv似乎是错误的。
有没有更好的方法给这只猫剥皮?
unittest.main()会采用备用 argv。unittest.main()忽略争论的方法。if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Test correction'
)
parser.add_argument(
'--plot-results',
help='Plot results of cal test',
action='store_true'
)
args = parser.parse_args()
if args.plot_results:
while '--plot-results' in sys.argv:
sys.argv.remove('--plot-results')
unittest.main()
Run Code Online (Sandbox Code Playgroud) 我正在开发一个小型Python程序,需要获取一些命令行参数并使用argparse来显示用法消息.我有这2行
parser.add_argument("-r",type=int,default=1)
parser.add_argument("-c",type=int,default=2)
Run Code Online (Sandbox Code Playgroud)
并且要求是我向用户显示以下消息:
*usage: myprogram.py [-h] [-r ROWS] [-c COLUMNS]*
Run Code Online (Sandbox Code Playgroud)
然而,我向用户展示的是 -
*usage: myprogram.py [-h] [-r R] [-c C]*
Run Code Online (Sandbox Code Playgroud)
如何将[-r R]转换为[-r ROW](并以相同的方式[-c C]转换为[-c COLUMNS])?
我已经看了很多argsparse文档但没有用...
我正在尝试创建一个简单的计算器,它在命令行接受参数.例如,在命令行:
Calculator.py 1 2 44 6 -add
Run Code Online (Sandbox Code Playgroud)
会给我数字的总和.但是,用户如何输入无限量的参数.我知道你必须在函数中使用*args或类似的东西,我只是想知道如何使用argparse将它合并到命令行中.
当你跑步
foo.py -h
要么
foo.py --help,
您将收到有关如何使用foo.py以及需要使用哪些参数的“帮助”消息。有什么方法可以附加到此消息吗?例如打印__doc__?
argparse ×10
python ×10
python-3.x ×2
arguments ×1
bash ×1
command-line ×1
docker ×1
subprocess ×1