- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我是 python 的新手,我一直在研究如何在使用命令行参数时构建我的简单脚本。
该脚本的目的是自动执行我工作中与图像排序和操作相关的一些日常任务。
我可以指定参数并让它们调用相关函数,但我也想在没有提供参数时设置默认操作。
这是我当前的结构。
parser = argparse.ArgumentParser()
parser.add_argument("-l", "--list", help="Create CSV of images", action="store_true")
parser.add_argument("-d", "--dimensions", help="Copy images with incorrect dimensions to new directory", action="store_true")
parser.add_argument("-i", "--interactive", help="Run script in interactive mode", action="store_true")
args = parser.parse_args()
if args.list:
func1()
if args.interactive:
func2()
if args.dimensions:
func3()
但是当我不提供参数时,什么都不会被调用。
Namespace(dimensions=False, interactive=False, list=False)
如果没有提供参数,我想要的是一些默认行为
if args.list:
func1()
if args.interactive:
func2()
if args.dimensions:
func3()
if no args supplied:
func1()
func2()
func3()
这看起来应该很容易实现,但我迷失了如何检测所有参数是否为假而不循环遍历参数并测试是否全部为假的逻辑。
多个参数一起有效,这就是我没有走 elif 路线的原因。
这是我更新后的代码,考虑了@unutbu 的回答
它似乎并不理想,因为所有内容都包含在 if 语句中,但在短期内我找不到更好的解决方案。我很高兴接受@unutbu 的回答,如有任何其他改进,我们将不胜感激。
lists = analyseImages()
if lists:
statusTable(lists)
createCsvPartial = partial(createCsv, lists['file_list'])
controlInputParital = partial(controlInput, lists)
resizeImagePartial = partial(resizeImage, lists['resized'])
optimiseImagePartial = partial(optimiseImage, lists['size_issues'])
dimensionIssuesPartial = partial(dimensionIssues, lists['dim_issues'])
parser = argparse.ArgumentParser()
parser.add_argument(
"-l", "--list",
dest='funcs', action="append_const", const=createCsvPartial,
help="Create CSV of images",)
parser.add_argument(
"-c", "--convert",
dest='funcs', action="append_const", const=resizeImagePartial,
help="Convert images from 1500 x 2000px to 900 x 1200px ",)
parser.add_argument(
"-o", "--optimise",
dest='funcs', action="append_const", const=optimiseImagePartial,
help="Optimise filesize for 900 x 1200px images",)
parser.add_argument(
"-d", "--dimensions",
dest='funcs', action="append_const", const=dimensionIssuesPartial,
help="Copy images with incorrect dimensions to new directory",)
parser.add_argument(
"-i", "--interactive",
dest='funcs', action="append_const", const=controlInputParital,
help="Run script in interactive mode",)
args = parser.parse_args()
if not args.funcs:
args.funcs = [createCsvPartial, resizeImagePartial, optimiseImagePartial, dimensionIssuesPartial]
for func in args.funcs:
func()
else:
print 'No jpegs found'
最佳答案
您可以将函数append_const
args.funcs
属性,然后使用一个 if 语句来提供未设置选项时的默认行为:
if not args.funcs:
args.funcs = [func1, func2, func3]
import argparse
def func1(): pass
def func2(): pass
def func3(): pass
parser = argparse.ArgumentParser()
parser.add_argument(
"-l", "--list",
dest='funcs', action="append_const", const=func1,
help="Create CSV of images", )
parser.add_argument(
"-i", "--interactive",
dest='funcs', action="append_const", const=func2,
help="Run script in interactive mode",)
parser.add_argument(
"-d", "--dimensions",
dest='funcs', action='append_const', const=func3,
help="Copy images with incorrect dimensions to new directory")
args = parser.parse_args()
if not args.funcs:
args.funcs = [func1, func2, func3]
for func in args.funcs:
print(func.func_name)
func()
% test.py
func1
func2
func3
% test.py -d
func3
% test.py -d -i
func3
func2
请注意,与您的原始代码不同,这允许用户控制调用函数的顺序:
% test.py -i -d
func2
func3
这可能是理想的,也可能不是。
响应更新 2:
您的代码可以正常工作。然而,这里有另一种组织方式:
不是将主程序嵌套在 if
子句中,您可以使用
if not lists:
sys.exit('No jpegs found')
# put main program here, unnested
sys.exit将 No jpegs found
打印到 stderr
并以退出代码 1 终止。
虽然我最初建议使用 functools.partial
,但现在想到了另一种——也许更简单——的方法:代替
for func in args.funcs:
func()
我们可以说
for func, args in args.funcs:
func(args)
我们需要做的就是在 args.func
中存储一个元组 (func, args)
而不是单独的函数。
例如:
import argparse
import sys
def parse_args(lists):
funcs = {
'createCsv': (createCsv, lists['file_list']),
'resizeImage': (resizeImage, lists['resized']),
'optimiseImage': (optimiseImage, lists['size_issues']),
'dimensionIssues': (dimensionIssues, lists['dim_issues']),
'controlInput': (controlInput, lists)
}
parser = argparse.ArgumentParser()
parser.add_argument(
"-l", "--list",
dest='funcs', action="append_const", const=funcs['createCsv'],
help="Create CSV of images",)
parser.add_argument(
"-c", "--convert",
dest='funcs', action="append_const", const=funcs['resizeImage'],
help="Convert images from 1500 x 2000px to 900 x 1200px ",)
parser.add_argument(
"-o", "--optimise",
dest='funcs', action="append_const", const=funcs['optimiseImage'],
help="Optimise filesize for 900 x 1200px images",)
parser.add_argument(
"-d", "--dimensions",
dest='funcs', action="append_const", const=funcs['dimensionIssues'],
help="Copy images with incorrect dimensions to new directory",)
parser.add_argument(
"-i", "--interactive",
dest='funcs', action="append_const", const=funcs['controlInput'],
help="Run script in interactive mode",)
args = parser.parse_args()
if not args.funcs:
args.funcs = [funcs[task] for task in
('createCsv', 'resizeImage', 'optimiseImage', 'dimensionIssues')]
return args
if __name__ == '__main__':
lists = analyseImages()
if not lists:
sys.exit('No jpegs found')
args = parse_args(lists)
statusTable(lists)
for func, args in args.funcs:
func(args)
关于没有提供参数时python argparse设置行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14358753/
我正在尝试使用 parser = argparse.ArgumentParser对于我写的一个小程序。 程序接受作为输入 EITHER ( txt 文件的路径 ) OR ( opt1 && opt2
我为需要遵循特定格式的参数定义了自定义正则表达式类型。我使用了另一篇文章 ( regex custom type ) 中的代码,它非常有用。我的问题是我正在编写单元测试,我希望正则表达式失败并尝试断言
我写了下面的代码。 import argparse parser = argparse.ArgumentParser() parser.add_argument('-v', '--version',
我一定遗漏了一些明显的东西。目标是使用 argparse,第一个参数是必需的,第二个是可选的,其他任何剩余参数都是可选的。 为了展示这个问题,我制作了两个测试解析器;它们之间的唯一区别是在一个中使用
我正在努力寻找一种将参数传递给 docker container 中的 python 脚本的方法。基于ubuntu 。我正在与docker-compose.yml合作. 请查看下面的示例! docke
我正在努力寻找一种将参数传递给 docker container 中的 python 脚本的方法。基于ubuntu 。我正在与docker-compose.yml合作. 请查看下面的示例! docke
我像这样创建一个 argparser: parser = argparse.ArgumentParser(description='someDesc') parser.add_argument
我正在编写一个脚本,其中包含 2 个相互排斥的参数,以及一个仅对其中一个参数有意义的选项。如果您使用毫无意义的参数调用它,我会尝试将 argparse 设置为失败。 要清楚: -m -f 有意义 -s
我正在使用 Python 3.6 和 argparse 1.1。 除了 -h/--help 我还想有一个选项 -v/--version打印带有版本信息的字符串并退出程序(就像使用帮助字符串一样)。但是
有没有办法将来自父解析器的参数分组到不同的组中?我无权访问父解析器本身,所以我不能在那里添加组。 (我使用的是 Google 的 OAuth2 框架)。 目前我的代码是: # test.py from
GNU grep 有一个参数可以在匹配行周围打印一定数量的额外行。从手册页: -C NUM, -NUM, --context=NUM Print NUM lines of output context
现在,我有一个脚本可以使用 argparse 接受命令行参数。例如,像这样: #foo.py def function_with_args(optional_args=None): parser
我在脚本中的 argparse 解析器中添加了一些参数,如下所示: parser = argparse.ArgumentParser() parser.add_argument("--eval_mod
我在 python 代码中使用 argparse 作为参数解析器。将字典解析为 argparse 对象的最佳方法是什么? 例如,我的字典是: { "activation_dropout": 0
我正在使用 argparse从命令行接收输入以运行我的脚本。 我当前的输入字符串如下所示: path> python -t T1 T2 T3 -f F1 F2 argparse 中是否有一个参数,而
我看到了有关使用 argparse 库将字典和列表传递给 Python 的问题。这些示例都显示了我的 Python 代码的样子。但是没有人告诉我它们在命令行上的样子。我在哪里需要大括号、方括号和引号?
我想模拟大多数命令行实用程序的行为,其中可选参数可以放在命令行中的任何位置,包括位置参数之间,例如 mkdir例子: mkdir before --mode 077 after 在这种情况下,我们知道
我想获取传递给 sys.argv 的所有参数有格式someprogram.py --someparameter 23 -p 42 -anotherparam somevalue . 结果我正在寻找一个
这个问题在这里已经有了答案: Argparse optional positional arguments? (3 个回答) 1年前关闭。 我如何才能设置我的 argparser 以具有以下行为? b
这是我的简单 test.py 脚本: import argparse parser = argparse.ArgumentParser('A long string that goes on and
我是一名优秀的程序员,十分优秀!