Python - 在 setup.py install 之前和之后导入包模块 [英] Python - Import package modules before as well as after setup.py install

查看:76
本文介绍了Python - 在 setup.py install 之前和之后导入包模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个 Python 包(例如,MyPackage)由几个模块(例如,MyModule1.pyMyModule2.py)和一组单元测试(例如,在 MyPackage_test.py 中).

<预><代码>.├── 我的包裹│ ├── __init__.py│ ├── MyModule1.py│ └── MyModule2.py├── README.md├──需求.txt├── setup.py└── 测试└── MyPackage_test.py

我想在MyPackage_test.py 的单元测试中导入MyModule1.py 的函数.具体来说,我想通过 setup.py install MyPackage 在包安装之前和之后导入这些函数.

目前,我使用两个单独的命令,具体取决于安装包之前或之后的状态:

# BEFORE导入系统,操作系统sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'MyPackage'))# 后导入我的包裹

这可以用一个命令完成吗?

解决方案

选项 1:

似乎以下命令满足了我的需要:

sys.path.append(os.path.join(__file__.split(__info__)[0] + __info__), __info__)

选项 2:

根据 __init__.py 的位置,这也有效:

sys.path.append(os.path.dirname(os.path.split(inspect.getfile(MyPackage))[0]))

选项 3:

此外,ResourceManager API 似乎提供了其他方法.

Assume a Python package (e.g., MyPackage) that consists of several modules (e.g., MyModule1.py and MyModule2.py) and a set of unittests (e.g., in MyPackage_test.py).

.
├── MyPackage
│   ├── __init__.py
│   ├── MyModule1.py
│   └── MyModule2.py
├── README.md
├── requirements.txt
├── setup.py
└── tests
    └── MyPackage_test.py

I would like to import functions of MyModule1.py within the unittests of MyPackage_test.py. Specifically, I would like to import the functions both before as well as after package installation via setup.py install MyPackage.

Currently, I am using two separate commands, depending on the state before or after package installation:

# BEFORE
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'MyPackage'))

# AFTER
import MyPackage

Can this be done with a single command?

解决方案

Option 1:

It seems that the following command does what I need:

sys.path.append(os.path.join(__file__.split(__info__)[0] + __info__), __info__)

Option 2:

Depending on the location of __init__.py, this also works:

sys.path.append(os.path.dirname(os.path.split(inspect.getfile(MyPackage))[0]))

Option 3:

Moreover, the ResourceManager API seems to offer additional methods.

这篇关于Python - 在 setup.py install 之前和之后导入包模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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