Run function from the command line

Steven picture Steven · Oct 21, 2010 · Viewed 593.9k times · Source

I have this code:

def hello():
    return 'Hi :)'

How would I run this directly from the command line?

Answer

Frédéric Hamidi picture Frédéric Hamidi · Oct 21, 2010

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()'