首页 > 解决方案 > Is there a way to make my script a library so I don't have to import from a specific path?

问题描述

I have Python scripts that contain many functions that are used by many other scripts and codes in my program. They do it with import.

Today, I was trying to do an import from a different directory, and tried at first this

from .etc.mycodes.helper_functions import graph

So I tried something like

import sys
sys.path.insert(1, '/etc/mycodes/helper_functions')
import graph

and it did not work either.

I was wondering if there is a better way to do and if it was possible to make my helper_functions some sort of library, so I do not have to specify the path to it, kind of make it a environment variable.

标签: pythonpython-3.x

解决方案


You can turn your helper_functions into a Python package that you can install with pip install. See the documentation on Packaging Python Projects. It's generally used for distributing Python projects over PyPi for sharing with other developers, but it can also be used for personal or project-specific libraries.

Setup your my_helper_functions to be a Python package:

Creating the package files

You will now create a handful of files to package up this project and prepare it for distribution. Create the new files listed below - you will add content to them in the following steps.

packaging_tutorial/  
  example_pkg/  
    __init__.py  
  tests/  
  setup.py
  LICENSE
  README.md

Then you can just

$ cd my_helper_functions
$ pip install .

to install it into your Python environment. The . here means "install the contents of this folder".

Then in your codes

from my_helper_functions import my_awesome_util

which doesn't need setting any paths.


推荐阅读