Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing Python Script From Command Line is Hiding Print Statements

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?

like image 537
bradleyrzeller Avatar asked Dec 12 '22 16:12

bradleyrzeller


2 Answers

Add at the end of the file:

if __name__ == '__main__':
    hello()
like image 197
A. Rodas Avatar answered May 09 '23 09:05

A. Rodas


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."

like image 34
MattDMo Avatar answered May 09 '23 09:05

MattDMo