[英]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. 所以我的问题是:如何从命令行执行python脚本,以便我可以看到print语句。
For example, say I have the file test.py: 例如,假设我有文件test.py:
def hello():
print "hello"
If I enter the interpreter, import test.py, and then call test.hello(), everything works fine. 如果我进入解释器,导入test.py,然后调用test.hello(),一切正常。 However, I want to be able to just run 但是,我希望能够跑
python test.py
from the command line and have it print "hello" to the terminal. 从命令行打印并向终端打印“hello”。
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? 我还需要调用main(),还是自动调用?
Add at the end of the file: 在文件末尾添加:
if __name__ == '__main__':
hello()
Your print
statement is enclosed in a function definition block. 您的print
语句包含在函数定义块中。 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." 基本上这是说“如果这个文件是主文件(已从命令行调用),则运行此代码。”
You have to have the script actually call your method. 您必须让脚本实际调用您的方法。 Generally, you can do this with a if __name__ == "__main__":
block. 通常,您可以使用if __name__ == "__main__":
块来执行此操作。
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. 或者,你可以使用解释器的-c
参数从cli中显式地导入和运行你的模块,但这需要脚本在你的python路径上,并且因为你现在已经执行了Python,所以也会是糟糕的样式Python模块之外的代码。
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: 您的文件应该包含对hello()
函数的调用:
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 这是一种非常“类似脚本”的方法......它可以工作,但必须有更好的方法来实现它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.