Daniel
Daniel

Reputation: 657

Calling a python function from bash script

I have an "alarm email" function inside a python module. I want to be able to call this function from a bash script. I know you can call a module using 'python ' in the script, but I'm not if you can or how you would call a specific function within the module.

Upvotes: 37

Views: 61299

Answers (4)

Tengerye
Tengerye

Reputation: 1964

To supplements others' answers with two notes:

  1. If you need to feed environment variables as parameters, use double quotes;
  2. The parameters are not necessarily str.

Here is an example:

# test.py
def call(param):
    print(f'{param} with type={type(param)}')

print('hi')

Execute from shell:

PARAM=10
python3 -c "import test; test.call(${PARAM})"

You can read:

hi
10 with type=<class 'int'>

Upvotes: 2

S.Lott
S.Lott

Reputation: 391854

To call a specific function in a module, assure that the module has the following:

if __name__ == "__main__":
    the_function_to_call( )

Then you can simply do this in your shell script.

python module.py

Or

python -m module

Depending on whether or not the module's on the PYTHONPATH.

Upvotes: 4

Alex Martelli
Alex Martelli

Reputation: 881635

python -c'import themodule; themodule.thefunction("boo!")'

Upvotes: 74

carl
carl

Reputation: 50554

You can use the -c option:

python -c "import random; print random.uniform(0, 1)"

Modify as you need.

Upvotes: 24

Related Questions