我想在bash脚本中运行python task.py——调试,现在我需要设置"调试";嵌套函数的参数如下:
main() :
call A_1():
call A_2():
...
call A_10():
if debug :
print("error")
其中A_10
是第10个嵌套函数,我只需要调试参数就可以在A_10
中生效,如图所示。现在,强力方法是将参数debug
从A_1
添加到A_10
。还有其他更优雅的方式来实现我所需要的吗?
参数可用于读取sys.argv
的脚本的任何部分,无论是否嵌套。
示例:
你好.py
import sys
def test():
print(sys.argv)
if "--debug" in sys.argv:
print("We're in debug mode.")
def main():
test()
if __name__ == "__main__":
main()
如果我运行python3 hello.py --debug
,它会返回:
['hello.py', '--debug']
We're in debug mode.
只需将调试定义为main
中的一个变量。这就足够了,它将在嵌套函数的范围内。
def main():
debug = True
def A_1():
def A_2():
def A_10():
if debug:
print("error")
A_10()
A_2()
A_1()
if __name__ == "__main__":
main()
或者
def main():
def A_1():
def A_2():
def A_10():
if debug:
print("error")
A_10()
A_2()
A_1()
if __name__ == "__main__":
debug = True
main()
在后者中,debug
是一个全局变量。
根据您的偏好,我看到了两种可能的方法:
1.创建一个对象来分层管理参数
创建一个对象,例如顶层的Args
类
class Args:
"""store all your arguments here"""
foo = 42
class A_10:
debug = True
# from anywhere in the script at any nested position, call desired function with corresponding args
A_10(debug=Args.A_10.debug)
通过这样做,您可以简单地调用A_10(debug=Args.A10.debug)
。
Pro:
- 不需要全局变量
- 无需将
Args
传递给所有父函数 - 简单
- 类参数的自动补全支持
Con:
- 脚本中变量args的硬编码
2.使用argparse子命令
使用argparse子命令可以一举两得(CLI args,分层组织的参数(,请参阅https://docs.python.org/3/library/argparse.html#sub-命令
Pro:
- 解析CLI参数
- 使用子命令拆分功能
Con:
- 样板代码