5

I know this must be a super basic question, however, I have tried finding a simple answer throughout SO and cannot find one.

So my question is this: How can I execute a python script from the command line such that I can see print statements.

For example, say I have the file test.py:

def hello():
    print "hello"

If I enter the interpreter, import test.py, and then call test.hello(), everything works fine. However, I want to be able to just run

python test.py

from the command line and have it print "hello" to the terminal.

How do I do this?

Thanks!

UPDATED: Yes, sorry, my script is actually more like this:

def main():
    hello()

def hello():
    print "hello"

Do I still need to call main(), or is it automatically invoked?

1

4 Answers 4

9

Add at the end of the file:

if __name__ == '__main__':
    hello()
Sign up to request clarification or add additional context in comments.

1 Comment

The better if you explain __main__, even if looks obvious.
3

Your print statement is enclosed in a function definition block. You would need to call the function in order for it to execute:

def hello():
    print "hello"

if __name__ == '__main__':
    hello()

Basically this is saying "if this file is the main file (has been called from the command line), then run this code."

Comments

2

You have to have the script actually call your method. Generally, you can do this with a if __name__ == "__main__": block.

Alternatively, you could use the -c argument to the interpreter to import and run your module explicitly from the cli, but that would require that the script be on your python path, and also would be bad style as you'd now have executing Python code outside the Python module.

Comments

0

As I understand it, your file just has the following lines:

def hello():
    print "hello"

The definition is correct, but when do you "call" the function?

Your file should include a call to the hello() function:

def hello():
    print "hello"

hello()

This way, the function is defined and called in a single file.

This is a very "script-like" approach... it works, but there must be a better way to do it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.