不要从任意路径导入模块和包。相反,在Python中,您使用包和绝对导入。这将避免所有未来的问题。
示例:
创建以下文件:
MyApp\myapp\__init__.py
MyApp\myapp\utils\__init__.py
MyApp\myapp\utils\charts.py
MyApp\myapp\model\__init__.py
MyApp\myapp\view\__init__.py
MyApp\myapp\controller\__init__.py
MyApp\run.py
MyApp\setup.py
MyApp\README
文件应该是空的,除了以下文件:
MyApp\myapp\utils\charts.py:
class GChartWrapper(object):
def __init__(self):
print "DEBUG: An instance of GChartWrapper is being created!"
MyApp\myapp\view\__init__.py:
from myapp.utils.charts import GChartWrapper
def start():
c = GChartWrapper()
MyApp\run.py:
from myapp.view import start
start()
就这些!当你运行入口点(run.py
)时,它会调用视图上的一个函数,那会创建一个 GChartWrapper 类的实例。使用这个结构,你可以在任何地方导入任何东西并使用它。
为了补充,在 MyApp\setup.py
中,你需要为 MyApp\myapp 包编写安装程序。使用 distutils 来编写:
from distutils.core import setup
setup(name='MyApp',
version='1.0',
description='My Beautiful Application',
author='Martin',
author_email='martin@xxxxxxx.com',
url='https://dev59.com/9XNA5IYBdhLWcg3wVcP6
packages=['myapp'],
scripts=['run.py']
)
就这些内容已经足够了。现在,当用户下载 MyApp 文件夹时,他们只需使用 setup.py 进行安装,然后使用 run.py 运行即可。Distutils 可以生成多种格式的软件包,包括 Windows 安装文件 .EXE。
这是分发 Python 软件包/应用程序的标准方式。