Python import script on another folder in same level

后端 未结 2 1071
鱼传尺愫
鱼传尺愫 2021-01-27 17:32

Lets say this is my project structure :

codes

 - pre.py

training

 - model.py

Both folder have empty __init__.py inside them, an

相关标签:
2条回答
  • 2021-01-27 18:23

    You can create a setup.py file at the outermost level. So your directory tree may look like this

    |_project_name
      |_codes
        |_pre.py
        |___init__.py
      |_training
        |_models.py
        |___init__.py
      |___init__.py
    |_setup.py
    

    Then in the setup.py do something like this

    from distutils.core import setup
    from setuptools import find_packages
    
    requires = [
        'six>=1.10.0',
    ]
    
    if __name__ == "__main__":
        setup(
            name="project-name",
            version="0.0.1",
            packages=find_packages(),
            author='Your Name',
            author_email='email@email.com',
            install_requires=requires,
            description='The API to fetch data from different sources',
            include_package_data=True,
        )
    

    And finally from the outermost directory use python setup.py install it will install your package and then you will be able to easily do from project_name.pre import * in models

    Also consider using a virtualenv for this kind of things.

    Hope this helps.

    0 讨论(0)
  • 2021-01-27 18:28

    try using full path of your code folder

    import sys
    sys.path.insert(0, "fullpath")
    from pre import *
    
    0 讨论(0)
提交回复
热议问题