有没有办法根据操作系统和模块中的 Python 版本从特定文件夹导入 Python?

问题描述 投票:0回答:1

我正在用 Python 构建一个图像处理模块,我在其中使用一些 Fortran90 编译文件来简化迭代方法,但这些文件严格取决于 Python 版本。

现在,我有这个目录结构:

├── ImageExtras.egg-info
│   ├── PKG-INFO
│   ├── SOURCES.txt
│   ├── dependency_links.txt
│   ├── requires.txt
│   ├── top_level.txt
│   └── zip-safe
├── LICENSE
├── MANIFEST.in
├── README.md
├── __init__.py
├── imageextras
│   ├── __init__.py <--
│   ├── cmp_src
│   │   └── dithering.f90
│   ├── compiled
│   │   ├── __init__.py
│   │   ├── py310
│   │   │   ├── __init__.py
│   │   │   ├── linux
│   │   │   │   ├── __init__.py
│   │   │   │   └── dithering.cpython-310-x86_64-linux-gnu.so
│   │   │   └── win
│   │   │       ├── __init__.py
│   │   │       └── dithering.cp310-win_amd64.pyd
│   │   └── py39
│   │       ├── __init__.py
│   │       ├── linux
│   │       │   ├── __init__.py
│   │       │   └── dithering.cpython-39-x86_64-linux-gnu.so
│   │       └── win
│   │           ├── __init__.py
│   │           └── dithering.cp39-win_amd64.pyd
│   └── src
│       ├── __init__.py
│       └── utils.py
├── setup.cfg
└── setup.py

我遇到的问题出现在我用箭头标记的 python 初始化文件中。我希望根据操作系统和 Python 版本导入不同的文件,所以我做了这个并添加到标记的初始化文件中:

# Native imports
from imageextras.src.utils import *

# Compiled imports
import os
import platform
import sys

system = platform.system()

if (sys.version_info >= (3, 10)) and (sys.version_info < (3, 11)):
    py_ver = "py310"
elif (sys.version_info >= (3, 9)) and (sys.version_info < (3, 10)):
    py_ver = "py39"
else:
    raise RuntimeError("Unsupported Python version")

if system == "Windows":
    os_choice = "win"
elif system == "Linux":
    os_choice = "linux"
else:
    raise OSError(f"Unsupported platform: {system}")

module_names = ["dithering"] # modules to add

for module_name in module_names:
    module_dir = os.path.join("imageextras", "compiled", py_ver, os_choice)
    sys.path.append(module_dir)
    __import__(module_name)

出于某种原因无法导入文件。

我构建了包,每当我尝试导入模块时,它就是无法导入“抖动”模块。问题是,使用包本身而不安装它可以正常工作,但只要我“pip install”。并尝试使用另一个目录中的包,找不到该文件。顺便说一句,我确保在清单中包含所需的文件,如果我检查安装,所有文件都在它们应该在的位置,这让我无能为力。我也尝试过将相对路径更改为绝对路径,但它也没有用。

作为一次孤注一掷的尝试,我尝试将 init 文件更改为:

# Native imports
from imageextras.src.utils import *

# Provisional workaround
try:
    from imageextras.compiled.py310.win import dithering
except:
    
    try:
        from imageextras.compiled.py39.win import dithering
    except:
        
        try:
            from imageextras.compiled.py310.linux import dithering
        except:    
            from imageextras.compiled.py39.linux import dithering

这很好用。我一无所知。我得到的错误是:“找不到模块抖动”

python module package setuptools pypi
1个回答
0
投票

根据这个answer,看来推荐的方法是使用

importlib

for module_name in module_names:
    importlib.import_module(f'imageextras.compiled.{py_ver}.{os_choice}.{module_name}')
© www.soinside.com 2019 - 2024. All rights reserved.