[英]How do I import a class directly from a Python package?
I'm trying to make a python package where I can import a class directly into another project and use it. 我正在尝试制作一个python包,可以在其中将一个类直接导入另一个项目并使用它。 Here is my file directory setup.
这是我的文件目录设置。
proj1
proj1
__init__.py
proj1.py
setup.py
proj2
file.py
Where __init__.py
is __init__.py
在哪里
from .proj1 import Proj1
and setup.py
is 和
setup.py
是
#!/usr/bin/env python
from setuptools import find_packages, setup
setup(name='proj1',
version='1.0',
description='',
author='',
author_email='',
url='',
packages=find_packages(),
)
and file.py contains 和file.py包含
from proj1 import Proj1
class File(Proj1):
...
When I execute file.py, I get the error cannot import name 'Proj1'
. 当我执行file.py时,出现错误
cannot import name 'Proj1'
。 I can import it if I have from proj1.proj1 import Proj1
, but that's messy. 如果可以
from proj1.proj1 import Proj1
,我可以将其from proj1.proj1 import Proj1
,但这很麻烦。
How can I import the class directly from the package? 如何直接从包中导入类?
You'd have to add the path of proj1 to your sys.path. 您必须将proj1的路径添加到sys.path中。 check out sys.path.insert.
签出sys.path.insert。 Eg:
例如:
sys.path.insert(0, myPath)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.