我是Python新手,大多使用自己的代码.但是现在我下载了一个我需要解决的问题.
结构示例:
root\
externals\
__init__.py
cowfactory\
__init__.py
cow.py
milk.py
kittens.py
Run Code Online (Sandbox Code Playgroud)
现在,cowfactory __init__.py的确如此from cowfactory import cow.这会导致导入错误.
我可以修复它并将import语句更改为from externals.cowfactory import cow但有些东西告诉我有一种更简单的方法,因为它不太实用.
另一个修复可能是将cowfactory包放在我的项目的根目录中,但这也不是很整洁.
我想我必须对__init__.pyexternals目录中的文件做一些事情,但我不确定是什么.
Inside the cowfactory package, relative imports should be used such as from . import cow. The __init__.py file in externals is not necessary. Assuming that your project lies in root\ and cowfactory is the external package you downloaded, you can do it in two different ways:
Install the external module
External Python packages usually come with a file "setup.py" that allows you to install it. On Windows, it would be the command "setup.py bdist_wininst" and you get a EXE installer in the "dist" directory (if it builds correctly). Use that installer and the package will be installed in the Python installation directory. Afterwards, you can simply do an import cowfactory just like you would do import os.
If you have pip or easy_install installed: Many external packages can be installed with them (pip even allows easy uninstallation).
Use PYTHONPATH for development
If you want to keep all dependencies together in your project directory, then keep all external packages in the externals\ folder and add the folder to the PYTHONPATH. If you're using the command line, you can create a batch file containing something like
set PYTHONPATH=%PYTHONPATH%:externals
yourprogram.py
Run Code Online (Sandbox Code Playgroud)
I'm actually doing something similar, but using PyDev+Eclipse. There, you can change the "Run configurations" to include the environment variable PYTHONPATH with the value "externals". After the environment variable is set, you can simply import cowfactory in your own modules. Note how that is better than from external import cowfactory because in the latter case, it wouldn't work anymore once you install your project (or you'd have to install all external dependencies as a package called "external" which is a bad idea).
当然,相同的解决方案也适用于Linux,但具有不同的命令.