使用setup.py导入已安装软件包的错误
我在使用 setup.py
设置python包时遇到问题。首先,我有以下目录设置:
I have a problem with using setup.py
to setup a python package. First, I have the following directory setup:
maindir
|- setup.py
|-mymodule
|- __init__.py
|- mainmodule.py
|-subdir
|- __init__.py
|- submodule.py
ie项目目录包含 setup.py
和一个目录 mymodule
,它本身在两个目录中包含两个python模块。
文件 submodule.py
仅包含
i.e. the project directory contains the setup.py
and a directory mymodule
, which in itself contains two python modules in two directories.
The file submodule.py
contains just
teststring = "hello world"
mainmodule.py
包含:
from .subdir import submodule
mainstring = "42"
和 setup.py
包含:
import os
from setuptools import setup
setup(
name = "mytestmodule",
version = "0.0.1",
description = ("A simple module."),
packages=['mymodule'],
)
当我从mymodule导入mainmodule 中使用
ipython
从 sourceTest
行为按预期工作,我可以参考例如 mainmodule.submodule.teststring
给我字符串 hello world
。
When I do from mymodule import mainmodule
with ipython
from within sourceTest
the behaviour works as expected and I can reference e.g. mainmodule.submodule.teststring
which gives me the string hello world
.
另一方面,当我使用 python setup.py install
安装此软件包时,尝试做相同(从其他目录中),我得到一个导入错误:
On the other side, when I install this 'package' using python setup.py install
and try to do the same (from within some other directory), I get an import error:
In [1]: from mymodule import mainmodule
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
/home/alexander/<ipython-input-1-cf4c9bafa487> in <module>()
----> 1 from mymodule import mainmodule
/home/alexander/build/bdist.linux-i686/egg/mymodule/mainmodule.py in <module>()
ImportError: No module named subdir
我没看到我做错了什么,因为我跟着入门教程和导入内部包的规则。我想我的错误是一个非常小的错误,但我无法发现它并且感谢帮助。
I do not see what I have done wrong, as I followed a Getting started tutorial and rules for importing intra-packages. I suppose my mistake is a really tiny one, but I cannot spot it and help is appreciated.
您必须列出 setup
中的所有包,包括子包:
You have to list all packages in setup
, including subpackages:
setup(
name = "mytestmodule",
version = "0.0.1",
description = ("A simple module."),
packages=['mymodule', 'mymodule.subdir'],
)
或者您可以使用 setuptools
的神奇功能 find_packages
:
Or you can use setuptools
's magic function find_packages
:
from setuptools import setup, find_packages
setup(
name = "mytestmodule",
version = "0.0.1",
description = ("A simple module."),
packages=find_packages(),
)
这是提到的此处:
如果您有子包,则必须在包中明确列出,
但是package_dir中的任何条目都是自动的扩展到子包。
(换句话说, Distutils不会扫描您的源代码树,尝试
来确定哪些目录对应于Python包
寻找__ init __。py
files。)