python - pyinstaller hidden_import exe 文件然后子进程 Popen exe 文件

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

是否有可能在 .spec 文件中包含一个 exe 文件作为 hidden_import,然后在主 py 脚本中使用命令 subprocess.Popen 来运行它?

我收到这样的错误:

Traceback (most recent call last):
  File "running_example.py", line 40, in <module>
    s = shout.Shout()
  File "shout.py", line 66, in __init__
    self.p1 = Popen([resource_path0("msys_shout.exe")], stdin=PIPE, stdout=PIPE,shell=False, universal_newlines=True, bufsize=1, close_fds=ON_POSIX)
  File "subprocess.py", line 969, in __init__
  File "subprocess.py", line 1438, in _execute_child
FileNotFoundError: [WinError 2] The system cannot find the file specified

resource_path0 函数是:

def resource_path0(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(
        sys,
        '_MEIPASS',
        os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)

.spec 文件是:

# -*- mode: python ; coding: utf-8 -*-


block_cipher = None


a = Analysis(
    ['running_example.py'],
    pathex=[],
    binaries=[],
    datas=[],
    hiddenimports=["msys_shout.*","shout.*","*.mp3"],
    hookspath=[],
    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='running_example',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=True,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
)

python pyinstaller popen
1个回答
0
投票

正如@Grismar 建议使用此规范文件:

# -*- mode: python ; coding: utf-8 -*-


block_cipher = None


a = Analysis(
    ['running_example.py'],
    pathex=[],
    binaries=[],
    datas=[ ('msys_shout.exe', '.'), ('*.mp3','.') ],
    hiddenimports=["shout"],
    hookspath=[],
    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='running_example',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=True,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
)

然后运行:

python -m PyInstaller running_example.spec
解决了问题。

谢谢 Grismar.

总结一下:当导入 .py 脚本时使用 hidden_import,对于其他情况,如 txt 文件、mp3 文件、exe 文件,其路径在 python 脚本中引用,使用 spec 文件中的数据。

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