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
2010-01-22 19:03:05
+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
2010-01-22 20:40:37
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
2010-01-22 21:32:23
@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
2010-01-24 13:42:39
@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
2010-01-25 16:40:21
@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
2010-01-25 17:17:32
@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
2010-02-01 22:24:47