Reputation: 31
Hi Everyone so I have read all of the "similar" posts and have not found a clear answer. What is the most simple way to map an argument to a specific function I have defined?
parser = argparse.ArgumentParser(" ")
parser.add_argument("-u", "--url")
parser.add_argument("-i", "--ip")
parser.add_argument("-a", "--action")
args = parser.parse_args()
def func1(ip):
do something
func1(ip)
def func2(url):
do something
func1(url)
def func3(action):
do something
func1(action)
My functions work properly with the arguments, but I do not want say func2 & func3 to run if the -u flag is used, or I only want func3 to run if -a is used. In laymans terms is this possible? The other answers were not clear at all.
Thanks!
Upvotes: 0
Views: 677
Reputation: 145
import argparse
parser = argparse.ArgumentParser(" ")
parser.add_argument("-u", "--url")
args = parser.parse_args()
def func1(some_variable):
print(some_variable)
if args.url:
func1(args.url)
And so on for other args. Hope you get idea.
Upvotes: 1
Reputation: 1653
You can use a the args._get_kwargs()
function to see the values and arguments like this
import argparse
parser = argparse.ArgumentParser(" ")
parser.add_argument("-u", "--url")
parser.add_argument("-i", "--ip")
parser.add_argument("-a", "--action")
args = parser.parse_args()
arg_dict = dict(args._get_kwargs())
def func1(ip):
do something
def func2(url):
do something
def func3(action):
do something
arg_func_dict = {'ip': func1, 'url': func2, 'action': func3}
for arg, value in arg_dict.items():
if value != None:
arg_func_dict[arg](value)
Upvotes: 1