We are new in python and have learned functions all ready. If we do not know the PYthon functions we can get information from http://www.poftut.com/define-use-functions-python-def/ . Now we know a lot about functions. But we see that standard functions name __main__
in most of the python applications. We want to understand this special function usage.
我们是python的新手,已经学习了所有功能。 如果我们不了解PYthon函数,可以从http://www.poftut.com/define-use-functions-python-def/获取信息。 现在,我们对功能有了很多了解。 但是我们看到在大多数python应用程序中,标准函数都命名为__ main__
。 我们想了解这种特殊功能的用法。
As we know applications in python can be run in different ways in different operating systems. In this tutorial I will follow Linux type but this will work for Windows operating too.
众所周知,Python中的应用程序可以在不同的操作系统中以不同的方式运行。 在本教程中,我将遵循Linux类型,但这也适用于Windows操作。
“我应该从哪里开始”问我们的应用程序 (“Where Should I Start” asks Our App)
When we specify to run some python file generally have extension .py
the python interpreter starts by default from running file from first line. This may hurt our application some times. We may want to specify start point specifically in later lines than first line of the script file.
当我们指定运行一些通常带有扩展名.py
的python文件时,python解释器默认情况下从第一行运行文件开始。 这有时会损害我们的应用程序。 我们可能要在脚本文件第一行之后的几行中专门指定起点。
请看主要功能 (Look Main Function Please)
Python programming language provides special function named __main__
. main
function simply specifies the start point of the application. __main__
also collects the user provided parameters and provides to the application. We will create a main
function and call it with __main__
as seen below.
Python编程语言提供了名为__ main__
特殊功能。 main
函数仅指定应用程序的起点。 __ main__
还将收集用户提供的参数并提供给应用程序。 我们将创建一个main
函数,并使用__main__
对其进行调用,如下所示。
import sys
def main(argv=None):
print("I am the MAIN")
if __name__ == "__main__":
main(sys.argv)
为主要功能提供参数,参数 (Provide Arguments , Parameters To The Main Function)
One of the most popular usage case of python application is providing parameters. We generally need to read parameters provided by the user and take action according to these parameters.
python应用程序最流行的用法之一是提供参数。 我们通常需要读取用户提供的参数并根据这些参数采取措施。
import sys
def main(argv=None):
print("I am the MAIN and you chose")
print(argv)
if __name__ == "__main__":
main(sys.argv)
When we execute we will get following result.
当我们执行时,我们将得到以下结果。
$ python3 mymain.py "This is a parameter"
As we can see the name of the application and given text is provided as parameters in a list format. We can easily select parameters with list indexing like below.
如我们所见,应用程序的名称和给定的文本以列表格式作为参数提供。 我们可以通过列表索引轻松选择参数,如下所示。
param1 = sys.argv[1]