在python中调试argpars [英] debugging argpars in python
问题描述
我可以知道调试 argpars 函数的最佳做法是什么吗.
May I know what is the best practice to debug an argpars function.
假设我有一个包含以下几行的 py 文件 test_file.py
Say I have a py file test_file.py with the following lines
# Script start
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument("–output_dir", type=str, default="/data/xx")
args = parser.parse_args()
os.makedirs(args.output_dir)
# Script stop
上面的脚本可以通过以下方式从终端执行:
The above script can be executed from terminal by:
python test_file.py –output_dir data/xx
但是,对于调试过程,我想避免使用终端.因此解决方法是
However, for debugging process, I would like to avoid using terminal. Thus the workaround would be
# other line were commented for debugging process
# Thus, active line are
# Script start
import os
args = {"output_dir":"data/xx"}
os.makedirs(args.output_dir)
#Script stop
但是,我无法执行修改后的脚本.我可以知道我错过了什么吗?
However, I am unable to execute the modified script. May I know what have I miss?
推荐答案
当用作脚本时,parse_args
会产生一个 Namespace
对象,显示为:>
When used as a script, parse_args
will produce a Namespace
object, which displays as:
argparse.Namespace(output_dir='data/xx')
然后
args.output_dir
将是该属性的值
在测试中,您可以做几件事:
In the test you could do one several things:
args = parser.parse_args([....]) # a 'fake' sys.argv[1:] list
args = argparse.Namespace(output_dir= 'mydata')
并像以前一样使用 args
.或者干脆调用
and use args
as before. Or simply call the
os.makedirs('data/xx')
我建议将脚本组织为:
# Script start
import argparse
import os
# this parser definition could be in a function
parser = argparse.ArgumentParser()
parser.add_argument("–output_dir", type=str, default="/data/xx")
def main(args):
os.makedirs(args.output_dir)
if __name__=='__main__':
args = parser.parse_args()
main(args)
这样在导入文件时 parse_args
步骤就不会运行.无论您是将 args
Namespace
传递给 main
还是传递诸如 args.output_dir
或字典等值.是你的选择.
That way the parse_args
step isn't run when the file is imported. Whether you pass the args
Namespace
to main
or pass values like args.output_dir
, or a dictionary, etc. is your choice.
这篇关于在python中调试argpars的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!