Adding to the list for rake and PHP: Is there a way to test whether a Python function or method has been invoked directly from a Python shell, as opposed to being invoked from within a .py script file?
For example I want to define an expression, test_expr that behaves as follows when the expression appears in a module “shelltest.py”,
#!/usr/bin/python
"""Module shelltest.py"""
def test_expr():
#...
Case (1): it yields True when invoked directly from a shell
>>> import shelltest
>>> shelltest.test_expr()
True
Case (2): it yields False when imported into another module, “other.py” and used in code there
#!/usr/bin/python
"""Module other.py"""
import shelltest
def other_func():
# ...
shelltest.test_expr()
which is in turn invoked from a shell
>>> import other
>>> other.other_func()
False
If you are at the shell, then
__name__ == '__main__'. (In addition, as Ned Batchelder notes, this will only tell you where the function was defined.)You probably don’t want to test this inside a function – it’s used instead to distinguish whether a module is being called as a main programme or not. Your functions should probably work the same way regardless, and if you need different functions, you should import a different module containing the same function names.
Do something like this:
As to determining whether you’re in a web environment – do that in code that will only be called from the web. Python scripts are typically not invoked by CGI, so this doesn’t really arise as a use case.