使用Pyinstaller或Cython从Python模块创建可执行文件

4

我希望将这个Python 2.7项目转换为可执行文件,它具有模块结构:此页面

(.venv) ip-192-168-22-127:indictrans loretoparisi$ tree -L 1
.
├── __init__.py
├── __init__.pyc
├── __init__.spec
├── _decode
├── _utils
├── base.py
├── build
├── mappings
├── models
├── script_transliterate.py
├── tests
├── transliterator.py
└── trunk

我正在使用pyinstaller。在第一阶段,我只是这样做:

pyinstall --onefile __init__.py

然后我得到了一个可执行文件:

192 INFO: PyInstaller: 3.3.1
192 INFO: Python: 2.7.10
201 INFO: Platform: Darwin-17.7.0-x86_64-i386-64bit
202 INFO: wrote /Users/loretoparisi/Documents/Projects/AI/indic-trans/indictrans/__init__.spec
208 INFO: UPX is not available.
209 INFO: Extending PYTHONPATH with paths
['/Users/loretoparisi/Documents/Projects/AI/indic-trans',
 '/Users/loretoparisi/Documents/Projects/AI/indic-trans/indictrans']
210 INFO: checking Analysis
218 INFO: checking PYZ
223 INFO: checking PKG
224 INFO: Bootloader /Users/loretoparisi/Documents/Projects/AI/indic-trans/.venv/lib/python2.7/site-packages/PyInstaller/bootloader/Darwin-64bit/run
224 INFO: checking EXE
225 INFO: Rebuilding out00-EXE.toc because __init__ missing
225 INFO: Building EXE from out00-EXE.toc
225 INFO: Appending archive to EXE /Users/loretoparisi/Documents/Projects/AI/indic-trans/indictrans/dist/__init__
230 INFO: Fixing EXE for code signing /Users/loretoparisi/Documents/Projects/AI/indic-trans/indictrans/dist/__init__
234 INFO: Building EXE from out00-EXE.toc completed successfully.

但是当我运行它时,出现了导入错误。

Traceback (most recent call last):
  File "indictrans/__init__.py", line 9, in <module>
ValueError: Attempted relative import in non-package
[30629] Failed to execute script __init__

这个库是使用Cython通过cythonize安装构建的,因此另一个选项是使用--embedCython选项构建嵌入式可执行模块。

我的setup.py文件如下:

#!/usr/bin/env python

import os

from setuptools import setup
from setuptools.extension import Extension
from Cython.Build import cythonize

import numpy


os.environ['PBR_VERSION'] = '1.2.3'
os.environ['SKIP_WRITE_GIT_CHANGELOG'] = '1'
os.environ['SKIP_GENERATE_AUTHORS'] = '1'


extensions = [
    Extension(
        "indictrans._decode.beamsearch",
        [
            "indictrans/_decode/beamsearch.pyx"
        ],
        include_dirs=[numpy.get_include()]
    ),
    Extension(
        "indictrans._decode.viterbi",
        [
            "indictrans/_decode/viterbi.pyx"
        ],
        include_dirs=[numpy.get_include()]
    ),
    Extension(
        "indictrans._utils.ctranxn",
        [
            "indictrans/_utils/ctranxn.pyx"
        ],
        include_dirs=[numpy.get_include()]
    ),
    Extension(
        "indictrans._utils.sparseadd",
        [
            "indictrans/_utils/sparseadd.pyx"
        ],
        include_dirs=[numpy.get_include()]
    )

]

setup(
    setup_requires=['pbr'],
    pbr=True,
    ext_modules=cythonize(extensions)
)

虽然使用 --embed 选项 编译单个 Python 文件很容易,有关此内容,请参见这里,但我不知道如何在 setup.py 中使用 --embed 选项 去除项目中的所有依赖关系。


你用Python开始的主文件是哪个?是transliterator.py吗? - Stack
@Stack 我认为这是问题的一部分,因为主函数在__init__.py文件中,该文件处理参数并将其传递给从transliterator.py导入的Transliterator类。 - loretoparisi
1
尝试使用 pyinstaller --onefile transliterator.py 命令,或将主函数移动到另一个新文件中并尝试运行。 - Stack
@Stack 谢谢,我更愿意不改变模块结构,因为这将是一个从源代码自动构建的系统。顺便说一下,我已经添加了关于 setup.pyCython 的更多信息,如果你能帮忙,谢谢! - loretoparisi
1个回答

1
我将用包含setup.py文件的根目录来指代目录,对于你的情况是indic-trans。我将第一级源代码目录称为模块目录,对于你的情况是indic-trans/indictrans
如果我正确理解您的设置,您有一个问题,因为尝试在模块目录中创建一个脚本的.exe而不是目录。这使得当前目录成为内部模块目录,相对引用将无法工作。
在类似情况下,我解决此问题的方式是在主要目录(与setup.py相同的文件夹)中创建一个run.py脚本,该脚本导入包,然后运行您想要在模块目录内运行的任何脚本。
您没有发布__init__.py文件(顺便说一下,在__init.py__中放置任何真正的代码通常是不被允许的......),因此我将假设您想要在base.py脚本中运行main()函数。在这种情况下,使run.py类似于:
# This will import everything from the module __init__.py based on it's "all" setup
# You likely want to limit it to just what is needed or just the script you are targeting
# Or you can use the "import indictrans" format and let __init__.py handle it
from indictrans import * 

def main():
    indictrans.base.main()

if __name__ == '__main__':
    main()

现在,您可以从命令行中运行run.py或将其用作调试目标来运行您的软件包。
请注意,使用PyInstaller,您可以针对run.py(或run.spec)进行定位,并使用--name参数将其更改为其他名称。
pyinstaller --onefile --name indictrans run.spec

这将在dist目录中创建indictrans.exe


将您的软件包作为模块运行

请注意,在模块目录中,您还可以创建一个__main__.py文件,它基本上是run.py的副本,并执行相同的操作,但如果Python可执行文件在本地安装,则将作为模块运行。

python -m indictrans将使用__main__.py作为入口点来运行您的软件包。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接