Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import custom module in python

I want to import my custom-written functions in any script on any directory, just like I import the requests modules in any script. I am running Ubuntu and Python 3.9

Edit: I fulfilled my requirements by following this tutorial - https://packaging.python.org/tutorials/packaging-projects/

like image 978
Tarek Rahman Avatar asked Oct 28 '25 16:10

Tarek Rahman


2 Answers

You can add the folder to python path, or import sys, add path to this sesion and then import

import sys
sys.path.append(Path_to_module)
import module

or

import sys
sys.path.append(Path_to_module)
from module import function_names
like image 172
Ulises Bussi Avatar answered Oct 31 '25 05:10

Ulises Bussi


You could make a simple package of your custom functions and then just install the package in your system locally using pip. After this you will be able to import the functions from any script.

# for example
pip install .

# or if you need to edit your functions install in editable mode
pip install -e .

Note: the dot '.' above indicates that your setup.py is located in the current working directory. You can also provide the path to the setup.py for your package instead of the dot. Reference on creating package: How to write a Python module/package?


like image 35
aprath Avatar answered Oct 31 '25 06:10

aprath