Python Programming
One script
- Create a python script file (
.py
) - Write statements and save
- Run command:
python <path to file>
- Or start the file with
#! /usr/bin/python
then give execute permissionchmod +x <file>
and run the file only.
Project
Project structure
- Create a working directory with structure
myproject/ │ ├── src/ │ └── myprogram/ │ ├── __init__.py │ ├── __main__.py │ ├── config.toml │ ├── module1.py │ └── module2.py │ ├── tests/ │ ├── test_module1.py │ └── test_module2.py │ ├── LICENSE ├── MANIFEST.in ├── README.md └── pyproject.toml
- The
__main__.py
will be the entry point of the program and has code pattern: ```python from myprogram import module1, module2 def main(): """program function description"""
if name == "main": main()
3. The `__init__.py` to represents the root of the package. It will have package constants, configuration handler. Variables defined in `__init__.py` become available as variables in the package namespace. Best practice for this file:
```python
from importlib import resources
try:
import tomllib
except ModuleNotFoundError:
import tomli as tomllib
__version__ = "1.0.0"
_cfg = tomllib.loads(resources.read_text("reader", "config.toml"))
URL = _cfg["feed"]["url"]
- The
module1.py
andmodule2.py
provides functions, object types that is used by__main__.py
. Import the package itself can help the module access the package constants and variables. Example a module file: ```python import myprogram
def function1(): '''describe the feature of function1''' ... def function2(): '''describe the feature of function2''' ... ```
- The
pyproject.toml
contains metadata of the package, it describes:- Which build-system: a tool responsible for creating the actual files that you’ll upload to PyPI.
- Dependencies
- Project information
Using project localy
Build package
- Install two tools build and twine:
python -m pip install build twine
- Build the package: in the project root folder, run
python -m build
- Result: a dist folder created with two package formats created in .tar.gz and .whl in
- Confirm the package build:
unzip
the .tar.gz and inspect contents withtree
.- or run
twine check dist/
Upload to the [[PyPI - Python Package Index]]
- Create an account on pypi.org
- Run command
twine upload -r testpypi dist/*
- Twine will ask you for your username and password.
Reference: realpython.com/pypi-publish-python-package