views:

70

answers:

4

Say in my file i have:

def hello():
    return 'Hi :)'

How would I run this from the command line?

+2  A: 

python -c 'from myfile import hello; hello()' where myfile must be replaced with the basename of your Python script. (E.g., myfile.py becomes myfile).

However, if hello() is your "permanent" main entry point in your Python script, then the usual way to do this is as follows:

def hello():
    print "Hi :)"

if __name__ == "__main__":
    hello()

This allows you to execute the script simply by running python myfile.py or python -m myfile.

Some explanation here: __name__ is a special Python variable that holds the name of the module currently being executed, except when the module is started from the command line, in which case it becomes "__main__".

Tamás
+4  A: 

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.

WoLpH
+4  A: 

With the -c (command) argument (assuming your file is namedfoo.py):

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

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

$ python -c 'from foo import *; print hello()'
Frédéric Hamidi
A: 

This function cannot be run from the command line as it returns a value which will go unhanded. You can remove the return and use print instead

Shubham