views:

489

answers:

3

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.

+7  A: 

You can use the -c option:

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

Modify as you need.

carl
+5  A: 
python -c'import themodule; themodule.thefunction("boo!")'
Alex Martelli
+1  A: 

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.

S.Lott
This would only work if you didn't already have a main or already had a main that pointed to the function you need. In my case there is already a main and it points to another function in the module so this wasn't an option.
Daniel
@Daniel: That's not a limitation, that's how your design things. If you've already got a `main` and it does the wrong thing, you've designed it wrong.
S.Lott
@S.Lott: It's not designed wrong. The method by itself does exactly what it needs to do. It is a limitation because its a module not a class which means that it is a grouping of like functions. The main points at the one that is typically called, but in this case I need to start with a non-typical function thus the direct call.
Daniel
@Daniel: Two choices? That's what command-line parsing is all about. If you cannot simply run this from the command line, you did not design it correctly to be run from the command line. You have `optparse`, which will handle this more neatly than what you're trying.
S.Lott
@S.Lott: Good call on optparse. It honestly never crossed my mind to use that. I'm happy with the solution above for now, but optparse will definitely be something to look at in the future.
Daniel