Run function from the command line


Question

I have this code:

def hello():
    return 'Hi :)'

How would I run this directly from the command line?

1
305
3/6/2019 11:50:25 AM

Accepted Answer

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()'
480
8/31/2016 9:56:09 AM

Just put hello() somewhere below the function and it will execute when you do python your_file.py

For a neater solution you can use this:

if __name__ == '__main__':
    hello()

That way the function will only be executed if you run the file, not when you import the file.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon