标签归档:py2exe

如何将Python的.py转换为.exe?

问题:如何将Python的.py转换为.exe?

我试图将一个相当简单的Python程序转换为可执行文件,但是找不到我想要的东西,所以我有几个问题(我正在运行Python 3.6):

到目前为止,我发现的方法如下

  1. 下载旧版本的Python并使用 pyinstaller/py2exe
  2. 在Python 3.6中设置一个虚拟环境,这将允许我执行1。
  3. 下载Python到C ++转换器并使用它。

这是我尝试过的/遇到的问题。

  • 我在安装pyinstaller所需的下载之前安装了它(pypi-something),所以它无法正常工作。下载必备文件后,pyinstaller仍然无法识别它。
  • 如果要在Python 2.7中设置virtualenv,我是否真的需要安装Python 2.7?
  • 同样,我看到的唯一的python至C ++转换器只能在Python 3.5之前工作-尝试这样做是否需要下载并使用此版本?

I’m trying to convert a fairly simple Python program to an executable and couldn’t find what I was looking for, so I have a few questions (I’m running Python 3.6):

The methods of doing this that I have found so far are as follows

  1. downloading an old version of Python and using pyinstaller/py2exe
  2. setting up a virtual environment in Python 3.6 that will allow me to do 1.
  3. downloading a Python to C++ converter and using that.

Here is what I’ve tried/what problems I’ve run into.

  • I installed pyinstaller before the required download before it (pypi-something) so it did not work. After downloading the prerequisite file, pyinstaller still does not recognize it.
  • If I’m setting up a virtualenv in Python 2.7, do I actually need to have Python 2.7 installed?
  • similarly, the only python to C++ converters I see work only up until Python 3.5 – do I need to download and use this version if attempting this?

回答 0

在Python 3.6中将.py转换为.exe的步骤

  1. 安装Python 3.6
  2. 安装cx_Freeze,(打开命令提示符并输入pip install cx_Freeze
  3. 安装idna,(打开命令提示符并输入pip install idna
  4. 编写一个.py名为的程序myfirstprog.py
  5. setup.py在脚本的当前目录中创建一个新的python文件。
  6. setup.py文件中,复制下面的代码并保存。
  7. 按住Shift键并在同一目录上单击鼠标右键,因此您可以打开命令提示符窗口。
  8. 在提示中,键入 python setup.py build
  9. 如果您的脚本没有错误,那么创建应用程序将没有问题。
  10. 检查新创建的文件夹build。它有另一个文件夹。在该文件夹中,您可以找到您的应用程序。运行。让自己开心。

请参阅我的博客中的原始脚本。

setup.py:

from cx_Freeze import setup, Executable

base = None    

executables = [Executable("myfirstprog.py", base=base)]

packages = ["idna"]
options = {
    'build_exe': {    
        'packages':packages,
    },    
}

setup(
    name = "<any name>",
    options = options,
    version = "<any number>",
    description = '<any description>',
    executables = executables
)

编辑:

  • 确保不要myfirstprog.py步骤4中.py创建的扩展名放在文件名中;
  • 你应该包括每import版包您.pypackages列表(例如:packages = ["idna", "os","sys"]
  • any name, any number, any descriptionsetup.py文件不应保持不变,就应该相应地改变它(例如:name = "<first_ever>", version = "0.11", description = ''
  • import你开始之前,编辑软件包必须安装第8步

Steps to convert .py to .exe in Python 3.6

  1. Install Python 3.6.
  2. Install cx_Freeze, (open your command prompt and type pip install cx_Freeze.
  3. Install idna, (open your command prompt and type pip install idna.
  4. Write a .py program named myfirstprog.py.
  5. Create a new python file named setup.py on the current directory of your script.
  6. In the setup.py file, copy the code below and save it.
  7. With shift pressed right click on the same directory, so you are able to open a command prompt window.
  8. In the prompt, type python setup.py build
  9. If your script is error free, then there will be no problem on creating application.
  10. Check the newly created folder build. It has another folder in it. Within that folder you can find your application. Run it. Make yourself happy.

See the original script in my blog.

setup.py:

from cx_Freeze import setup, Executable

base = None    

executables = [Executable("myfirstprog.py", base=base)]

packages = ["idna"]
options = {
    'build_exe': {    
        'packages':packages,
    },    
}

setup(
    name = "<any name>",
    options = options,
    version = "<any number>",
    description = '<any description>',
    executables = executables
)

EDIT:

  • be sure that instead of myfirstprog.py you should put your .pyextension file name as created in step 4;
  • you should include each imported package in your .py into packages list (ex: packages = ["idna", "os","sys"])
  • any name, any number, any description in setup.py file should not remain the same, you should change it accordingly (ex:name = "<first_ever>", version = "0.11", description = '' )
  • the imported packages must be installed before you start step 8.

回答 1

PyInstaller支持Python 3.6。

在您的Python文件夹中打开一个cmd窗口(打开命令窗口并使用cd或按住shift键,在Windows资源管理器中右键单击它,然后选择“在此处打开命令窗口”)。然后输入

pip install pyinstaller

就是这样。

使用它的最简单方法是在命令提示符下输入

pyinstaller file_name.py

有关如何使用它的更多详细信息,请查看此问题

Python 3.6 is supported by PyInstaller.

Open a cmd window in your Python folder (open a command window and use cd or while holding shift, right click it on Windows Explorer and choose ‘Open command window here’). Then just enter

pip install pyinstaller

And that’s it.

The simplest way to use it is by entering on your command prompt

pyinstaller file_name.py

For more details on how to use it, take a look at this question.


回答 2

GitHub上有一个名为auto-py-to-exe的开源项目。实际上,它也仅在内部使用PyInstaller,但由于它具有控制PyInstaller的简单GUI,因此它可能是一个舒适的选择。与其他解决方案相比,它还可以输出独立文件。他们还提供了视频,展示了如何进行设置。

界面:

输出:

There is an open source project called auto-py-to-exe on GitHub. Actually it also just uses PyInstaller internally but since it is has a simple GUI that controls PyInstaller it may be a comfortable alternative. It can also output a standalone file in contrast to other solutions. They also provide a video showing how to set it up.

GUI:

Output:


回答 3

我无法告诉您什么是最好的,但是我过去成功使用的工具是cx_Freeze。他们最近(在17年1月7日)更新到了5.0.1版,它支持Python 3.6。

这是Pypi https://pypi.python.org/pypi/cx_Freeze

该文档显示,有多种方法可以完成此操作,具体取决于您的需求。 http://cx-freeze.readthedocs.io/en/latest/overview.html

我还没有尝试过,所以我将指向一个帖子,其中讨论了执行此操作的简单方法。有些事情可能会或可能不会改变。

如何使用cx_freeze?

I can’t tell you what’s best, but a tool I have used with success in the past was cx_Freeze. They recently updated (on Jan. 7, ’17) to version 5.0.1 and it supports Python 3.6.

Here’s the pypi https://pypi.python.org/pypi/cx_Freeze

The documentation shows that there is more than one way to do it, depending on your needs. http://cx-freeze.readthedocs.io/en/latest/overview.html

I have not tried it out yet, so I’m going to point to a post where the simple way of doing it was discussed. Some things may or may not have changed though.

How do I use cx_freeze?


回答 4

我一直在我的软件包PySimpleGUI中使用Nuitka和PyInstaller。

努伊特卡 存在使tkinter与Nuikta进行编译的问题。一个项目贡献者开发了一个脚本来解决该问题。

如果您不使用tkinter,则可能对您“有效”。如果您使用的是tkinter,请这样说,我将尝试发布脚本和说明。

PyInstaller 我正在运行3.6,PyInstaller运行良好!我用来创建exe文件的命令是:

pyinstaller -wF myfile.py

-wF将创建一个EXE文件。因为我的所有程序都具有GUI,并且我不想显示命令窗口,所以-w选项将隐藏命令窗口。

这几乎就像运行用Python编写的Winforms程序一样

[2019年7月20日更新]

有使用PyInstaller的基于PySimpleGUI GUI的解决方案。它使用PySimpleGUI。它称为pysimplegui-exemaker,可以进行pip安装。

pip install PySimpleGUI-exemaker

要在安装后运行它:

python -m pysimplegui-exemaker.pysimplegui-exemaker

I’ve been using Nuitka and PyInstaller with my package, PySimpleGUI.

Nuitka There were issues getting tkinter to compile with Nuikta. One of the project contributors developed a script that fixed the problem.

If you’re not using tkinter it may “just work” for you. If you are using tkinter say so and I’ll try to get the script and instructions published.

PyInstaller I’m running 3.6 and PyInstaller is working great! The command I use to create my exe file is:

pyinstaller -wF myfile.py

The -wF will create a single EXE file. Because all of my programs have a GUI and I do not want to command window to show, the -w option will hide the command window.

This is as close to getting what looks like a Winforms program to run that was written in Python.

[Update 20-Jul-2019]

There is PySimpleGUI GUI based solution that uses PyInstaller. It uses PySimpleGUI. It’s called pysimplegui-exemaker and can be pip installed.

pip install PySimpleGUI-exemaker

To run it after installing:

python -m pysimplegui-exemaker.pysimplegui-exemaker


回答 5

现在,您可以使用PyInstaller进行转换。我甚至使用Python 3。

脚步:

  1. 启动电脑
  2. 打开命令提示符
  3. 输入命令 pip install pyinstaller
  4. 安装后,使用命令“ cd”转到工作目录。
  5. 运行命令 pyinstall <filename>

Now you can convert it by using PyInstaller. It works with even Python 3.

Steps:

  1. Fire up your PC
  2. Open command prompt
  3. Enter command pip install pyinstaller
  4. When it is installed, use the command ‘cd’ to go to the working directory.
  5. Run command pyinstall <filename>

IndexError:使用py2exe时元组索引超出范围

问题:IndexError:使用py2exe时元组索引超出范围

我目前正在尝试使用py2exe创建可执行文件。我使用Python 3.6。我正在使用的脚本可以导入openpyxlpptx在使用Pycharm或使用命令窗口运行脚本时运行良好。

输出产生错误:

IndexError: tuple index out of range

在下面可以找到cmd输出:

C:\Python36>python setup.py py2exe
running py2exe
Traceback (most recent call last):
  File "setup.py", line 4, in <module>
    setup(console=['Storybookmaker.py'])
  File "C:\Python36\lib\distutils\core.py", line 148, in setup
    dist.run_commands()
  File "C:\Python36\lib\distutils\dist.py", line 955, in run_commands
    self.run_command(cmd)
  File "C:\Python36\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "C:\Python36\lib\site-packages\py2exe\distutils_buildexe.py", line 188, in run
    self._run()
  File "C:\Python36\lib\site-packages\py2exe\distutils_buildexe.py", line 267, in _run
    builder.analyze()
  File "C:\Python36\lib\site-packages\py2exe\runtime.py", line 160, in analyze
    self.mf.import_hook(modname)
  File "C:\Python36\lib\site-packages\py2exe\mf3.py", line 120, in import_hook
    module = self._gcd_import(name)
  File "C:\Python36\lib\site-packages\py2exe\mf3.py", line 274, in _gcd_import
    return self._find_and_load(name)
  File "C:\Python36\lib\site-packages\py2exe\mf3.py", line 357, in _find_and_load
    self._scan_code(module.__code__, module)
  File "C:\Python36\lib\site-packages\py2exe\mf3.py", line 388, in _scan_code
    for what, args in self._scan_opcodes(code):
  File "C:\Python36\lib\site-packages\py2exe\mf3.py", line 417, in _scan_opcodes
    yield "store", (names[oparg],)
IndexError: tuple index out of range

C:\Python36>

是什么原因造成的IndexError

编辑:这是setup.py文件:

from distutils.core import setup
import py2exe

setup(console=['Storybookmaker.py'])

I’m currently trying to make an executable using py2exe. I use Python 3.6. The script I’m using imports openpyxl and pptx and runs fine when I use Pycharm or run the script using the command window.

The output produces the error:

IndexError: tuple index out of range

Below you can find the cmd output:

C:\Python36>python setup.py py2exe
running py2exe
Traceback (most recent call last):
  File "setup.py", line 4, in <module>
    setup(console=['Storybookmaker.py'])
  File "C:\Python36\lib\distutils\core.py", line 148, in setup
    dist.run_commands()
  File "C:\Python36\lib\distutils\dist.py", line 955, in run_commands
    self.run_command(cmd)
  File "C:\Python36\lib\distutils\dist.py", line 974, in run_command
    cmd_obj.run()
  File "C:\Python36\lib\site-packages\py2exe\distutils_buildexe.py", line 188, in run
    self._run()
  File "C:\Python36\lib\site-packages\py2exe\distutils_buildexe.py", line 267, in _run
    builder.analyze()
  File "C:\Python36\lib\site-packages\py2exe\runtime.py", line 160, in analyze
    self.mf.import_hook(modname)
  File "C:\Python36\lib\site-packages\py2exe\mf3.py", line 120, in import_hook
    module = self._gcd_import(name)
  File "C:\Python36\lib\site-packages\py2exe\mf3.py", line 274, in _gcd_import
    return self._find_and_load(name)
  File "C:\Python36\lib\site-packages\py2exe\mf3.py", line 357, in _find_and_load
    self._scan_code(module.__code__, module)
  File "C:\Python36\lib\site-packages\py2exe\mf3.py", line 388, in _scan_code
    for what, args in self._scan_opcodes(code):
  File "C:\Python36\lib\site-packages\py2exe\mf3.py", line 417, in _scan_opcodes
    yield "store", (names[oparg],)
IndexError: tuple index out of range

C:\Python36>

What causes the IndexError?

Edit: here is the setup.py file:

from distutils.core import setup
import py2exe

setup(console=['Storybookmaker.py'])

回答 0

Python 3.6 完全重新设计了CPython的字节码(根本不再是“字节”代码,它是字码,其中所有操作码都是2字节宽而不是1-3)。

您看到的失败发生在py2exe操作码解析代码中,鉴于py2exe仅声明支持3.3和3.4的最新发布版本,该代码可能不了解或不支持新的字码操作码。他们甚至在py2exe上次更新时都没有想到过。字节码通常在各个版本之间以较小的方式变化,甚至可以破坏Python 3.5(明确要求仅支持3.3和3.4),但是3.6确保100%失败。

更新:至此(2019年11月)距上次py2exe发布已经超过五年了,到2020年初(当Python 2支持完全失效时),它将无法在任何受支持的Python版本上运行(3.4已经淘汰)的支持)。我认为可以肯定地说该项目被放弃了。查找其他选项,例如cx_FreezePyInstaller

Python 3.6 completely redesigned the bytecode for CPython (it’s not a “byte” code at all anymore, it’s a wordcode, where all opcodes are two bytes wide instead of 1-3).

The failure you’re seeing occurs in py2exe opcode parsing code, which, given the most recent posted version of py2exe only claims support for 3.3 and 3.4, could not possibly have knowledge of, or support for, the new wordcode opcodes; they hadn’t even been conceived of at the time py2exe was last updated. The bytecode often changes in small ways from version to version that could break even Python 3.5 (given only 3.3 and 3.4 support is claimed explicitly), but 3.6 is 100% guaranteed to fail.

Update: At this point (November 2019), it’s been over five years since the last py2exe release, and by the beginning of 2020 (when Python 2 support lapses completely), it will not run on any supported version of Python (3.4 is already out of support). I think it’s safe to say the project is abandoned; find other options, e.g. cx_Freeze or PyInstaller.


回答 1

我使用的解决方案是使用PyInstaller作为替代方案,因为Py2Exe在python 3.4处停止了开发,并且不适用于较新的版本。

C:/>pip install pyinstaller
C:/>pyinstaller yourprogram.py

这将创建一个名为dist的子目录,并将yourprogram.exe包含在名为yourprogram的文件夹中。

使用-F将所有生成的文件放在一个可执行文件中。

C:/>pyinstaller -F yourprogram

如果要删除GUI的控制台显示,可以使用-w进行。

C:/>pyinstaller -w yourprogram.py

全部放在一起。

C:/>pyinstaller -w -F yourprogram.py

在此处阅读有关PyInstaller的更多信息

Python版本3.7.3。

The solution I used was to use PyInstaller as an alternative because Py2Exe stopped development at python 3.4 and will not work with newer versions.

C:/>pip install pyinstaller
C:/>pyinstaller yourprogram.py

This will create a subdirectory called dist with the yourprogram.exe contained in a folder called yourprogram.

Use -F to place all generated files in one executable file.

C:/>pyinstaller -F yourprogram

Use can use -w to if you want to remove console display for GUI’s.

C:/>pyinstaller -w yourprogram.py

Putting it all togerther.

C:/>pyinstaller -w -F yourprogram.py

Read more about PyInstaller here.

Python version 3.7.3.


回答 2

我遇到了同样的问题,因为解决方法是使用cx_freeze。我的应用程序基于wxPython,Windows 10,python 3.6,cx_freeze 5.5.1

这是我使用的安装文件,在dist文件夹中有msi文件。

#setup.py
import sys, os
from cx_Freeze import setup, Executable

__version__ = "1.1.0"

include_files = ['logging.ini', 'config.ini', 'running.png']
excludes = ["tkinter"]
packages = ["os", "idna", "requests","json","base64","pyodbc"]

setup(
    name = "appname",
    description='App Description',
    version=__version__,
    options = {"build_exe": {
    'packages': packages,
    'include_files': include_files,
    'excludes': excludes,
    'include_msvcr': True,
}},
executables = [Executable("b2b_conn.py",base="Win32GUI")]
)`

然后 python setup.py bdist_msi

I had same problem, as workaround I used cx_freeze. My app is based on wxPython, windows 10, python 3.6, cx_freeze 5.5.1

This is the setup file that I used and I got msi file on dist folder.

#setup.py
import sys, os
from cx_Freeze import setup, Executable

__version__ = "1.1.0"

include_files = ['logging.ini', 'config.ini', 'running.png']
excludes = ["tkinter"]
packages = ["os", "idna", "requests","json","base64","pyodbc"]

setup(
    name = "appname",
    description='App Description',
    version=__version__,
    options = {"build_exe": {
    'packages': packages,
    'include_files': include_files,
    'excludes': excludes,
    'include_msvcr': True,
}},
executables = [Executable("b2b_conn.py",base="Win32GUI")]
)`

then python setup.py bdist_msi


回答 3

我在https://github.com/albertosottile/py2exe上使用py2exe的分叉实现了Python 3.6程序的成功。

I’ve had success with a Python 3.6 program using the fork of py2exe at https://github.com/albertosottile/py2exe.


回答 4

我通过安装Python 3.4.3尝试了一种解决方法:

C:\socket> c:\Python34\python.exe setup.py py2exe

1)输入您的脚本文件夹

2)停用您拥有的任何防病毒软件(奇怪的事情,由另一个SO问题xD知道)

3)通过他的绝对路径调用python 3.4.3解释器,在我的情况下,我已经安装在:

C:\Python34

4)执行命令

C:\Python34\python.exe setup.py py2exe

I tried a workaround, by installing Python 3.4.3:

C:\socket> c:\Python34\python.exe setup.py py2exe

1) enter in your script folder

2) deactivate any antivirus that you have (weird thing, know by another SO question xD)

3) call the python 3.4.3 interpreter by his absolute path, in my case, i’ve installed in:

C:\Python34

4) execute the command

C:\Python34\python.exe setup.py py2exe

py2exe-生成单个可执行文件

问题:py2exe-生成单个可执行文件

我以为我听说py2exe可以做到这一点,但我从来没有想过。有人成功做到了吗?我可以看到您的setup.py文件以及使用的哪些命令行选项吗?

基本上,我正在考虑给它提供一个可执行文件,该文件可执行将自身解压缩到/ temp并运行的操作。

I thought I heard that py2exe was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?

Basically I’m thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.


回答 0

PyInstaller将创建一个没有依赖关系的.exe文件;使用该--onefile选项。它通过将所有需要的共享库打包到可执行文件中,并在运行之前解压缩它们来完成此操作,正如您所描述的那样(编辑:py2exe也具有此功能,请参见minty的答案

我使用的是svn的PyInstaller版本,因为最新版本(1.3)有点过时了。对于依赖于PyQt,PyQwt,numpy,scipy等应用程序的应用程序来说,它的运行情况非常好。

PyInstaller will create a single .exe file with no dependencies; use the --onefile option. It does this by packing all the needed shared libs into the executable, and unpacking them before it runs, just as you describe (EDIT: py2exe also has this feature, see minty’s answer)

I use the version of PyInstaller from svn, since the latest release (1.3) is somewhat outdated. It’s been working really well for an app which depends on PyQt, PyQwt, numpy, scipy and a few more.


回答 1

使用py2exe进行此操作的方法是在setup.py文件中使用bundle_files选项。对于单个文件,您将需要设置bundle_files为1,compressed为True,并将zipfile选项设置为None。这样,它会创建一个压缩文件以便于分发。

这是直接从py2exe网站引用的bundle_file选项的更完整说明*

使用“ bundle_files”和“ zipfile”

创建单文件可执行文件的一种更简单(更好)的方法是将bundle_files设置为1或2,并将zipfile设置为None。这种方法不需要将文件提取到一个临时位置,从而可以更快地启动程序。

bundle_files的有效值为:

  • 3(默认)不捆绑
  • 2捆绑除Python解释器以外的所有内容
  • 1捆绑一切,包括Python解释器

如果zipfile设置为None,则文件将捆绑在可执行文件中,而不是在library.zip中。

这是一个示例setup.py:

from distutils.core import setup
import py2exe, sys, os

sys.argv.append('py2exe')

setup(
    options = {'py2exe': {'bundle_files': 1, 'compressed': True}},
    windows = [{'script': "single.py"}],
    zipfile = None,
)

The way to do this using py2exe is to use the bundle_files option in your setup.py file. For a single file you will want to set bundle_files to 1, compressed to True, and set the zipfile option to None. That way it creates one compressed file for easy distribution.

Here is a more complete description of the bundle_file option quoted directly from the py2exe site*

Using “bundle_files” and “zipfile”

An easier (and better) way to create single-file executables is to set bundle_files to 1 or 2, and to set zipfile to None. This approach does not require extracting files to a temporary location, which provides much faster program startup.

Valid values for bundle_files are:

  • 3 (default) don’t bundle
  • 2 bundle everything but the Python interpreter
  • 1 bundle everything, including the Python interpreter

If zipfile is set to None, the files will be bundle within the executable instead of library.zip.

Here is a sample setup.py:

from distutils.core import setup
import py2exe, sys, os

sys.argv.append('py2exe')

setup(
    options = {'py2exe': {'bundle_files': 1, 'compressed': True}},
    windows = [{'script': "single.py"}],
    zipfile = None,
)

回答 2

就像其他海报提到的那样,py2exe将生成一个可执行文件和一些要加载的库。您还可以将一些数据添加到程序中。

下一步是使用安装程序,将所有这些程序打包到一个易于使用的可安装/不可安装程序中。

我使用InnoSetup(http://www.jrsoftware.org/isinfo.php)已经有好几年了,并且用于商业程序,所以我衷心推荐它。

As the other poster mention, py2exe, will generate an executable + some libraries to load. You can also have some data to add to your program.

Next step is to use an installer, to package all this into one easy-to-use installable/unistallable program.

I have used InnoSetup ( http://www.jrsoftware.org/isinfo.php ) with delight for several years and for commercial programs, so I heartily recommend it.


回答 3

我已经能够将所有资源嵌入到exe中来创建一个exe文件。我在Windows上构建。这样就可以解释我正在使用的os.system调用。

首先,我尝试将所有图像转换为位垫,然后将所有数据文件转换为文本字符串。但这导致最终exe变得非常大。

谷歌搜索一周后,我想出了如何更改py2exe脚本以满足我的需求。

这是我提交的有关sourceforge的补丁程序链接,请发表评论,以便我们将其包含在下一个发行版中。

http://sourceforge.net/tracker/index.php?func=detail&aid=3334760&group_id=15583&atid=315583

这使所做的所有更改无效,我只是在设置行中添加了一个新选项。这是我的setup.py。

我将尽我所能评论。请知道我的setup.py很复杂,因为我要按文件名访问图像。所以我必须存储一个列表来跟踪它们。

这是我试图制作的“想要”屏幕保护程序。

我使用exec在运行时生成设置,这样更容易剪切和粘贴。

exec "setup(console=[{'script': 'launcher.py', 'icon_resources': [(0, 'ICON.ico')],\
      'file_resources': [%s], 'other_resources': [(u'INDEX', 1, resource_string[:-1])]}],\
      options={'py2exe': py2exe_options},\
      zipfile = None )" % (bitmap_string[:-1])

分解

脚本= PY脚本,我想转向一个EXE

icon_resources = exe的图标

file_resources =我要嵌入exe的文件

other_resources =要嵌入到exe中的字符串,在这种情况下为文件列表。

options = py2exe用于将所有内容创建到一个exe文件中的选项

bitmap_strings =要包含的文件列表

请注意,只有按照上述链接中所述编辑py2exe.py文件后,file_resources才是有效选项。

第一次尝试在此站点上发布代码,如果我弄错了,请不要解雇我。

from distutils.core import setup
import py2exe #@UnusedImport
import os

#delete the old build drive
os.system("rmdir /s /q dist")

#setup my option for single file output
py2exe_options = dict( ascii=True,  # Exclude encodings
                       excludes=['_ssl',  # Exclude _ssl
                                 'pyreadline', 'difflib', 'doctest', 'locale',
                                 'optparse', 'pickle', 'calendar', 'pbd', 'unittest', 'inspect'],  # Exclude standard library
                       dll_excludes=['msvcr71.dll', 'w9xpopen.exe',
                                     'API-MS-Win-Core-LocalRegistry-L1-1-0.dll',
                                     'API-MS-Win-Core-ProcessThreads-L1-1-0.dll',
                                     'API-MS-Win-Security-Base-L1-1-0.dll',
                                     'KERNELBASE.dll',
                                     'POWRPROF.dll',
                                     ],
                       #compressed=None,  # Compress library.zip
                       bundle_files = 1,
                       optimize = 2                        
                       )

#storage for the images
bitmap_string = '' 
resource_string = ''
index = 0

print "compile image list"                          

for image_name in os.listdir('images/'):
    if image_name.endswith('.jpg'):
        bitmap_string += "( " + str(index+1) + "," + "'" + 'images/' + image_name + "'),"
        resource_string += image_name + " "
        index += 1

print "Starting build\n"

exec "setup(console=[{'script': 'launcher.py', 'icon_resources': [(0, 'ICON.ico')],\
      'file_resources': [%s], 'other_resources': [(u'INDEX', 1, resource_string[:-1])]}],\
      options={'py2exe': py2exe_options},\
      zipfile = None )" % (bitmap_string[:-1])

print "Removing Trash"
os.system("rmdir /s /q build")
os.system("del /q *.pyc")
print "Build Complete"

好的,这就是setup.py了,现在魔术需要访问图像。我在开发此应用程序时没有考虑到py2exe,后来又添加了它。因此您会看到两种情况的访问权限。如果找不到图像文件夹,它将尝试从exe资源中提取图像。代码将对此进行解释。这是我的Sprite类的一部分,它使用Directx。但是您可以使用所需的任何api或仅访问原始数据。没关系

def init(self):
    frame = self.env.frame
    use_resource_builtin = True
    if os.path.isdir(SPRITES_FOLDER):
        use_resource_builtin = False
    else:
        image_list = LoadResource(0, u'INDEX', 1).split(' ')

    for (model, file) in SPRITES.items():
        texture = POINTER(IDirect3DTexture9)()
        if use_resource_builtin: 
            data = LoadResource(0, win32con.RT_RCDATA, image_list.index(file)+1) #windll.kernel32.FindResourceW(hmod,typersc,idrsc)               
            d3dxdll.D3DXCreateTextureFromFileInMemory(frame.device,   #Pointer to an IDirect3DDevice9 interface
                                              data,                #Pointer to the file in memory
                                              len(data),           #Size of the file in memory
                                              byref(texture))      #ppTexture
        else:
            d3dxdll.D3DXCreateTextureFromFileA(frame.device, #@UndefinedVariable
                                               SPRITES_FOLDER + file,
                                               byref(texture))            
        self.model_sprites[model] = texture
    #else:
    #    raise Exception("'sprites' folder is not present!")

任何问题都可以随意提出。

I’ve been able to create a single exe file with all resources embeded into the exe. I’m building on windows. so that will explain some of the os.system calls i’m using.

First I tried converting all my images into bitmats and then all my data files into text strings. but this caused the final exe to be very very large.

After googleing for a week i figured out how to alter py2exe script to meet my needs.

here is the patch link on sourceforge i submitted, please post comments so we can get it included in the next distribution.

http://sourceforge.net/tracker/index.php?func=detail&aid=3334760&group_id=15583&atid=315583

this explanes all the changes made, i’ve simply added a new option to the setup line. here is my setup.py.

i’ll try to comment it as best I can. Please know that my setup.py is complex do to the fact that i’m access the images by filename. so I must store a list to keep track of them.

this is from a want-to-b screen saver I was trying to make.

I use exec to generate my setup at run time, its easyer to cut and paste like that.

exec "setup(console=[{'script': 'launcher.py', 'icon_resources': [(0, 'ICON.ico')],\
      'file_resources': [%s], 'other_resources': [(u'INDEX', 1, resource_string[:-1])]}],\
      options={'py2exe': py2exe_options},\
      zipfile = None )" % (bitmap_string[:-1])

breakdown

script = py script i want to turn to an exe

icon_resources = the icon for the exe

file_resources = files I want to embed into the exe

other_resources = a string to embed into the exe, in this case a file list.

options = py2exe options for creating everything into one exe file

bitmap_strings = a list of files to include

Please note that file_resources is not a valid option untill you edit your py2exe.py file as described in the link above.

first time i’ve tried to post code on this site, if I get it wrong don’t flame me.

from distutils.core import setup
import py2exe #@UnusedImport
import os

#delete the old build drive
os.system("rmdir /s /q dist")

#setup my option for single file output
py2exe_options = dict( ascii=True,  # Exclude encodings
                       excludes=['_ssl',  # Exclude _ssl
                                 'pyreadline', 'difflib', 'doctest', 'locale',
                                 'optparse', 'pickle', 'calendar', 'pbd', 'unittest', 'inspect'],  # Exclude standard library
                       dll_excludes=['msvcr71.dll', 'w9xpopen.exe',
                                     'API-MS-Win-Core-LocalRegistry-L1-1-0.dll',
                                     'API-MS-Win-Core-ProcessThreads-L1-1-0.dll',
                                     'API-MS-Win-Security-Base-L1-1-0.dll',
                                     'KERNELBASE.dll',
                                     'POWRPROF.dll',
                                     ],
                       #compressed=None,  # Compress library.zip
                       bundle_files = 1,
                       optimize = 2                        
                       )

#storage for the images
bitmap_string = '' 
resource_string = ''
index = 0

print "compile image list"                          

for image_name in os.listdir('images/'):
    if image_name.endswith('.jpg'):
        bitmap_string += "( " + str(index+1) + "," + "'" + 'images/' + image_name + "'),"
        resource_string += image_name + " "
        index += 1

print "Starting build\n"

exec "setup(console=[{'script': 'launcher.py', 'icon_resources': [(0, 'ICON.ico')],\
      'file_resources': [%s], 'other_resources': [(u'INDEX', 1, resource_string[:-1])]}],\
      options={'py2exe': py2exe_options},\
      zipfile = None )" % (bitmap_string[:-1])

print "Removing Trash"
os.system("rmdir /s /q build")
os.system("del /q *.pyc")
print "Build Complete"

ok, thats it for the setup.py now the magic needed access the images. I developed this app without py2exe in mind then added it later. so you’ll see access for both situations. if the image folder can’t be found it tries to pull the images from the exe resources. the code will explain it. this is part of my sprite class and it uses a directx. but you can use any api you want or just access the raw data. doesn’t matter.

def init(self):
    frame = self.env.frame
    use_resource_builtin = True
    if os.path.isdir(SPRITES_FOLDER):
        use_resource_builtin = False
    else:
        image_list = LoadResource(0, u'INDEX', 1).split(' ')

    for (model, file) in SPRITES.items():
        texture = POINTER(IDirect3DTexture9)()
        if use_resource_builtin: 
            data = LoadResource(0, win32con.RT_RCDATA, image_list.index(file)+1) #windll.kernel32.FindResourceW(hmod,typersc,idrsc)               
            d3dxdll.D3DXCreateTextureFromFileInMemory(frame.device,   #Pointer to an IDirect3DDevice9 interface
                                              data,                #Pointer to the file in memory
                                              len(data),           #Size of the file in memory
                                              byref(texture))      #ppTexture
        else:
            d3dxdll.D3DXCreateTextureFromFileA(frame.device, #@UndefinedVariable
                                               SPRITES_FOLDER + file,
                                               byref(texture))            
        self.model_sprites[model] = texture
    #else:
    #    raise Exception("'sprites' folder is not present!")

Any questions fell free to ask.


回答 4

如前所述,您应该创建一个安装程序。即使也可以通过将bundle_files选项设置为1并将zipfile关键字参数设置为None来让py2exe将所有内容捆绑到一个可执行文件中,但我不建议PyGTK应用程序使用此方法。

这是因为GTK +试图从其加载目录中加载其数据文件(本地,主题等)。因此,您必须确保可执行文件的目录还包含GTK +使用的库以及GTK +安装中的目录lib,share等。否则,您将在未在全系统范围内安装GTK +的计算机上运行应用程序时遇到问题。

有关更多详细信息,请阅读我的PyGTK应用程序py2exe指南。它还说明了如何捆绑除GTK +之外的所有内容。

You should create an installer, as mentioned before. Even though it is also possible to let py2exe bundle everything into a single executable, by setting bundle_files option to 1 and the zipfile keyword argument to None, I don’t recommend this for PyGTK applications.

That’s because of GTK+ tries to load its data files (locals, themes, etc.) from the directory it was loaded from. So you have to make sure that the directory of your executable contains also the libraries used by GTK+ and the directories lib, share and etc from your installation of GTK+. Otherwise you will get problems running your application on a machine where GTK+ is not installed system-wide.

For more details read my guide to py2exe for PyGTK applications. It also explains how to bundle everything, but GTK+.


回答 5

我被告知bbfreeze将创建一个文件.EXE,并且比py2exe更新。

I’m told bbfreeze will create a single file .EXE, and is newer than py2exe.


回答 6

尝试 c_x Frozen 它可以创建一个很好的独立版本

try c_x freeze it can create a good standalone


回答 7

我最近使用py2exe创建了一个用于后期审阅的可执行文件,用于将审阅发送到ReviewBoard。

这是我使用的setup.py

from distutils.core import setup
import py2exe

setup(console=['post-review'])

它创建了一个目录,其中包含exe文件和所需的库。我认为无法使用py2exe来获取单个.exe文件。如果需要,首先需要使用py2exe,然后使用某种形式的安装程序来制作最终的可执行文件。

需要注意的一件事是,您在应用程序中使用的任何egg文件都需要解压缩,否则py2exe不能包含它们。py2exe文档中对此进行了介绍。

I recently used py2exe to create an executable for post-review for sending reviews to ReviewBoard.

This was the setup.py I used

from distutils.core import setup
import py2exe

setup(console=['post-review'])

It created a directory containing the exe file and the libraries needed. I don’t think it is possible to use py2exe to get just a single .exe file. If you need that you will need to first use py2exe and then use some form of installer to make the final executable.

One thing to take care of is that any egg files you use in your application need to be unzipped, otherwise py2exe can’t include them. This is covered in the py2exe docs.


回答 8

不,就您以后只有一个文件的意义而言,它没有给您单个可执行文件-但您有一个目录,其中包含运行程序所需的所有文件,包括exe文件。

我今天才写了这个setup.py。您只需要调用python setup.py py2exe

No, it’s doesn’t give you a single executable in the sense that you only have one file afterwards – but you have a directory which contains everything you need for running your program, including an exe file.

I just wrote this setup.py today. You only need to invoke python setup.py py2exe.


Pyinstaller-将Python程序打包为独立的可执行文件

PyInstaller概述

PyInstaller将Python应用程序及其所有依赖项捆绑到单个包中。用户无需安装Python解释器或任何模块即可运行打包的应用程序

文档: https://pyinstaller.readthedocs.io/
网站: http://www.pyinstaller.org/
代码: https://github.com/pyinstaller/pyinstaller

PyInstaller读取您编写的Python脚本。它分析您的代码以发现您的脚本执行所需的所有其他模块和库。然后,它会收集所有这些文件的副本–包括活动的Python解释器!–并将它们与脚本放在单个文件夹中,或者也可以放在单个可执行文件中

PyInstaller在Windows、MacOSX和GNU/Linux上进行了测试。但是,它不是交叉编译器:要制作Windows应用程序,您需要在Windows中运行PyInstaller;要制作GNU/Linux应用程序,需要在GNU/Linux等环境中运行它。PyInstaller已成功用于AIX、Solaris、FreeBSD和OpenBSD,但作为持续集成测试的一部分,没有针对它们进行测试

主要优势

  • 开箱即用,可与任何Python版本3.6-3.9配合使用
  • 完全多平台,利用操作系统支持加载动态库,确保完全兼容
  • 正确捆绑主要的Python包,如numpy、PyQt5、PySide2、Django、wxPython、matplotlib和其他开箱即用的包
  • 与许多开箱即用的第三方软件包兼容。(使外部包工作所需的所有技巧都已集成。)
  • 完全支持PyQt5、PySide2、wxPython、matplotlib或Django等库,无需手动处理插件或外部数据文件
  • 在OS X上使用代码签名
  • 在Windows上捆绑MS Visual C++DLL

安装

PyInstaller在PyPI上可用。您可以通过pip安装它:

pip install pyinstaller

要求和测试平台

  • 巨蟒:
  • 3.6-3.9
  • tinyaes1.0+(仅当使用字节码加密时)。与其安装天鹅座,pip install pyinstaller[encryption]取而代之的是
  • Windows(32位/64位):
  • PyInstaller应该可以在Windows 7或更新版本上运行,但我们只正式支持Windows 8+
  • 由于以下原因,当不使用虚拟环境时,我们不支持从Windows商店安装Pythonpermission errors那不是很容易修好的
  • GNU/Linux(32位/64位)
  • LDD:用于打印每个程序或共享库所需共享库的控制台应用程序。这通常可以在分发包glibc或libc-bin中找到
  • objdump:显示对象文件信息的控制台应用程序。这通常可以在分发包的binutils中找到
  • objcopy:复制和翻译目标文件的控制台应用程序。这通常也可以在分发包的binutils中找到
  • Mac OS X(64位):
  • Mac OS X 10.13(High Sierra)或更高版本

用法

基本用法非常简单,只需针对您的主脚本运行即可:

pyinstaller /path/to/yourscript.py

有关更多详细信息,请参阅manual

未经测试的平台

已经贡献了以下平台,欢迎对这些平台进行任何反馈或增强

  • FreeBSD
  • LDD
  • Solaris
  • LDD
  • 对象转储
  • AIX
  • AIX 6.1或更高版本。PyInstaller不能使用静态链接的Python库
  • LDD
  • PowerPC GNU/Linux(Debian)

在使用任何贡献的平台之前,您需要构建PyInstaller引导加载器,因为我们不提供二进制包。下载PyInstaller源代码,并构建引导加载器:

cd bootloader
python ./waf all

然后安装PyInstaller:

python setup.py install

或者直接从源代码(pyinstaller.py)使用它

支持

看见http://www.pyinstaller.org/support.html有关如何获得帮助以及商业支持的信息

此版本中的更改

您可以在以下位置找到此版本中更改的详细列表Changelog手册的一节