python - 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.
解决方案
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.
推荐阅读
- node.js - @azure/cosmos.js - 同步获取数据库
- javascript - 为什么传奇效应没有被调用?
- fortran - 如何创建具有给定度数分布的网络(图)?
- routes - 如何知道我的骆驼路线是否已启动并正在运行以处理来自队列的消息
- c# - 无法调用/加载 .NET Core 程序集,但 .NET Standard 在 PowerShell 中使用 Add-Type 可以正常工作
- perl - 循环遍历当前的哈希数组;构建一个新的哈希数组并忽略具有特定键 = 值的记录
- python - 如何在作为类对象的画布之间切换?
- php - 如何在 CakePHP 中创建一个使用 rest API 从数据库中检索数据的方法?
- excel - 循环浏览用户表单标签?
- jquery - $.post 到 Zapier webhook