进口自制包装

2024-06-02 08:25:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在测试我自己的软件包,但我很难导入它。我的包文件结构如下:

File Structure

(您也可以查看我的Github存储库here

在PyAdventures中是myinit.py,内容为

name="pyadventures"

所以我的问题是,当我在另一个python文件中导入它时,它为什么不工作?你知道吗

我跑:

import pyadventures

但我得到以下错误:

No module named pyadventures

如果你能回答我的问题就太好了!你知道吗

It's important to note that the package is in my Python package directory, not the test one I showed

新发现!在我的PyAdventures文件夹(Python实际使用的文件夹)中,该文件夹只有几个文件,而不是上面屏幕截图中的文件。你知道吗

New Discovery

您可以用pip install pyadventures安装它


Tags: 文件thenamepyimportgithub文件夹package
2条回答

很简单。即使pip上列出的包是namdpyadventures,但在代码中,目录名为PyAdventures。这就是python所知道的。我运行了import PyAdventures,效果很好。你知道吗

啊,就像其他人在评论和回答中所说的:骆驼案可能就是问题所在。(为什么不用小写字母命名:pyadventures?-否则用户会像现在的开发者一样困惑:D。)

以前,我想,如果您想在没有(本地)安装模块的情况下使用它,可能会有问题。我的以下回答适用于这种情况(使用本地文件夹中未安装的软件包):

在文档中,您可以阅读:

The variable sys.path is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:

import sys sys.path.append('/ufs/guido/lib/python')

因此,在导入之前:

import sys
sys.path.append('/absolute/or/relative/path/to/your/module/pyadventures')
# Now, your module is "visible" for the module loader
import pyadventures

或者,您可以将pyadventures模块文件夹本地放置在您的工作目录中,在那里启动python,然后执行以下操作

import pyadventures

但是,只在一个地方保存一个版本并从其他地方/脚本引用它要容易得多。(否则您有多个副本,并且难以跟踪多个副本上的更改)。你知道吗

据我所知,您的__init__.py不需要包含任何内容。如果它是空的,它就工作。它只是将您的目录标记为一个模块。你知道吗

相关问题 更多 >