如何将 运行 exe 文件从 python 脚本转换为 exe

How to run exe file from python script converted to exe

我有两个 EXE 文件,实际上都是 python 脚本,使用 pyinstaller 转换(使用 Auto Py 到 Exe)。

file1.exe : 是应用程序。 file2.exe : 是license app,检查license,如果ok则执行file1,否则退出。

我的问题是,当我将两个 exe 文件合并为 1 个 exe 文件时,file2.exe 找不到 file1.exe,除非我将它复制到同一目录。

pyinstaller 命令:

pyinstaller -y -F --add-data "D:/test/file1.exe";"."  "D:/test/file2.py"

现在我应该有这样的东西:

file2.exe 
      +------- file1.exe

但是每次我 运行 file2.exe 它都会给我这个错误

WinError 2] The system cannot find the file specified: 'file1.exe'

直到我将 file1.exe 复制到同一目录(因为它忽略了我已经将它合并到 pyinstaller 中) 所以文件树看起来像这样:

file1.exe
file2.exe 
      +------- file1.exe

file2 中启动 file1 的命令行是:

  os.system('file1.exe')

我该如何解决?

也许你应该尝试使用绝对路径。

除非您知道 C:\ 中文件的绝对路径,否则您将无法执行此操作,因为不同人的用户帐户名称不同。我强烈建议将它们合并到一个文件中,因为这很可能也会简化调试。我不确定使用 pathlibshutil 之类的搜索目录是否有效,但它可能会找到错误的文件。

当您执行 os.sysetm('file1.exe') 时,它希望在您 运行 您的 file2.exe

当前工作目录中找到它

因此,您需要执行以下操作才能使用 file2.exe 中捆绑的 file1.exe

import sys, os
if getattr(sys, 'frozen', False):
    # we are running in a bundle
    bundle_dir = sys._MEIPASS
else:
    # we are running in a normal Python environment
    bundle_dir = os.path.dirname(os.path.abspath(__file__))

os.system(os.path.join(bundle_dir, 'file1.exe'))

正如我在评论中提到的,请查看 PyInstaller 文档中的 Run-time Information 部分。

作为旁注,与您的问题无关,最好使用 subprocess.run(),而不是 os.system()

根据 this post and this 的回答,我认为您应该将 PyInstaller 命令更改为 pyinstaller -y -F --add-data "D:/test/file1.exe;." "D:/test/file2.py" 而不是 "D:/test/file1.exe";"."

如果它不起作用,请尝试 pyinstaller -y -F --add-data "D:/test/file1.exe;file1.exe" "D:/test/file2.py",如果将 file2.exe 放入 PyInstaller 分发文件夹,启动 file1.exe 的命令将是 os.system('main/file1.exe')