【问题标题】:How to run exe file from python script converted to exe如何从转换为exe的python脚本运行exe文件
【发布时间】:2021-06-12 00:03:37
【问题描述】:

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

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

我的问题是当我将两个exe文件合并到一个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] 系统找不到指定的文件:'file1.exe'

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

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

file2 中启动 file1 的命令行是:

  os.system('file1.exe')

我该如何解决这个问题?

【问题讨论】:

  • 显示使用该文件的代码。这看起来像是脚本中路径的问题。检查pyinstaller.readthedocs.io/en/stable/…
  • 您是否有理由不将两个 Python 脚本捆绑到一个 .exe 中?看起来这比捆绑一个然后将它捆绑到另一个(一旦你的路径工作)更有效。
  • @CrazyChucky,是的,因为提到的第二个文件是检查许可证。所以使用这种方法会更容易。
  • 您仍将运行两个完整的 Python 运行时。
  • @buran,嗨,我已经在执行 file1.exe 时提供了类似 file2.exe 的命令。

标签: python pyinstaller


【解决方案1】:

当您执行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()

【讨论】:

  • 非常感谢,这解决了我的问题。关于你的旁注,你能澄清一下为什么 subprocess.run() 更好吗?
  • 我认为是因为它没有启动新环境,而是将其作为子进程启动。
  • os.system 的文档中提到了 - subprocess 模块提供了更强大的工具来生成新进程并检索其结果; 使用该模块优于使用此功能。
【解决方案2】:

从this 帖子和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')。

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 绝对路径不适用于所有计算机,因为不同的用户文件夹会破坏它。
    【解决方案4】:

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

    【讨论】:

    • 他们已经使用 -F 选项合并到一个文件中,但是他们用来尝试访问捆绑的 .exe 的路径不起作用。
    • 不,我的意思是 file1.exe 和 file2.exe。因此,只需在许可证检查后将应用程序中的代码放入一个文件并使用它。它只会留下一个file.exe,不会遇到任何引用问题
    猜你喜欢
    • 2019-12-31
    • 2020-11-23
    • 2021-06-04
    • 2020-03-01
    • 2021-09-25
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多