English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonction en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Fonction main() en Python

Dans ce tutoriel, nous allons apprendre à utiliser l'attribut __name__ du programme Python pour le faire fonctionner de manière dynamique dans différents contextes.

Qu'est-ce que la fonction main() en Python ?

Certains langages de programmation ont une fonction spéciale appelée main(), qui est le point d'exécution du fichier de programme. Cependant, l'interpréteur Python exécute chaque ligne de fichier en commençant par le haut et sans fonction main() explicite.

Python fournit d'autres conventions pour définir le point d'exécution. L'une d'elles consiste à utiliser la fonction main() du fichier Python et l'attribut __name__.

Qu'est-ce que __name__ en Python ?

La variable __name__ est une variable spéciale intégrée en Python qui affiche le nom du module actuel.

Selon l'emplacement où le fichier Python est exécuté, il a différentes valeurs. Laissons voir un exemple.

Exécuter un fichier Python en tant que script

Supposons que nous ayons un fichierhelloworld.pyLe fichier Python, dont le contenu est le suivant :

print(__name__)

Si nous exécutonshelloworld.pySi cela est le cas, il sera exécuté en tant que script Python. Nous pouvons utiliser la commande suivante pour exécuter un programme Python :

python helloworld.py
def foo():
    str="__main__"
    print(str);
if __name__=="__main__":
    foo()

When we run the program as a script, the value of the variable __name__ is set to__main__. Therefore, the output of the following program will be:

__main__

Running Python files as modules

We can also run Python files as modules. To do this, we must import this file into another Python program. Let's look at an example.

Suppose we have a file namedmain.pyPython file. It has the following content:

import helloworld

When running this file, the following output will be obtained:

helloworld

Here, we can see that importing a module also runs all the code in the module file.

But, we can see, instead of displaying __main__, the program will display the name of the module, that is helloworld.

This is because, when a Python file is run as a module, the name of the module itself is assigned to the __name__ variable.

Using if condition with __name__

Now that we have understood how the __name__ variable is assigned values, we can use the if conditional clause to run the same Python file in different contexts in different ways.

Let's look at an example.

Suppose we willhelloworld.pyThe content of the file is changed to the following:

def main():
    print("Hello World")
if __name__=="__main__":
    main()

Now, when we run it as a script from the command line, the output will be:

Hello World

However, when we import itmain.pyWhen the file runs as a module, no output is displayed because the main() function is not called.

Here, we create a custom main() function in the helloworld.py file. It is only executed when the program runs as a standalone script and not as an imported module.

This is the standard method for explicitly defining the main() function in Python. It is one of the most popular use cases for the Python file __name__ variable.