Python main() 函数似乎不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17257631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:53:59  来源:igfitidea点击:

The main() function appears to not work

pythonmain

提问by

I am new to Python, and I am using Python 3.3.2. I ran the following code :

我是 Python 新手,我使用的是 Python 3.3.2。我运行了以下代码:

import sys
def random(size=16):
    return open(r"C:\Users\ravishankarv\Documents\Python\key.txt").read(size)
def main():
    key = random(13)
    print(key)

and expected it to print the content in the key file. The program runs without errors on IDLE but nothing happens. The key is not printed.

并期望它打印密钥文件中的内容。程序在 IDLE 上运行没有错误,但没有任何反应。不打印密钥。

Can someone help?

有人可以帮忙吗?

回答by TerryA

Python isn't like other languages where it automatically calls the main()function. All you have done is defined your function.

Python 与其他语言不同,它会自动调用main()函数。您所做的就是定义了您的功能。

You have to manually call your main function:

您必须手动调用主函数:

main()

Also, you may commonly see this in some code:

此外,您通常会在某些代码中看到这一点:

if __name__ == '__main__':
    main()

回答by BrenBarn

You're not calling the function. Put main()at the bottom of your code.

你不是在调用函数。放在main()代码的底部。

回答by BrenBarn

You've not called your main function at all, so the Python interpreter won't call it for you.

您根本没有调用 main 函数,因此 Python 解释器不会为您调用它。

Add this as the last line to just have it called at all times:

将此添加为最后一行以始终调用它:

main()

If you use the commonly seen:

如果您使用常见的:

if __name__ == "__main__":
    main()

It will make sure your main method is called only if that module is executed as the starting code by the Python interpreted, more about that is discussed here: What does if __name__ == "__main__": do?

它将确保您的 main 方法仅在该模块作为 Python 解释的起始代码执行时才被调用,更多相关信息在此处讨论:如果 __name__ == "__main__": do?

If you want to know how to write the best possible 'main' function, Guido van Rossum (the creator of Python) wrote about it here.

如果您想知道如何编写尽可能最好的“main”函数,Guido van Rossum(Python 的创造者)在这里写了相关文章。

回答by ankush981

You are defining a function but never calling it. Hence you get no error but nothing happens. Add this add the end and it will work:

您正在定义一个函数,但从未调用过它。因此,您没有收到任何错误,但没有任何反应。添加此添加末尾,它将起作用:

if __name__ == "__main__":
    main()

回答by alfonso.kim

There's no such mainmethod in python, what you have to do is:

mainpython中没有这样的方法,你要做的是:

if __name__ == '__main__':
    main()