3

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

4 Answers 4

6

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()
Sign up to request clarification or add additional context in comments.

3 Comments

Wouldn't a dict of functions be even better?
It works perfectly when the command line does not requires additional input arguments. But when running function has something like def func1(): input_data = input("please input 1 or 2") if input_data == "1": print("1") if input_data == "2": print("2") then it gives a SyntaxError: unexpected EOF while parsing. How can I handle this?
@jin890 that's another problem, use raw_input() instead of input() . Please conisder to upvote the answer and mark it as accepted.
3

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 :)

Comments

1

@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?

Comments

1

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]()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.