问题
I have created a Python package with the following directory structure:
/
LICENSE
MANIFEST.IN
README.rst
VERSION
docs/
multitool/
__init__.py
core/
__init__.py
classes.py
utils.py
libs/
multitool.py
tests/
tools/
__init__.py
hashtool.py
webtool.py
setup.py
The goal is to create a command line application (multitool.py) that 3rd parties can add to by adding their own files to the tools directory. This is accomplished by having them subclass a class that I've created. For example, these are the first few lines of hashtool.py:
import multitool
class HashTool(multitool.core.classes.CLITool):
All of this works as long as I run it from the project directory itself:
$ ./multitool.py -h <---works
$ ./multitool/multitool.py -h <---works
The problem comes when I try to create and install it as a package. The install runs and installs the script. However, when you run the script, it cannot find any of the modules in the package:
$ multitool.py
import core
ImportError: No module named core
I've tried changing the import to multitool, multitool.core, .multitool, ..multitool, and others with the same result.
However, I am able to do imports from the Python interpreter:
Type "help", "copyright", "credits" or "license" for more information.
>>> import multitool
>>> import multitool.core
>>> import multitool.core.classes
>>> from multitool import core
>>>
Here is the relevant portion of my setup.py
setup(
name = 'multitool',
version = __version__,
license = 'GPLv2',
packages = find_packages(exclude=['test/']),
scripts = ['multitool/multitool.py'],
include_package_data = True,
....
)
What am I doing wrong? How can I import my own code and the files from the tools directory in the script that I install with the package?
Updated MrAlias's edited comment below worked. The confusion was that the script was the same name as the package itself and was not in a separate directory. Moving the script to its own bin/ directory solved the problem.
回答1:
First off, when you install the package you are importing core without identifying it is being apart of the multitool package. So:
import core
should be,
from multitool import core
That way the interpreter knows the module to import core from.
[Edit]
As for the directory structure of the installed package, scripts need to go into a separate directory from the module itself. The way the shown directory structure is Distutils will install the script you named into both a place your system looks for executables as well as in the package itself, which is likely where all the confusion is coming from.
回答2:
import multitool class HashTool(multitool.core.classes.CLITool):
Importing a package does not import its subpackages and submodules. Try this:
import multitool.core.classes
class HashTool(multitool.core.classes.CLITool):
来源:https://stackoverflow.com/questions/24221631/installed-python-script-cannot-import-package-modules