如何从 Python 中的其他项目导入函数? [英] How to import functions from other projects in Python?

查看:23
本文介绍了如何从 Python 中的其他项目导入函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个项目中有一些代码,我想在另一个项目中重用.我需要做什么(在两个文件夹中)才能做到这一点?

I have some code in a project which I'd like to reuse in another project. What do I need to do (in both folders) so that I can do this?

目录结构类似于:

    • 项目 1
      • file1.py
      • file2.py
      • 项目 2
        • fileX.py
        • fileY.py

        我想在 fileX.py 和 fileY.py 中使用 file1.py 和 file2.py 中的函数.

        I want to use functions from file1.py and file2.py in fileX.py and fileY.py.

        推荐答案

        理想情况下,这两个项目都是一个可安装的 Python 包,其中包含 __init__.py 和 setup.py.然后可以使用 python setup.py install 或类似工具安装它们.

        Ideally both projects will be an installable python package, replete with __init__.py and setup.py. They could then be installed with python setup.py install or similar.

        如果这是不可能的,不要使用 execfile()!操作 PYTHONPATH 添加 Foo 以便 import Project1.file1 工作.

        If that is not possible, don't use execfile()! Manipulate the PYTHONPATH to add Foo so that import Project1.file1 works.

        例如来自 Project2/fileX.py:

        For example, from Project2/fileX.py:

        from os import path
        import sys
        sys.path.append(path.abspath('../Foo'))
        
        from Project1.file1 import something
        

        然而,真正的答案是让每个都成为一个独立的可安装包.

        However, the real answer is to make each a discrete installable package.

        这篇关于如何从 Python 中的其他项目导入函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆