使用argparse在我的脚本中运行2个函数中的1个 [英] Use argparse to run 1 of 2 functions in my script

查看:87
本文介绍了使用argparse在我的脚本中运行2个函数中的1个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的.py脚本中目前有2个函数.

I currently have 2 functions in my .py script.

#1连接到数据库并进行一些处理.

#1 connects to the database and does some processing.

#2对文件进行其他处理

#2 does some other processing on files

当前,在运行脚本之前,我必须手动注释/取消注释要在 main if语句块中运行的功能.

Currently before I run the script, I have to manually comment/uncomment the function I want to run in my main if statement block.

如何使用argparse,所以它会问我在运行脚本时要运行哪个函数?

How can I use argparse, so it asks me which function to run when I run my script?

推荐答案

通过action='store_const'和在add_argument()调用中或在set_defaults()调用中使用const=<stuff>对(在使用子解析器时,后者最有用).如果这样做,则可以在解析后返回的parsed_args对象上查找函数,而不必说在全局名称空间中查找该函数.

It is possible to tell ArgumentParser objects about the function or object that has your desired behavior directly, by means of action='store_const' and const=<stuff> pairs in an add_argument() call, or with a set_defaults() call (the latter is most useful when you're using sub-parsers). If you do that, you can look up your function on the parsed_args object you get back from the parsing, instead of say, looking it up in the global namespace.

作为一个小例子:

import argparse

def foo(parsed_args):
    print "woop is {0!r}".format(getattr(parsed_args, 'woop'))

def bar(parsed_args):
    print "moop is {0!r}".format(getattr(parsed_args, 'moop'))

parser = argparse.ArgumentParser()

parser.add_argument('--foo', dest='action', action='store_const', const=foo)
parser.add_argument('--bar', dest='action', action='store_const', const=bar)
parser.add_argument('--woop')
parser.add_argument('--moop')

parsed_args = parser.parse_args()
if parsed_args.action is None:
    parser.parse_args(['-h'])
parsed_args.action(parsed_args)

然后您可以这样称呼它:

And then you can call it like:

% python /tmp/junk.py --foo                                           
woop is None
% python /tmp/junk.py --foo --woop 8 --moop 17                        
woop is '8'
% python /tmp/junk.py --bar --woop 8 --moop 17                        
moop is '17'

这篇关于使用argparse在我的脚本中运行2个函数中的1个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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