如何导入上面目录中的Python类?

发布于 2024-07-25 20:02:52 字数 52 浏览 1 评论 0 原文

我想继承位于当前目录上方目录中的文件中的类。

是否可以相对导入该文件?

I want to inherit from a class in a file that lies in a directory above the current one.

Is it possible to relatively import that file?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

无畏 2024-08-01 20:02:52

from ..subpkg2 import mod

根据 Python 文档:在包层次结构内部时,使用两个点,作为 导入声明 文档说:

指定要导入的模块时,不必指定模块的绝对名称。 当模块或包包含在另一个包中时,可以在同一顶级包中进行相对导入,而不必提及包名称。 通过在 from 之后的指定模块或包中使用前导点,您可以指定在当前包层次结构中向上遍历的高度,而无需指定确切的名称。 前导点表示进行导入的模块所在的当前包。 两个点表示升级一级。 三个点代表上两级,依此类推。因此,如果您执行 from 。 从 pkg 包中的模块导入 mod 然后您最终将导入 pkg.mod。 如果您从 pkg.subpkg1 中执行 from ..subpkg2 import mod,您将导入 pkg.subpkg2.mod。 相对导入的规范包含在 PEP 328 中。

PEP 328 处理绝对/相对导入。

from ..subpkg2 import mod

Per the Python docs: When inside a package hierarchy, use two dots, as the import statement doc says:

When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod. If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod. The specification for relative imports is contained within PEP 328.

PEP 328 deals with absolute/relative imports.

以为你会在 2024-08-01 20:02:52
import sys
sys.path.append("..") # Adds higher directory to python modules path.
import sys
sys.path.append("..") # Adds higher directory to python modules path.
活雷疯 2024-08-01 20:02:52

@gimel 的答案是正确的如果你可以保证他提到的包层次结构。 如果你不能——如果你的真正需求正如你所表达的那样,完全依赖于目录并且与打包没有任何必要的关系——那么你需要使用 __file__ 来找出父目录(几个 os.path.dirname 调用即可;-),然后(如果该目录尚未位于 sys.path 上)在前面临时插入所述目录从sys.path开始,__import__,再次删除所述目录——确实是混乱的工作,但是,“当你必须的时候,你必须”(并且 Pyhon 努力永不停止程序员不做必须的事情——就像ISO C标准在其前言的“C的精神”部分中所说的那样!-)。

这是一个可能适合您的示例:

import sys
import os.path
sys.path.append(
    os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))

import module_in_parent_dir

@gimel's answer is correct if you can guarantee the package hierarchy he mentions. If you can't -- if your real need is as you expressed it, exclusively tied to directories and without any necessary relationship to packaging -- then you need to work on __file__ to find out the parent directory (a couple of os.path.dirname calls will do;-), then (if that directory is not already on sys.path) prepend temporarily insert said dir at the very start of sys.path, __import__, remove said dir again -- messy work indeed, but, "when you must, you must" (and Pyhon strives to never stop the programmer from doing what must be done -- just like the ISO C standard says in the "Spirit of C" section in its preface!-).

Here is an example that may work for you:

import sys
import os.path
sys.path.append(
    os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))

import module_in_parent_dir
长梦不多时 2024-08-01 20:02:52

从当前目录的上一级目录导入模块:

from .. import module

Import module from a directory which is exactly one level above the current directory:

from .. import module
撩心不撩汉 2024-08-01 20:02:52

如何加载作为目录的模块

前言:我对之前的答案进行了实质性重写,希望帮助人们轻松进入Python的生态系统,并希望通过Python的导入系统为每个人带来成功的最佳改变。

这将涵盖包内的相对导入,我认为这是OP问题最有可能的情况。

Python 是一个模块化系统,

这就是为什么我们编写 import foo 来从根命名空间加载模块“foo”,而不是编写:

foo = dict();  # please avoid doing this
with open(os.path.join(os.path.dirname(__file__), '../foo.py') as foo_fh:  # please avoid doing this
    exec(compile(foo_fh.read(), 'foo.py', 'exec'), foo)  # please avoid doing this

Python 没有耦合到文件系统

这就是为什么我们可以将 python 嵌入到没有实际文件系统的环境中,而不提供虚拟文件系统,例如 Jython。

与文件系统分离使导入变得灵活,这种设计允许从存档/zip 文件导入、导入单例、字节码缓存、cffi 扩展,甚至远程代码定义加载等。

那么,如果导入没有耦合到文件系统,“上一个目录”是什么意思? 我们必须选择一些启发式方法,但我们可以这样做,例如在 中工作时包,已经定义了一些启发式方法,使 相对像 .foo..foo 这样的导入在同一个包中工作。 凉爽的!

如果您真诚地希望将源代码加载模式耦合到文件系统,您可以这样做。 您必须选择自己的启发式方法,并使用某种导入机制,我推荐 importlib

Python 的 importlib 示例看起来像这样:

import importlib.util
import sys

# For illustrative purposes.
file_path = os.path.join(os.path.dirname(__file__), '../foo.py')
module_name = 'foo'

foo_spec = importlib.util.spec_from_file_location(module_name, file_path)
# foo_spec is a ModuleSpec specifying a SourceFileLoader
foo_module = importlib.util.module_from_spec(foo_spec)
sys.modules[module_name] = foo_module
foo_spec.loader.exec_module(foo_module)

foo = sys.modules[module_name]
# foo is the sys.modules['foo'] singleton

打包

这里有一个官方提供的很棒的示例项目: https:// github.com/pypa/sampleproject

python 包是有关您的源代码的信息的集合,它可以通知其他工具如何将您的源代码复制到其他计算机,以及如何将您的源代码集成到该系统的路径中这样 import foo 适用于其他计算机(无论解释器、主机操作系统等)

目录结构

让包名称 foo 位于某个目录(最好是空目录) )。

some_directory/
    foo.py  # `if __name__ == "__main__":`  lives here

我的偏好是创建 setup.py作为 foo.py 的兄弟,因为它使编写 setup.py 文件更简单,但是如果您愿意,您可以编写配置来更改/重定向 setuptools 默认执行的所有操作; 例如,将 foo.py 放在“src/”目录下有点流行,这里不介绍。

some_directory/
    foo.py
    setup.py

#!/usr/bin/env python3
# setup.py

import setuptools

setuptools.setup(
    name="foo",
    ...
    py_modules=['foo'],
)

python3 -m pip install --editable ./  # or path/to/some_directory/

“editable”又名 -e 将再次重定向导入机器以加载此目录中的源文件,而不是将当前的确切文件复制到安装环境的库。 这也可能会导致开发人员计算机上的行为差异,请务必测试您的代码!
除了 pip 之外还有其他工具,但我建议 pip 作为入门工具:)

我也喜欢将 foo 制作为一个“包”(包含 __init__.py 的目录) )而不是模块(单个“.py”文件),“包”和“模块”都可以加载到根命名空间中,模块允许嵌套命名空间,如果我们想要一个“相对一个目录”,这会很有帮助上”导入。

some_directory/
    foo/
        __init__.py
    setup.py

#!/usr/bin/env python3
# setup.py

import setuptools

setuptools.setup(
    name="foo",
    ...
    packages=['foo'],
)

我还喜欢制作一个 foo/__main__.py,这允许 python 将包作为模块执行,例如 python3 -m foo 将执行 foo/__main__ .py__main__

some_directory/
    foo/
        __init__.py
        __main__.py  # `if __name__ == "__main__":`  lives here, `def main():` too!
    setup.py

#!/usr/bin/env python3
# setup.py

import setuptools

setuptools.setup(
    name="foo",
    ...
    packages=['foo'],
    ...
    entry_points={
        'console_scripts': [
            # "foo" will be added to the installing-environment's text mode shell, eg `bash -c foo`
            'foo=foo.__main__:main',
        ]
    },
)

让我们用更多的模块来充实它:
基本上,您可以拥有如下目录结构:

some_directory/
    bar.py           # `import bar`
    foo/
        __init__.py  # `import foo`
        __main__.py
        baz.py       # `import foo.baz
        spam/           
            __init__.py  # `import foo.spam`
            eggs.py      # `import foo.spam.eggs`
    setup.py

setup.py 通常保存有关源代码的元数据信息,例如:

  • 安装名为“install_requires”的依赖项需要
  • 使用什么名称包管理(安装/卸载“name”),我建议在我们的例子中与您的主要 python 包名称相匹配 foo,尽管用下划线代替连字符是流行的
  • 许可信息
  • 成熟度标签(alpha/beta/etc) 、
  • 受众标签(针对开发人员、针对机器学习等)、
  • 单页文档内容(例如自述文件)、
  • shell 名称(您在用户 shell 中输入的名称,例如 bash,或者在图形用户 shell 中找到的名称,例如开始菜单),
  • 的 python 模块列表
  • 这个包将安装(和卸载)事实上的“运行测试”入口点

python ./setup.py test它非常广泛,它甚至可以动态编译 c 扩展如果源模块正在开发计算机上安装。 对于日常示例,我推荐 PYPA 示例存储库的 setup.py

如果您要发布构建工件,例如旨在运行几乎相同的计算机的代码副本,则requirements.txt文件是捕获精确依赖关系信息的流行方法,其中“install_requires”是捕获最小和最小依赖关系的好方法。最大兼容版本。 然而,考虑到目标机器几乎是相同的,我强烈建议创建整个 python 前缀的 tarball。 这可能很棘手,太详细了,无法在这里讨论。 查看pip install--target选项,或virtualenv aka venv来寻找线索。

回到示例

,如何导入上一级目录的文件:

从 foo/spam/eggs.py 中,如果我们想要 foo/baz 中的代码,我们可以通过其绝对命名空间来请求它:

import foo.baz

如果我们想保留移动鸡蛋的功能。 py 到其他目录中,并使用其他相对的 baz 实现,我们可以使用相对导入,例如:

import ..baz

How to load a module that is a directory up

preface: I did a substantial rewrite of a previous answer with the hopes of helping ease people into python's ecosystem, and hopefully give everyone the best change of success with python's import system.

This will cover relative imports within a package, which I think is the most probable case to OP's question.

Python is a modular system

This is why we write import foo to load a module "foo" from the root namespace, instead of writing:

foo = dict();  # please avoid doing this
with open(os.path.join(os.path.dirname(__file__), '../foo.py') as foo_fh:  # please avoid doing this
    exec(compile(foo_fh.read(), 'foo.py', 'exec'), foo)  # please avoid doing this

Python isn't coupled to a file-system

This is why we can embed python in environment where there isn't a defacto filesystem without providing a virtual one, such as Jython.

Being decoupled from a filesystem lets imports be flexible, this design allows for things like imports from archive/zip files, import singletons, bytecode caching, cffi extensions, even remote code definition loading.

So if imports are not coupled to a filesystem what does "one directory up" mean? We have to pick out some heuristics but we can do that, for example when working within a package, some heuristics have already been defined that makes relative imports like .foo and ..foo work within the same package. Cool!

If you sincerely want to couple your source code loading patterns to a filesystem, you can do that. You'll have to choose your own heuristics, and use some kind of importing machinery, I recommend importlib

Python's importlib example looks something like so:

import importlib.util
import sys

# For illustrative purposes.
file_path = os.path.join(os.path.dirname(__file__), '../foo.py')
module_name = 'foo'

foo_spec = importlib.util.spec_from_file_location(module_name, file_path)
# foo_spec is a ModuleSpec specifying a SourceFileLoader
foo_module = importlib.util.module_from_spec(foo_spec)
sys.modules[module_name] = foo_module
foo_spec.loader.exec_module(foo_module)

foo = sys.modules[module_name]
# foo is the sys.modules['foo'] singleton

Packaging

There is a great example project available officially here: https://github.com/pypa/sampleproject

A python package is a collection of information about your source code, that can inform other tools how to copy your source code to other computers, and how to integrate your source code into that system's path so that import foo works for other computers (regardless of interpreter, host operating system, etc)

Directory Structure

Lets have a package name foo, in some directory (preferably an empty directory).

some_directory/
    foo.py  # `if __name__ == "__main__":`  lives here

My preference is to create setup.py as sibling to foo.py, because it makes writing the setup.py file simpler, however you can write configuration to change/redirect everything setuptools does by default if you like; for example putting foo.py under a "src/" directory is somewhat popular, not covered here.

some_directory/
    foo.py
    setup.py

.

#!/usr/bin/env python3
# setup.py

import setuptools

setuptools.setup(
    name="foo",
    ...
    py_modules=['foo'],
)

.

python3 -m pip install --editable ./  # or path/to/some_directory/

"editable" aka -e will yet-again redirect the importing machinery to load the source files in this directory, instead copying the current exact files to the installing-environment's library. This can also cause behavioral differences on a developer's machine, be sure to test your code!
There are tools other than pip, however I'd recommend pip be the introductory one :)

I also like to make foo a "package" (a directory containing __init__.py) instead of a module (a single ".py" file), both "packages" and "modules" can be loaded into the root namespace, modules allow for nested namespaces, which is helpful if we want to have a "relative one directory up" import.

some_directory/
    foo/
        __init__.py
    setup.py

.

#!/usr/bin/env python3
# setup.py

import setuptools

setuptools.setup(
    name="foo",
    ...
    packages=['foo'],
)

I also like to make a foo/__main__.py, this allows python to execute the package as a module, eg python3 -m foo will execute foo/__main__.py as __main__.

some_directory/
    foo/
        __init__.py
        __main__.py  # `if __name__ == "__main__":`  lives here, `def main():` too!
    setup.py

.

#!/usr/bin/env python3
# setup.py

import setuptools

setuptools.setup(
    name="foo",
    ...
    packages=['foo'],
    ...
    entry_points={
        'console_scripts': [
            # "foo" will be added to the installing-environment's text mode shell, eg `bash -c foo`
            'foo=foo.__main__:main',
        ]
    },
)

Lets flesh this out with some more modules:
Basically, you can have a directory structure like so:

some_directory/
    bar.py           # `import bar`
    foo/
        __init__.py  # `import foo`
        __main__.py
        baz.py       # `import foo.baz
        spam/           
            __init__.py  # `import foo.spam`
            eggs.py      # `import foo.spam.eggs`
    setup.py

setup.py conventionally holds metadata information about the source code within, such as:

  • what dependencies are needed to install named "install_requires"
  • what name should be used for package management (install/uninstall "name"), I suggest this match your primary python package name in our case foo, though substituting underscores for hyphens is popular
  • licensing information
  • maturity tags (alpha/beta/etc),
  • audience tags (for developers, for machine learning, etc),
  • single-page documentation content (like a README),
  • shell names (names you type at user shell like bash, or names you find in a graphical user shell like a start menu),
  • a list of python modules this package will install (and uninstall)
  • a defacto "run tests" entry point python ./setup.py test

Its very expansive, it can even compile c extensions on the fly if a source module is being installed on a development machine. For a every-day example I recommend the PYPA Sample Repository's setup.py

If you are releasing a build artifact, eg a copy of the code that is meant to run nearly identical computers, a requirements.txt file is a popular way to snapshot exact dependency information, where "install_requires" is a good way to capture minimum and maximum compatible versions. However, given that the target machines are nearly identical anyway, I highly recommend creating a tarball of an entire python prefix. This can be tricky, too detailed to get into here. Check out pip install's --target option, or virtualenv aka venv for leads.

back to the example

how to import a file one directory up:

From foo/spam/eggs.py, if we wanted code from foo/baz we could ask for it by its absolute namespace:

import foo.baz

If we wanted to reserve capability to move eggs.py into some other directory in the future with some other relative baz implementation, we could use a relative import like:

import ..baz
我做我的改变 2024-08-01 20:02:52

为了清楚起见,这是 ThorSummoner 答案的三步简单版本。 它并没有完全达到我想要的效果(我将在底部解释),但它可以正常工作。

步骤 1:创建目录和 setup.py

filepath_to/project_name/
    setup.py

setup.py 中,写入:

import setuptools

setuptools.setup(name='project_name')

步骤 2:将此目录作为包安装

在控制台中运行此代码:

python -m pip install --editable filepath_to/project_name

而不是 python,您可能需要使用python3或其他东西,具体取决于您的python安装方式。 另外,您可以使用 -e 而不是 --editable

现在,您的目录将或多或少看起来像这样。 不知道鸡蛋是什么东西

filepath_to/project_name/
    setup.py
    test_3.egg-info/
        dependency_links.txt
        PKG-INFO
        SOURCES.txt
        top_level.txt

该文件夹被视为 python 包,即使您在计算机上的其他位置编写脚本,也可以从此父目录中的文件导入。

步骤 3. 从上面导入

假设您创建了两个文件,一个位于项目的主目录中,另一个位于子目录中。 它看起来像这样:

filepath_to/project_name/
    top_level_file.py
    subdirectory/
        subfile.py

    setup.py          |
    test_3.egg-info/  |----- Ignore these guys
        ...           |

现在,如果 top_level_file.py 看起来像这样:

x = 1

那么我可以从 subfile.py 导入它,或者实际上是您的其他任何位置的任何其他文件电脑。

# subfile.py  OR  some_other_python_file_somewhere_else.py

import random # This is a standard package that can be imported anywhere.
import top_level_file # Now, top_level_file.py works similarly.

print(top_level_file.x)

这与我正在寻找的不同:我希望 python 有一种从上面的文件导入的单行方法。 相反,我必须将脚本视为模块,执行一堆样板文件,然后全局安装它,以便整个 python 安装能够访问它。 这太过分了。 如果有人有比不涉及上述过程或 importlib 恶作剧更简单的方法,请告诉我。

Here's a three-step, somewhat minimalist version of ThorSummoner's answer for the sake of clarity. It doesn't quite do what I want (I'll explain at the bottom), but it works okay.

Step 1: Make directory and setup.py

filepath_to/project_name/
    setup.py

In setup.py, write:

import setuptools

setuptools.setup(name='project_name')

Step 2: Install this directory as a package

Run this code in console:

python -m pip install --editable filepath_to/project_name

Instead of python, you may need to use python3 or something, depending on how your python is installed. Also, you can use -e instead of --editable.

Now, your directory will look more or less like this. I don't know what the egg stuff is.

filepath_to/project_name/
    setup.py
    test_3.egg-info/
        dependency_links.txt
        PKG-INFO
        SOURCES.txt
        top_level.txt

This folder is considered a python package and you can import from files in this parent directory even if you're writing a script anywhere else on your computer.

Step 3. Import from above

Let's say you make two files, one in your project's main directory and another in a sub directory. It'll look like this:

filepath_to/project_name/
    top_level_file.py
    subdirectory/
        subfile.py

    setup.py          |
    test_3.egg-info/  |----- Ignore these guys
        ...           |

Now, if top_level_file.py looks like this:

x = 1

Then I can import it from subfile.py, or really any other file anywhere else on your computer.

# subfile.py  OR  some_other_python_file_somewhere_else.py

import random # This is a standard package that can be imported anywhere.
import top_level_file # Now, top_level_file.py works similarly.

print(top_level_file.x)

This is different than what I was looking for: I hoped python had a one-line way to import from a file above. Instead, I have to treat the script like a module, do a bunch of boilerplate, and install it globally for the entire python installation to have access to it. It's overkill. If anyone has a simpler method than doesn't involve the above process or importlib shenanigans, please let me know.

顾忌 2024-08-01 20:02:52

@alex-martellipathlib:

import pathlib
import sys

_parentdir = pathlib.Path(__file__).parent.parent.resolve()
sys.path.insert(0, str(_parentdir))

import module_in_parent_dir

sys.path.remove(str(_parentdir))

Polished answer of @alex-martelli with pathlib:

import pathlib
import sys

_parentdir = pathlib.Path(__file__).parent.parent.resolve()
sys.path.insert(0, str(_parentdir))

import module_in_parent_dir

sys.path.remove(str(_parentdir))
非要怀念 2024-08-01 20:02:52

现在是 2022 年了,没有一个答案对我真正有用。 这是最终起作用的

import sys
sys.path.append('../my_class')
import my_class

我的目录结构:

src
--my_class.py
笔记本
-- mynotebook.ipynb

我从 mynotebook.ipynb 导入了 my_class

It is 2022 and none of the answers really worked for me. Here is what worked in the end

import sys
sys.path.append('../my_class')
import my_class

My directory structure:

src
--my_class.py
notebooks
-- mynotebook.ipynb

I imported my_class from mynotebook.ipynb.

春花秋月 2024-08-01 20:02:52

要运行导入/myprogram/mainmodule.pypython /myprogram/submodule/mymodule.py,例如,通过

from mainmodule import *

Linux(例如,在python Docker 镜像),我必须将程序根目录添加到 PYTHONPATH 中:

export PYTHONPATH=/myprogram

To run python /myprogram/submodule/mymodule.py which imports /myprogram/mainmodule.py, e.g., via

from mainmodule import *

on Linux (e.g., in the python Docker image), I had to add the program root directory to PYTHONPATH:

export PYTHONPATH=/myprogram
一向肩并 2024-08-01 20:02:52

您可以使用 sys.path.append() 方法将包含包的目录添加到搜索模块的路径列表中。 例如,如果包位于当前目录上方两个目录,则可以使用以下代码:

import sys
sys.path.append("../../")

如果包位于当前目录上方一个目录,则可以使用下面的代码:

import sys
sys.path.append("..")

You can use the sys.path.append() method to add the directory containing the package to the list of paths searched for modules. For example, if the package is located two directories above the current directory, you can use the following code:

import sys
sys.path.append("../../")

if the package is location one directory above the current directory, you can use below code:

import sys
sys.path.append("..")
伤痕我心 2024-08-01 20:02:52

Python 是一个模块化系统

Python 不依赖于文件系统

为了可靠地加载 python 代码,将该代码放在一个模块中,并将该模块安装在 python 的库中。

始终可以使用 import 从顶级命名空间加载已安装的模块,


这里有一个官方提供的很棒的示例项目:https://github.com/pypa/sampleproject

基本上,您可以拥有如下所示的目录结构:

the_foo_project/
    setup.py  

    bar.py           # `import bar`
    foo/
      __init__.py    # `import foo`

      baz.py         # `import foo.baz`

      faz/           # `import foo.faz`
        __init__.py
        daz.py       # `import foo.faz.daz` ... etc.

请务必在 setup.py 中声明您的 setuptools.setup()

官方示例:https://github.com/pypa/sampleproject/blob/master/setup.py

在我们的例子中,我们可能想要导出 bar. pyfoo/__init__.py,我的简短示例:

setup.py

#!/usr/bin/env python3

import setuptools

setuptools.setup(
    ...
    py_modules=['bar'],
    packages=['foo'],
    ...
    entry_points={}, 
        # Note, any changes to your setup.py, like adding to `packages`, or
        # changing `entry_points` will require the module to be reinstalled;
        # `python3 -m pip install --upgrade --editable ./the_foo_project
)

现在我们可以将模块安装到 python 库中;
使用 pip,您可以在编辑模式下将 the_foo_project 安装到您的 python 库中,
这样我们就可以实时处理它

python3 -m pip install --editable=./the_foo_project

# if you get a permission error, you can always use 
# `pip ... --user` to install in your user python library

现在,从任何 python 上下文,我们可以加载共享的 py_modules 和包

foo_script.py

#!/usr/bin/env python3

import bar
import foo

print(dir(bar))
print(dir(foo))

Python is a modular system

Python doesn't rely on a file system

To load python code reliably, have that code in a module, and that module installed in python's library.

Installed modules can always be loaded from the top level namespace with import <name>


There is a great sample project available officially here: https://github.com/pypa/sampleproject

Basically, you can have a directory structure like so:

the_foo_project/
    setup.py  

    bar.py           # `import bar`
    foo/
      __init__.py    # `import foo`

      baz.py         # `import foo.baz`

      faz/           # `import foo.faz`
        __init__.py
        daz.py       # `import foo.faz.daz` ... etc.

.

Be sure to declare your setuptools.setup() in setup.py,

official example: https://github.com/pypa/sampleproject/blob/master/setup.py

In our case we probably want to export bar.py and foo/__init__.py, my brief example:

setup.py

#!/usr/bin/env python3

import setuptools

setuptools.setup(
    ...
    py_modules=['bar'],
    packages=['foo'],
    ...
    entry_points={}, 
        # Note, any changes to your setup.py, like adding to `packages`, or
        # changing `entry_points` will require the module to be reinstalled;
        # `python3 -m pip install --upgrade --editable ./the_foo_project
)

.

Now we can install our module into the python library;
with pip, you can install the_foo_project into your python library in edit mode,
so we can work on it in real time

python3 -m pip install --editable=./the_foo_project

# if you get a permission error, you can always use 
# `pip ... --user` to install in your user python library

.

Now from any python context, we can load our shared py_modules and packages

foo_script.py

#!/usr/bin/env python3

import bar
import foo

print(dir(bar))
print(dir(foo))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文