Python Logging, Packaging and Some Other Advanced Topics
__init__.py and __main__.py in python package
In a package directory, there is always a file named __init__.py. Very often, people leave it as empty, just indicate the folder is a package. Actually we can put code in this file to initialize package level data. The code in this file will be invoked when the package or a module in the package is imported. For example, in a automation package, we define some configuration in the file config.cfg. In the __init__.py file, we use following code to load these configuration.
from os import path
import importlib_resources as _resource
from configparser import ConfigParser
cfg = ConfigParser()
with _resource.path("conf", "config.cfg") as _path:
cfg.read(str(_path))
SCREENSHOT_DEST_FOLDER = cfg.get("SCREENSHOT_DEST_FOLDER", "screen_repository")
Then in any module from this package, we can import this configuration variable and use it directly.
from automation import SCREENSHOT_DEST_FOLDER
Trust you have already known how to run a module from command line. But if you need to run the whole automation package, then we can add a __main__.py file under the package.
def main():
// call the relevant modules with proper parameters
if __name__ == '__main__':
main()
In command line, we just simply run: __python
logging
in progress….