pyshorteners 在可执行文件中不起作用

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

我正在尝试在从 Python 脚本创建的可执行文件中使用 pyshorteners 库。当我将代码作为 Python 脚本运行时,代码运行良好,但是当我运行可执行版本时,它会抛出错误:

def Shorten_Link(link):
    shortener = pyshorteners.Shortener()
    return shortener.tinyurl.short(link)

我在日志文件中得到的错误是:

File "main.py", line 38, in Shorten_Link
  File "pyshorteners\__init__.py", line 32, in __init__
  File "importlib\__init__.py", line 126, in import_module
  File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'pyshorteners.shorteners'

我正在使用 PyInstaller 转换为可执行文件。我该如何解决这个问题? 或者还有其他简单的选择吗?

python
1个回答
0
投票

图书馆需要进行一些改动。首先,您需要导航到库目录,该目录通常位于: C:\USER**\AppData\Local\Programs\Python\Python310\Lib\site-packages\pyshorteners **请用您的用户名替换“USER”。

导航到目录后,打开“shorteners”子目录并复制除“init.py”文件以外的所有文件。将这些文件粘贴到主目录 (pyshorteners) 中。接下来,打开“init.py”文件并插入以下代码:

import logging
import importlib
import pkgutil

logger = logging.getLogger(__name__)
__version__ = "1.0.1"
__author__ = "Ellison Leão"
__email__ = "[email protected]"
__license__ = "GPLv3"


class Shortener(object):
    """Base Factory class to create shoreteners instances

    >>> s = Shortener(**kwargs)
    >>> instance = s.shortener_name
    >>> instance.short('http://www.google.com')
    'http://short.url/'

    Available Shorteners can be seen with:

    >>> s = Shortener()
    >>> print(s.available_shorteners)
    """

    def __init__(self, **kwargs):
        self.kwargs = kwargs
        # validate some required fields
        self.kwargs["debug"] = bool(kwargs.pop("debug", False))
        self.kwargs["timeout"] = int(kwargs.pop("timeout", 2))
        self.kwargs["verify"] = bool(kwargs.pop("verify", True))
        module = importlib.import_module("pyshorteners")
        self.available_shorteners = [
            i.name for i in pkgutil.iter_modules(module.__path__)
        ]

    def __getattr__(self, attr):
        if attr not in self.available_shorteners:
            return self.__getattribute__(attr)

        # get instance of shortener class
        short_module = importlib.import_module(
            "{}.{}".format("pyshorteners", attr)
            
        )
        instance = getattr(short_module, "Shortener")(**self.kwargs)

        return instance

之后,您需要导入您正在使用的模块。例如,如果您使用 Shortener 类的“tinyurl”属性,您还需要在代码中导入它。

希望对您有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.