Executing Python Script From Command Line is Hiding Print Statements

14,115

Solution 1

Add at the end of the file:

if __name__ == '__main__':
    hello()

Solution 2

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

Solution 3

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.

Share:
14,115
bradleyrzeller
Author by

bradleyrzeller

Updated on July 06, 2022

Comments

  • bradleyrzeller
    bradleyrzeller almost 2 years

    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?