在setuptools包上的Pyinstaller

问题描述 投票:7回答:4

我正在尝试使用Click库在我使用Python构建的CLI应用程序上运行PyInstaller。我在使用PyInstaller构建项目时遇到了麻烦。 PyInstaller在他们的GitHub wiki中有一个名为Recipe Setuptools Entry Point的文档,该文档提供了有关如何将PyInstaller与setuptools包一起使用的信息,我正在将其用于此项目。但是,当我运行pyinstaller --onefile main.spec时,它似乎无法找到基本模块。

我的问题是:问题只是我的文件夹结构的问题吗? Recipe Setuptools Entry Point是否假定某种文件结构?

相关信息

Pyinstaller输出

184 INFO: PyInstaller: 3.3.1
184 INFO: Python: 3.6.4
189 INFO: Platform: Darwin-16.7.0-x86_64-i386-64bit
193 INFO: UPX is available.
Traceback (most recent call last):
  File "/usr/local/bin/pyinstaller", line 11, in <module>
    sys.exit(run())
  File "/usr/local/lib/python3.6/site-packages/PyInstaller/__main__.py", line 94, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "/usr/local/lib/python3.6/site-packages/PyInstaller/__main__.py", line 46, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/PyInstaller/building/build_main.py", line 791, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "/usr/local/lib/python3.6/site-packages/PyInstaller/building/build_main.py", line 737, in build
    exec(text, spec_namespace)
  File "<string>", line 40, in <module>
  File "<string>", line 26, in Entrypoint
  File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 582, in get_entry_info
    return get_distribution(dist).get_entry_info(group, name)
  File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 564, in get_distribution
    dist = get_provider(dist)
  File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 436, in get_provider
    return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
  File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 984, in require
    needed = self.resolve(parse_requirements(requirements))
  File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 870, in resolve
    raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'myapp' distribution was not found and is required by the application

main.specmain.py文件,这是我的CLI应用程序的入口点:

block_cipher = None

def Entrypoint(dist, group, name,
               scripts=None, pathex=None, hiddenimports=None,
               hookspath=None, excludes=None, runtime_hooks=None):
    import pkg_resources

    # get toplevel packages of distribution from metadata
    def get_toplevel(dist):
        distribution = pkg_resources.get_distribution(dist)
        if distribution.has_metadata('top_level.txt'):
            return list(distribution.get_metadata('top_level.txt').split())
        else:
            return []

    hiddenimports = hiddenimports or []
    packages = []
    for distribution in hiddenimports:
        packages += get_toplevel(distribution)

    scripts = scripts or []
    pathex = pathex or []
    # get the entry point
    ep = pkg_resources.get_entry_info(dist, group, name)
    # insert path of the egg at the verify front of the search path
    pathex = [ep.dist.location] + pathex
    # script name must not be a valid module name to avoid name clashes on import
    script_path = os.path.join(workpath, name + '-script.py')
    print ("creating script for entry point", dist, group, name)
    with open(script_path, 'w') as fh:
        print("import", ep.module_name, file=fh)
        print("%s.%s()" % (ep.module_name, '.'.join(ep.attrs)), file=fh)
        for package in packages:
            print ("import", package, file=fh)

    return Analysis([script_path] + scripts, pathex, hiddenimports, hookspath, excludes, runtime_hooks)

a = Entrypoint('myapp', 'console_scripts', 'myapp')

pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          exclude_binaries=True,
          name='main',
          debug=False,
          strip=False,
          upx=True,
          console=True )
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               name='main')

我在虚拟环境中运行myapp时生成的pip3 install --editable .脚本的内容:

#!/some/path/to/myapp-cli/venv/bin/python3.6
# EASY-INSTALL-ENTRY-SCRIPT: 'myapp','console_scripts','myapp'
__requires__ = 'myapp'
import re
import sys
from pkg_resources import load_entry_point

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
    sys.exit(
        load_entry_point('myapp', 'console_scripts', 'myapp')()
    )

最后,我的存储库结构:

myapp-cli/
├── README.md
├── myapp
│   ├── __init__.py
│   ├── main.py
│   ├── main.spec
│   ├── resources
│   │   ├── __init__.py
│   │   └── functions.py
│   ├── subcommands
│   │   ├── __init__.py
│   │   ├── config
│   │   │   ├── __init__.py
│   │   │   └── cli.py
│   │   ├── create
│   │   │   ├── __init__.py
│   │   │   └── cli.py
│   │   ├── destroy
│   │   │   ├── __init__.py
│   │   │   └── cli.py
│   │   └── switch
│   │       ├── __init__.py
│   │       └── cli.py
│   └── variables.py
├── requirements.txt
└── setup.py

和我的setup.py文件:

from setuptools import find_packages
from setuptools import setup
import os

base_dir = os.path.dirname(__file__)

setup(
    entry_points = '''
        [console_scripts]
        myapp=myapp.main:entry_point
    ''',
    install_requires = [
        'packageone==1.0',
        'packagetwo==2.0',
    ],
    name = "myapp",
    packages=find_packages(),
    setup_requires="setuptools",
    version = "0.1",
)
python python-3.x pyinstaller setuptools python-click
4个回答
3
投票

这个错误:

pkg_resources.DistributionNotFound:找不到'myapp'分发,并且是应用程序所必需的

表示此包不在PYTHONPATH上。我在Windows上修复它:

set PYTHONPATH=.

适应您选择的操作系统。


除路径问题外,还有:

In setup.py:

setup(
    entry_points = '''
        [console_scripts]
        myapp=myapp.main:entry_point
    ''',

In main.spec:

a = Entrypoint('myapp', 'console_scripts', 'myapp')

根据setup.py,看起来你的入口点是myapp.main而不是myapp。所以你可能需要:

a = Entrypoint('myapp', 'console_scripts', 'myapp.main')

3
投票

第一:我使用斯蒂芬的答案和一些自己的挖掘来找到答案。最后,斯蒂芬的第一部分就是诀窍:手动添加/导出PYTHONPATH变量。你可以在pathex函数中使用Entrypoint来实际指定它,如下所示:

a = Entrypoint('myapp-cli',
    'console_scripts',
    'myapp',
    pathex=['/some/path/to/myapp-cli/myapp', '/some/path/to/myapp-cli']
)

毕竟我最终还不需要myapp.main

第二:我仍然遇到PyInstaller没有生成单个二进制文件的问题。对我来说,这就是诀窍:

  • 将最新版本的PyInstaller添加到requirements.txtinstall_requires中的setup.pyhttps://github.com/pyinstaller/pyinstaller/archive/develop.zip
  • 此外,你可以使用.spec中的--onefile选项制作你的pyi-makespec文件,如:pyi-makespec --onefile myapp.py。这将生成一个.spec文件,确保将所有包编译为二进制文件。

最后,以下spec文件完成了这个技巧,我能够创建一个完全正常工作的二进制文件:

# -*- mode: python -*-

block_cipher = None

def Entrypoint(dist, group, name,
               scripts=None, pathex=None, hiddenimports=None,
               hookspath=None, excludes=None, runtime_hooks=None):
    import pkg_resources

    # get toplevel packages of distribution from metadata
    def get_toplevel(dist):
        distribution = pkg_resources.get_distribution(dist)
        if distribution.has_metadata('top_level.txt'):
            return list(distribution.get_metadata('top_level.txt').split())
        else:
            return []

    hiddenimports = hiddenimports or []
    packages = []
    for distribution in hiddenimports:
        packages += get_toplevel(distribution)

    scripts = scripts or []
    pathex = pathex or []
    # get the entry point
    ep = pkg_resources.get_entry_info(dist, group, name)
    # insert path of the egg at the verify front of the search path
    pathex = [ep.dist.location] + pathex
    # script name must not be a valid module name to avoid name clashes on import
    script_path = os.path.join(workpath, name + '-script.py')
    print ("creating script for entry point", dist, group, name)
    with open(script_path, 'w') as fh:
        print("import", ep.module_name, file=fh)
        print("%s.%s()" % (ep.module_name, '.'.join(ep.attrs)), file=fh)
        for package in packages:
            print ("import", package, file=fh)

    return Analysis([script_path] + scripts, pathex, hiddenimports, hookspath, excludes, runtime_hooks)

a = Entrypoint('myapp-cli',
    'console_scripts',
    'myapp',
    pathex=['/some/path/to/myapp-cli/myapp', '/some/path/to/myapp-cli']
)

pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='myapp',
          debug=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          console=True )

我认为最终使用类似Cobra for Golang的东西会更容易工作,因为Golang编译开箱即用的单文件二进制文件。但是,如果您更喜欢Python,这应该可以解决问题。


0
投票

我注意到的一点是,一旦你按照Scott Crooks在typical way of adding a data file中推荐的方式修补了入口点,ticked answer就不起作用了。对我来说,我不得不附加到a.datas阵列。在python3中,这看起来像:

...
a = Entrypoint(...)
from pathlib import Path
Path('/tmp/modulename/datafile.txt').write_text(Path('datafile.txt').read_text()))
a.datas.append('datafile.txt', '/tmp/modulename/datafile.txt', 'DATA')

pyz = PYZ(...)
...

0
投票

接受的答案对我不起作用。我必须通过egg-info文件添加.spec目录。

我对Entrypoint函数的调用如下所示:

a = Entrypoint(
        'PrintIt',
        'console_scripts',
        'printit',
        datas=[('plugins/*.egg', 'plugins/'),
               ('../PrintIt.egg-info/*', 'PrintIt.egg-info/')])
© www.soinside.com 2019 - 2024. All rights reserved.