【问题标题】:Using pyinstaller to convert Python3 and Python2 to .exe使用 pyinstaller 将 Python3 和 Python2 转换为 .exe
【发布时间】:2019-11-22 14:08:34
【问题描述】:

我目前正在 Python 3 上编写脚本。

我需要从我的 Python 3 脚本中调用一个已经存在的 Python 2 脚本。

在 Python3 脚本中,我正在使用类似这样的方法:

import subprocess
my_command = 'python script_in_py2.py arg1 arg2'
process = subprocess.Popen(my_command.split(), stdout = subprocess.PIPE)
output, error = process.communicate()

因此,如果我刚刚在终端中写入my_command,变量output 将获得将显示在屏幕上的输出。

虽然我目前在 Ubuntu 中进行开发,但最终我会将其迁移到需要将其转换为 .exe 的 Windows。为此,我以前使用过 pyinstaller。

我知道在没有安装 Python 的 Windows 机器上运行生成的 .exe(纯 Python3 脚本)完全可以。 但是在继续之前我需要知道它是否也会像这样工作。我的直觉是否定的(据我所知,创建这样的过程类似于直接在终端/命令提示符中运行命令),但是我想知道是否有人知道一种方法/解决方法。 (不能在运行脚本的机器上安装 Python2)。

【问题讨论】:

  • 如果您在代码中运行python script,那么您必须在计算机上安装Python2。
  • pyinstaller 不会创建真正的.exe 文件(与C/C++ 一样),但它会创建带有python.exe 的自解压.zip 文件以及您在此.zip 中的脚本。也许最好用 Python2 全部编写,也许 python script 也可以与 pyinstaller 放入 .exe 的 python.exe 一起使用
  • 或更好地重写其他脚本,以便您可以import 他们并从此脚本运行函数 - 而不是使用子进程运行。您还可以使用if __name__ == '__main__': 以两种不同的方式运行它。
  • @furas 感谢您的评论,但是鉴于它不是我需要在 2 中运行的次要脚本,我只是想知道是否可以在不深入研究在 3 中重写整个内容的情况下做到这一点。

标签: python python-3.x python-2.7 pyinstaller


【解决方案1】:

可能的解决方案如下:

  1. 使用 pyinstaller 将您的 python2 脚本(即“script_in_py2.py”)转换为可执行文件,即“script_in_py2.exe”。

    pyinstaller script_in_py2.py

  2. 在您的 python3 脚本中,调用此 python 2 可执行文件,而不是调用 python 2 脚本。

    import subprocess  
    my_command = 'script_in_py2.exe arg1 arg2'  
    process = subprocess.Popen(my_command.split(), stdout = subprocess.PIPE)  
    output, error = process.communicate()  
    
  3. 现在使用 pyinstaller 将您的 python3 脚本转换为可执行文件。

    pyinstaller script_in_py3.py

  4. 将可执行文件“script_in_py2.exe”和“python27.dll”粘贴到“script_in_py3”的dist文件夹中(即与可执行文件“script_in_py3.exe”的位置平行)

  5. 运行“script_in_py3.exe”,您将获得所需的输出。

我已经在我的系统上试用过了,它运行良好。

【讨论】:

    猜你喜欢
    • 2018-03-09
    • 2022-08-05
    • 2021-05-02
    • 2016-08-03
    • 1970-01-01
    • 2017-01-24
    • 2020-12-05
    • 2017-06-03
    • 1970-01-01
    相关资源
    最近更新 更多