Home > Mobile >  How to import custom module in python
How to import custom module in python

Time:11-19

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/

CodePudding user response:

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?


CodePudding user response:

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

CodePudding user response:

Given your_function inside your_script.py in the same directory of your current code, you can write on your code:

 from your_script import your_function
  • Related