From d2ec3ec7c55535673410305c3f0d3526525e21e5 Mon Sep 17 00:00:00 2001 From: David Rotermund <54365609+davrot@users.noreply.github.com> Date: Thu, 14 Dec 2023 01:00:16 +0100 Subject: [PATCH] Update README.md Signed-off-by: David Rotermund <54365609+davrot@users.noreply.github.com> --- python_basics/modules/README.md | 35 ++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/python_basics/modules/README.md b/python_basics/modules/README.md index 4605c46..6bbd09b 100644 --- a/python_basics/modules/README.md +++ b/python_basics/modules/README.md @@ -148,7 +148,7 @@ module ::= (identifier ".")* identifier relative_module ::= "."* module | "."+ ``` -Python code in one [module](https://docs.python.org/3/glossary.html#term-module) gains access to the code in another module by the process of [importing](https://docs.python.org/3/glossary.html#term-importing) it. +> Python code in one [module](https://docs.python.org/3/glossary.html#term-module) gains access to the code in another module by the process of [importing](https://docs.python.org/3/glossary.html#term-importing) it. see [The import system](https://docs.python.org/3/reference/import.html) for more details. @@ -166,5 +166,38 @@ If a file **myfunctions.py** with **thefunction** is places in a subdirectory ** from sub1.sub2.myfunctions import thefunction ``` +## [Executing modules as scripts​](https://docs.python.org/3/tutorial/modules.html#more-on-modules) +When you run a Python module with​ + +```shell +python fibo.py +``` + +> the code in the module will be executed, just as if you imported it, but with the \_\_name\_\_ set to "\_\_main\_\_". That means that by adding this code at the end of your module: + +```python +if __name__ == "__main__": + import sys + fib(int(sys.argv[1])) +``` + +> you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file:​ + +```shell +python fibo.py 50​ +``` + +Output: +```shell +1 1 2 3 5 8 13 21 34 +``` + +> If the module is just imported, + +```python +import fibo +``` + +> the code is not run.​