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

查看:537
本文介绍了如何从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?

目录结构类似于:


  • Foo

    • Project1

      • file1.py

      • file2.py


      • Project2

        • fileX.py

        • fileY.py

        我想使用file1.py和file2中的函数。 py在fileX.py和fileY.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 ,以便导入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天全站免登陆