Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

python - Use argparse to run 1 of 2 functions in my script

I currently have 2 functions in my .py script.

#1 connects to the database and does some processing.

#2 does some other processing on files

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

As a little example:

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...