![](/img/trans.png)
[英]Python - Including python scripts from project root in setup.py build
[英]including python file from project root in setup.py build
我試圖在運行時創建的 build/lib 目錄中包含一個 python 文件
python setup.py install
特別是,我想包含一個簡單的配置文件('definitions.py'),它定義了一個 ROOT_DIR 變量,然后由子包使用。 “definitions.py”文件包含:
import os
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
我的目標是讓每個子包 ('config.py') 中的配置文件調用 ROOT_DIR 來構建自己的絕對路徑:
from definitions import ROOT_DIR
PACKAGE_DIR = os.path.join(ROOT_DIR, 'package1/')
這個想法來自這個 stackoverflow 答案: https : //stackoverflow.com/a/25389715 。
但是,在運行“setup.py install”時,這個“definitions.py”文件永遠不會出現在構建目錄中。
下面是項目的目錄結構:
project | ├── setup.py | ├── definitions.py | ├── package1 | ├── __init__.py | ├── config.py | └── ... | ├── package2 | ├── __init__.py | └── ... └── ...
我的多次嘗試都失敗了(嘗試,例如https://stackoverflow.com/a/11848281 中提供的建議)。 據我所知,這是因為 definition.py 位於我的項目結構的頂層(缺少 __init__.py 文件)。
我試過了:
1) ...在 setuptools.setup() 中使用“package-data”變量
package_data={'package': ['./definitions.py']}
但 definition.py 沒有出現在構建中
2) ...使用 MANIFEST.in 文件,但這也不起作用
我的問題:
有沒有辦法在構建目錄中包含定義.py?
或者,是否有更好的方法來訪問從多個子包的頂級目錄構建的絕對路徑?
如果您正在尋找一種方法來訪問已安裝模塊中的非 python 數據文件,如您鏈接的問題(頂級包中的配置文件,應在子包中訪問),請使用pkg_resources
機器而不是發明自定義路徑解析。 一個示例項目結構:
project
├── setup.py
└── root
├── __init__.py
├── config.txt
├── sub1
│ └── __init__.py
└── sub2
└── __init__.py
setup.py
:
from setuptools import setup
setup(
name='myproj',
...,
packages=['root', 'root.sub1', 'root.sub2'], # or setuptools.find_packages()
package_data={'root': ['config.txt']}
)
正如wim在評論中指出的那樣,現在有一個importlib.resources
移植(僅在 Python 3.7 及更高版本中可用) - importlib_resources
,它提供了一種利用pathlib
的現代資源機制:
# access the filepath
importlib_resources.path('root', 'config.txt')
# access the contents as string
importlib_resources.read_text('root', 'config.txt')
# access the contents as file-like object
importlib_resources.open_binary('root', 'config.txt')
使用pkg_resources
,您可以從包的任何位置訪問root/config.txt
,而無需執行任何路徑解析:
import pkg_resources
# access the filepath:
filepath = pkg_resources.resource_filename('root', 'config.txt')
# access the contents as string:
contents = pkg_resources.resource_string('root', 'config.txt')
# access the contents as file-like object:
contents = pkg_resources.resource_stream('root', 'config.txt')
等等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.