个性化阅读
专注于IT技术分析

如何在Windows中使用pyinstaller从Python脚本创建可执行文件(.exe)

本文概述

你是创建脚本以简化生活的开发人员之一吗?巧合的是, 你喜欢Python吗?你有Windows吗?你需要知道有一种简单的方法可以执行脚本, 甚至在Windows中使用它们创建少量的控制台应用程序, 而不是通过控制台在控制台中手动执行脚本来重复工作。多亏了pyinstaller, 我们正在谈论使用python脚本创建.exe(是的, 应用程序文件)文件。 PyInstaller是在Windows, Linux, Mac OS X, FreeBSD, Solaris和AIX下将Python程序冻结(打包)成独立的可执行文件的程序。

在本文中, 你将学习如何在Windows中使用Pyinstaller从Python控制台脚本轻松创建可执行文件。

要求

要创建我们的可执行文件, 我们将使用pyinstaller软件包。要下载pyinstaller, 请在命令提示符(cmd.exe)中执行以下命令:

pip install pyinstaller

安装将继续进行, 你的环境中将提供可用的pyinstaller:

点安装pyinstaller Windows

你可以在官方网站上阅读有关此软件包的更多信息。要检查pyinstaller是否已正确安装, 你可以检查控制台中它是否作为执行pyinstaller –h的环境变量可用。

实现

使用pyinstaller创建可执行文件非常简单, 可自定义并且非常容易执行。在我们的示例中, 我们将创建以下脚本的可执行文件。脚本的文件名是file-creator.py, 其中包含以下代码(它只是提示用户输入新文件的名称和内容):

def start_setup():
    # raw_input returns the empty string for "enter"
    yes = set(['yes', 'y', 'ye', ''])
    no = set(['no', 'n'])
    prompt = '> '

    print ("Hi, welcome to Text File Creator 2000")
    print ("To get started, give a name to your file (without extension)")

    filename = input(prompt)

    print ("Awesome, now provide the content of the file !)")

    content = input(prompt)

    confirm = input("> Do you want to continue with the creation of " + filename + ".txt ? (Yes/No)").lower()

    if confirm in yes:
        text_file = open(filename + ".txt", "w")
        text_file.write(content)
        text_file.close()
        print ("File succesfully created, come back soon !")
        return True
    elif confirm in no:
        print ("Ok, nothing will happen !")
        return False
    else:
       print ("Please answer yes or no !, the setup will start again")
       # start again
       start_setup()

start_setup()

如你所见, 它是一个简单的控制台Python应用程序。现在创建可执行文件, 使用控制台(cmd.exe)导航到python脚本所在的文件夹(在本例中为Desktop \ pythonScripts):

cd C:\Users\sdkca\Desktop\pythonScripts

现在, 使用以下命令继续执行可执行文件:

pyinstaller file-creator.py

这是创建脚本可执行文件的最简单命令, 因此足以在脚本所在的文件夹中创建可执行文件。请注意, 我们的应用程序仅基于控制台(如果要在清单中包含同一清单和其他依赖项的可执行文件, 则可以将–console参数添加到命令中, 如果将GUI与wxPython之类的库一起使用, 则可以–console参数使用–windowed。)。

最后, 你可以在dist文件夹中测试创建的可执行文件, 该文件夹将在脚本所在的位置创建:

Python控制台可执行文件

提示与建议

  • 你可以在命令(pyinstaller script.py –icon = c:\ path-to \ icon.ico)上添加icon参数(以文件的路径为值)来更改可执行文件的图标。
  • 使用PyInstaller时可能会出现不同的典型问题。要解决应用程序中的问题, 请参阅此处的存储库中的”如果出错, 请自述文件”。

玩得开心 !

赞(0)
未经允许不得转载:srcmini » 如何在Windows中使用pyinstaller从Python脚本创建可执行文件(.exe)

评论 抢沙发

评论前必须登录!