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

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

问题描述

我的 .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

目前在我运行脚本之前,我必须手动注释/取消注释我想在我的 ma​​in 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 的方式直接告诉 ArgumentParser 对象具有您想要的行为的函数或对象='store_const'const= 配对在 add_argument() 调用中,或使用 set_defaults()调用(后者在您使用子解析器时最有用).如果这样做,您可以在解析返回的 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 个函数之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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