调试时模拟 argparse 命令行参数输入 [英] Simulating argparse command line arguments input while debugging

查看:47
本文介绍了调试时模拟 argparse 命令行参数输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此线程是前一个线程的扩展,可以在此处找到.说,我有一个有两个目的的代码,1)从整数列表中打印一个最大数字;2)创建一个新目录.

导入 argparse导入操作系统解析器 = argparse.ArgumentParser()parser.add_argument('整数', metavar='N', type=int, nargs='+',help='累加器的整数')parser.add_argument('--sum', dest='accumulate', action='store_const',常量=总和,默认=总和,help='sum the integers (default: find the max)')parser.add_argument("--output_dir", type=str, default="data/xx")定义主(参数):os.makedirs(args.output_dir)打印 args.accumulate(args.integers)如果 __name__=='__main__':args = parser.parse_args() # 调试时禁用@Run through terminal# args = argparse.Namespace(integers = 1, output_dir='mydata_223ss32') # 通过终端运行时禁用:用于调试过程主要(参数)

这些语句可以通过终端执行

python test_file.py --output_dir data/xxxx 2 2 5 --sum

但是,为了调试过程,我想跳过终端的使用.hpaulj 的想法可以从 这里 只是修改了

如果 __name__=='__main__':

进入

如果 __name__=='__main__':args = argparse.Namespace(output_dir= 'mydata') # 通过终端运行时禁用:用于调试过程主要(参数)

但是,我还想在调试过程中包含一个整数列表.包括整数列表和目录地址如下输出错误

args = argparse.Namespace(integers = "2 2 5", output_dir='mydata')

请问我哪里做错了.

提前致谢

解决方案

通过将代码稍微更改为:

导入 argparse导入系统解析器 = argparse.ArgumentParser()parser.add_argument('整数', metavar='N', type=int, nargs='+',help='累加器的整数')parser.add_argument('--sum', dest='accumulate', action='store_const',常量=总和,默认=总和,help='sum the integers (default: find the max)')parser.add_argument("--output_dir", type=str, default="data/xx")定义主(参数):#os.makedirs(args.output_dir) # XXX:为调试注释掉打印(args.accumulate(args.integers))如果 __name__=='__main__':打印(sys.argv)args = parser.parse_args() # 调试时禁用@Run through terminal# args = argparse.Namespace(integers = 1, output_dir='mydata_223ss32') # 通过终端运行时禁用:用于调试过程打印(参数)主要(参数)

我们可以看到,如果我们调用脚本:./test3.py --output_dir foo 1 2 3

我们的输出是:

<前>['test3.py', '--output_dir', 'foo', '1', '2', '3']命名空间(accumulate=<内置函数 sum>, integers=[1, 2, 3], output_dir='foo')6

所以,如果你想模拟命令行参数,你有两个选择:

1) 编辑 sys.argv(个人首选):

如果 __name__=='__main__':# 覆盖 sys.argvsys.argv = ['test3.py', '--output_dir', 'foo', '1', '2', '3']args = parser.parse_args()主要(参数)

2) 创建一个 Namespace 对象:

如果 __name__=='__main__':#args = parser.parse_args() # 调试时禁用@Run through terminalargs = argparse.Namespace(accumulate=sum, integers=[1,2,3], output_dir='foo')主要(参数)

第二种方法的问题是双重的.首先,您通过执行此操作跳过了调试过程中非常重要的部分,调试了 argparse 配置并确保参数按预期进行解析.其次,必须在此处定义由 argparse 配置添加的隐式默认值(例如,您的 --sum 参数/accumulate).如果您采用第一种方法,argparse 将处理 sys.argv 并添加累加,而无需进行任何更改.在第二种方法中,我们必须添加 accumulate=sum 以使其按预期运行.

This thread is an extension from the previous that can be found here. Say, I have a code that serve two purpose, 1) print a max number from a list of integer; 2) make a new dir.

import argparse
import os

parser = argparse.ArgumentParser()
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')

parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=sum,
                    help='sum the integers (default: find the max)')

parser.add_argument("--output_dir", type=str, default="data/xx")

def main(args):
    os.makedirs(args.output_dir)
    print args.accumulate(args.integers)

if __name__=='__main__':
    args = parser.parse_args()  # Disable during debugging @ Run through terminal
    # args = argparse.Namespace(integers = 1, output_dir= 'mydata_223ss32')  # Disable when run through terminal: For debugging process
    main(args)

These statement can be executed from terminal by

python test_file.py --output_dir data/xxxx 2 2 5 --sum

However, for debugging process, I want to skip the usage of terminal. The idea by hpaulj as can be found from here was simply modify the

if __name__=='__main__': 

into

if __name__=='__main__':
    args = argparse.Namespace(output_dir= 'mydata')  # Disable when run through terminal: For debugging process
    main(args)

However, I also want to include a list of integer during the debugging process. Including both the list of integer and dir address as below output an error

args = argparse.Namespace(integers = "2 2 5", output_dir= 'mydata') 

May I know where did I do wrong.

Thanks in advance

解决方案

By slightly changing your code to:

import argparse
import sys

parser = argparse.ArgumentParser()
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')

parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=sum,
                    help='sum the integers (default: find the max)')

parser.add_argument("--output_dir", type=str, default="data/xx")

def main(args):
    #os.makedirs(args.output_dir)              # XXX: Commented out for debugging
    print(args.accumulate(args.integers))

if __name__=='__main__':
    print(sys.argv)
    args = parser.parse_args()  # Disable during debugging @ Run through terminal
    # args = argparse.Namespace(integers = 1, output_dir= 'mydata_223ss32')  # Disable when run through terminal: For debugging process
    print(args)
    main(args)

We can see that if we call the script with: ./test3.py --output_dir foo 1 2 3

Our output is:

['test3.py', '--output_dir', 'foo', '1', '2', '3']
Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3], output_dir='foo')
6

So, if you want to emulate command line arguments, you have two options:

1) Edit sys.argv (personally preferred):

if __name__=='__main__':
    # Override sys.argv
    sys.argv = ['test3.py', '--output_dir', 'foo', '1', '2', '3']
    args = parser.parse_args()
    main(args)

2) Create a Namespace object:

if __name__=='__main__':    
    #args = parser.parse_args()  # Disable during debugging @ Run through terminal
    args = argparse.Namespace(accumulate=sum, integers=[1,2,3], output_dir='foo')
    main(args)

The problem with the second approach is two-fold. First, you're skipping a very important part of the debugging process by doing this, debugging the argparse configuration and ensuring the arguments are parsed as you expect. Second, implicit defaults added by your argparse configuration must be defined here (e.g. your --sum argument/accumulate). If you took the first approach, argparse would process sys.argv and add accumulate without you having to make any changes. In the second approach, we have to add accumulate=sum for it to run as expected.

这篇关于调试时模拟 argparse 命令行参数输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆