Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python calling custom function from bash shell

Tags:

python

bash

shell

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

like image 767
jin890 Avatar asked Feb 09 '26 17:02

jin890


2 Answers

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()
like image 116
Assem Avatar answered Feb 12 '26 06:02

Assem


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

like image 24
Radek Avatar answered Feb 12 '26 05:02

Radek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!