Reputation: 33
How can I call the custom-defined function in a python script from a bash shell?
I tried to use sys.argv[1], but not working properly.
for example,
import sys
if __name__=='__main__':
try:
func = sys.argv[1]
except: func = None
def function1():
~~~~~~~~
return a
def function2():
~~~~~~~~
return b
here, I want to call the function 1 or function 2 by typing like
$ script.py function1
$ script.py function2
Upvotes: 3
Views: 487
Reputation: 1630
I suggest to use argparse module: https://docs.python.org/3/library/argparse.html#module-argparse
You will thank yourself later.
For your case - since you need to call only 1 function at the time - you can use positional arguments:
import argparse
def function1():
print("1")
def function2():
print("2")
parser = argparse.ArgumentParser()
F_MAP = {'function1': function1,
'function2': function2}
parser.add_argument('function', choices=F_MAP.keys())
args = parser.parse_args()
F_MAP[args.function]()
As a bonus you get a nice help page when calling with -h argument :)
Upvotes: 3
Reputation: 3741
You can refer Display a list of user defined functions in the Python IDLE session
import types
list_function = [f for f in globals().values() if type(f) == types.FunctionType]
This will return list of available functions, Then you can check if any of these contain sys.argv[1], If yes then you can call your function as
list_function[index]()
Upvotes: 1
Reputation: 4755
@bigOTHER's answer is good and correct, but if you're looking to build a relatively complex text UI, maybe have a look at something like Click?
Upvotes: 1
Reputation: 12087
You are getting the name of function , but you are not running it. You should check first if the func name is one of your functions than execute it:
if __name__=='__main__':
try:
func = sys.argv[1]
except:
func = None
functions = {
"function1": function1,
"function2": function2
}
if func in functions:
functions[func]()
A simpler solution:
if func == "function1":
function1()
elif func == "function2":
function2()
Upvotes: 6