pyinstaller 打包 pytest 项目报了 importerror while loading conftest.py

使用pyinstaller打包pytest项目,输入参数运行打包程序之后报了一下错误

img


以下是我的 spec 文件配置

# -*- mode: python ; coding: utf-8 -*-
import sys
import os.path as osp
sys.setrecursionlimit(5000)

block_cipher = None

a = Analysis(['QTmain.py','C:\\Users\\65435\\PycharmProjects\\demo_Qt\\testcases\\conftest.py'
],
             pathex=['C:\\Users\\65435\\PycharmProjects\\demo_Qt'],
             binaries=[],
             datas=[('resource','.'),('testcases','.'),('conf','.')],
             hiddenimports=[],
             hookspath=['C:\\Users\\65435\\PycharmProjects\\demo_Qt'],
             hooksconfig={},
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)

exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,  
          [],
          name='QTmain',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=True,
          disable_windowed_traceback=False,
          target_arch=None,
          codesign_identity=None,
          entitlements_file=None , icon='img.ico')

打包命令
pyinstaller -F -w -i img.ico C:\Users\65435\PycharmProjects\demo_Qt\QTmain.spec

尝试过删除__pycache__文件再打包依然报错

pyinstaller 打包的文件应该是py文件,而不是spec

conftest.py这个包import 失败了,你检查一下你的目录结构

打包的步骤可以看我写的这篇文章,你打包的命令错误了。

解决方法

1、查看原先本地直接运行python文件是否正常启动,如果有第三方库缺失,记得安装
2、查看下pyinstaller打包时候的路径

如果上述都正确
尝试一下方法对pytest进行打包,

pytest_with_pyinstaller.py :

import pytest

class TestSanity(): 
    def test_step_1(self): 
        assert 2==2 
#        if __name__ == "__main__": 
        test=pytest.main(['-v', '-x', '--durations=0'])
        print(test)


TestSanity().test_step_1()

我将其保存为“pytest_with_pyinstaller.py”

然后我在anaconda提示符中使用了这一行来打包pyinstaller文件

pyinstaller --exclude-module PyQt5 --hidden-import pytest.mark --hidden-import py._builtin    --onefile --hidden-import pytest.main U:\PLAN\BCUBRICH\Python\Tests\pytest_with_pyinstaller.py

然后我从 Windows cmd 控制台运行生成的 .exe。

>Run>cmd
>cd "your output director"
>"your_exe.exe"
C:\Users\bcubrich\dist\test2>pytest_with_pyinstaller.exe ============================= 测试会话开始 ==== ========================= 平台 win32 -- Python 3.7.1、pytest-4.0.2、py-1.7.0、pluggy-0.80 -- C:\Users\bcubrich\dist\test2\pytest_with_pyinstaller.exe cachedir: .pytest_cache rootdir: C:\Users\bcubrich\dist\test2, inifile: 收集到 0 个项目


======================== 0.01 秒内没有运行测试 ==================== =====

5

末尾的 5 似乎是 pytest 行,与我在 spyder 中运行此代码时得到的数字相同,所以我认为它正在工作,除了 pytest 脚本将尝试测试 dist 目录中的任何内容。

参考链接:

如果上述方法还未起作用,这个链接内还有其他方法,可以尝试下是否可以解决。


如有问题及时沟通

同样使用此版本,您可以尝试使用不同的--import-mode选项值,特别是pytest --import-mode=importlib
或者删除__init__.py