Search code examples
pythonfunctioncommand-line

Run function from the command line


I have this code:

def hello():
    return 'Hi :)'

How would I run this directly from the command line?


See also: What does if __name__ == "__main__": do? to explain the standard idiom for getting the code started;
Why doesn't the main() function run when I start a Python script? Where does the script start running (what is its entry point)? for why things like this are necessary


Solution

  • With the -c (command) argument (assuming your file is named foo.py):

    $ python -c 'import foo; print foo.hello()'
    

    Alternatively, if you don't care about namespace pollution:

    $ python -c 'from foo import *; print hello()'
    

    And the middle ground:

    $ python -c 'from foo import hello; print hello()'