Executing Python Script From Command Line is Hiding Print Statements

六月ゝ 毕业季﹏ 提交于 2019-12-23 16:46:55

问题


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:


Add at the end of the file:

if __name__ == '__main__':
    hello()



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




回答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.




回答4:


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



来源:https://stackoverflow.com/questions/15556967/executing-python-script-from-command-line-is-hiding-print-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!