SoFunction
Updated on 2024-11-17

python custom module using .pth file to implement reuse approach

python custom module reuse using .pth files

The best way to reuse custom modules is to package them and publish them to pypi and then use pip to install them, but some modules that are used internally in the project and are not convenient to make public can be automatically introduced using .

A functional reference on python's .pth files:

Python. _pth file

concrete operation

1. Create a new .pth file in the Lib/site-packages directory of python.

2. Edit the .pth file, add the directory of the module to be reused, and edit multiple directories with multiple lines.

Then the modules in the D:\py\base directory can be imported and used directly

Here's the script I wrote to automatically add modules to .pth in_lab.py

import os
import shutil
 
python_path = ("python")
python_path = (python_path)
if python_path.startswith("/"):
    python_path = python_path[1] + ":" + python_path[2:]
print(python_path)
lib_path = (python_path, "lib")
if not (lib_path):
    lib_path = ((python_path), "lib")
 
pth_file = (lib_path, "site-packages", ".pth")
print(pth_file)
pwd = ((__file__))
if not (pth_file):
    with open(pth_file, "w") as f:
        (pwd + "\n")
else:
    with open(pth_file, "r") as f:
        content = ()
    if pwd not in content:
        with open(pth_file, "a") as f:
            (pwd + "\n")

Generate in_lab.py in the module to be added

Then run it in the currently used python environment

python d:/py/base/in_lab.py

This will automatically add d:/py/base to .pth

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.