简体   繁体   中英

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. Here is my file directory setup.

proj1
  proj1
    __init__.py
    proj1.py
  setup.py
proj2
  file.py

Where __init__.py is

from .proj1 import Proj1

and setup.py is

#!/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

from proj1 import Proj1

class File(Proj1):
   ...

When I execute file.py, I get the error cannot import name 'Proj1' . I can import it if I have from proj1.proj1 import Proj1 , but that's messy.

How can I import the class directly from the package?

You'd have to add the path of proj1 to your sys.path. check out sys.path.insert. Eg:

sys.path.insert(0, myPath)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM