Running python modules

satya - 3/15/2024, 10:56:19 AM

Consider this first


project/
¦
+-- mypackage/
¦   +-- __init__.py
¦   +-- mymodule.py
¦
+-- myscript.py

satya - 3/15/2024, 11:00:07 AM

Observations

  1. myscrip.py is called a script
  2. mymodule.py is also a script (and also sometimes referred to as a module)

satya - 3/15/2024, 11:59:08 AM

Few ways of running these


# Running a script with full path
python /somepath/project/myscript.py

# Running a script as a module.
# Notice no .py in the end nor the path
python -m mypackage.module

# Using only the package
# In this case there has to be a file called __main__.py
python -m mypackage

satya - 3/15/2024, 12:01:09 PM

In all cases the __name__ value in the script that it runs


# the __name__ is set to __main__ in that script or module

# So the following code segment is useful

if __name__ == '__main__':
    localTest()

satya - 3/15/2024, 12:01:49 PM

The -m module option

  1. Searches the module path to locate the module
  2. So full path is not necessary