Skip to content Skip to sidebar Skip to footer

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 scr

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.

Solution 4:

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

defhello():
    print"hello"

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

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

defhello():
    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

Post a Comment for "Executing Python Script From Command Line Is Hiding Print Statements"