Pyinstaller 使用外部库创建可执行文件

Pyinstaller create an executable with external libraries

我正在尝试为我在 PyCharm 中编写的 Python 脚本创建一个可执行文件 (exe)。 当我 运行 来自 PyCharm 的脚本工作正常但是当我尝试 运行 它作为一个单独的 .py 或尝试 运行 exe 时我收到一个错误.

我认为问题出在 "from infi.devicemanager import DeviceManager" 库上。

from infi.devicemanager import DeviceManager # Used for the retrievement of Device manager information
dm = DeviceManager()
dm.root.rescan()
devs = dm.all_devices # Get all the devices to a list called devs
for d in devs:
    print (d.description)

我收到以下错误:

PS C:\Python> python.exe .\tests.py
Traceback (most recent call last):
  File ".\tests.py", line 1, in <module>
    import infi.devicemanager # Used for the retrievement of Device manager information
ModuleNotFoundError: No module named 'infi'

PS C:\Python> pyinstaller -F .\tests.py

PS C:\Python\dist> .\tests.exe
Traceback (most recent call last):
  File "tests.py", line 1, in <module>
ModuleNotFoundError: No module named 'infi'
[15072] Failed to execute script tests

有没有办法将这个库包含到 exe 文件中,这样没有 python 的任何人都可以 运行 这个脚本? 我乐于接受建议。

提前致谢!

===更新=== 完整的脚本可以在这里找到 https://github.com/elessargr/k9-serial

我的回答假设具有 infi.devicemanager 的解释器是 C:\Python\venv\Scripts\python.exe,如 OP 在评论中所述

所以有一个名为venv的虚拟环境。您需要激活虚拟环境并在其中安装PyInstaller。

C:\Python>venv\Scripts\activate
(venv)C:\Python>

请注意 shell 前面的 (venv) - 这意味着虚拟环境 venv 已激活 现在安装 PyInstaller

(venv)C:\Python>pip install pyinstaller
-- here it will install pyinstaller --

现在您可以测试 pyinstallerinfi.devicemanager 都安装在 venv

(venv)C:\Python>pip list

它应该列出这两个软件包以及其他软件包。现在

(venv)C:\Python>pyinstaller -F C:\Python\tests.py --hidden-import=infi.devicemanager
--here it will create the exe --

如果我是对的,它现在应该可以工作了

编辑:看起来 infi 正在使用 __import__(pkg_resources),所以命令应该是

(venv)C:\Python>pyinstaller -F C:\Python\tests.py --hidden-import=infi.devicemanager --hiden-import=pkg_resources