python windows打包


接觸過的工具有pyinstaller,或者py2exe。感覺pyinstaller更簡單易用。

真正將依賴的dll打包稱一個安裝包還需要借助windows打包工具

Inno Setup 或 NSIS

1、pyinstaller

官網:www.pyinstaller.org

兩大步

(1)Install PyInstaller from PyPI:

pip install pyinstaller 

(2)Go to your program’s directory and run:

pyinstaller yourprogram.py

就會在本地生成一個文件夾dist 里面有對應的exe

2、py2exe

官網:http://py2exe.org

需要寫一些腳本

http://py2exe.org/index.cgi/Tutorial

寫的簡單易懂 需要創建一個setup.py 將需要打包的py寫進去,就可以進行打包

-----------------------------------------------------------------

Tutorial

py2exe turns Python programs into packages that can be run on other Windows computers without needing to install Python on those computers. Python is needed on the computer where py2exe itself is run because py2exe is a Python program and it includes parts of Python in the package that is built.

To successfully complete this tutorial you'll need to know the basics of Python (you can get started at python.org's getting started page). You'll also need to know how to run Python programs from the command prompt.

There are a few simple steps needed to use py2exe once you've installed it:

  1. Create/test your program

  2. Create your setup script (setup.py)

  3. Run your setup script

  4. Test your executable

  5. Providing the Microsoft Visual C runtime DLL

  6. Build an installer if applicable

 

 

1. Create/test your program

The biggest step is almost always the first one. The good news is that py2exe typically has little or no impact on this step. The vast majority of things you can do with Python will work with py2exe. Many modules just work seamlessly with py2exe, but some third party modules will require a little extra work. Luckily there is help available at WorkingWithVariousPackagesAndModules.

It's important that you make sure everything is working before you use py2exe. If py2exe fixes a broken program, then that's probably a bug in py2exe that needs to be fixed!

The first example we'll use here is our old friend...

 

切換行號顯示
 1 print "Hello World!" 

hello.py

We need to make sure it's working...

 

C:\Tutorial>python hello.py
Hello World!  C:\Tutorial>

Looks good!

 

 

2. Create your setup script (setup.py)

py2exe extends Distutils with a new "command". If you've installed third party Python modules then there's a good chance you've seen at least one distutils command:

 

C:\Tutorial>python setup.py install

"install" is a Distutils command that installs something (typically a Python module or package). The details Distutils needs to do that installation are contained in setup.py (and sometimes other associated files).

"py2exe" is a new Distutils command that is added when you import py2exe. To use py2exe you need to create a setup.py file to tell Distutils and py2exe what you want to do. Here's a setup.py whose simplicity is appropriate for our sample program...

 

切換行號顯示
from distutils.core import setup import py2exe  setup(console=['hello.py']) 

setup.py

Notice that this is ordinary Python. Let's go through it line by line...

  1. When working with py2exe the only part of Distutils we'll typically need to reference directly is the setup function, so that's all we'll import.
  2. Once Distutils is loaded, we need to load py2exe so that it can add its command.
  3. Whitespace is good!
  4. Call setup and tell it that we want a single console application and the main entry point is "hello.py".

 

 

3. Run your setup script

The next step is to run your setup script. Make sure to give the py2exe command and expect to see lots and lots of output:

 

C:\Tutorial>python setup.py py2exe
running py2exe *** searching for required modules *** *** parsing results *** creating python loader for extension 'zlib' creating python loader for extension 'unicodedata' creating python loader for extension 'bz2' *** finding dlls needed *** *** create binaries *** *** byte compile python files *** byte-compiling C:\Tutorial\build\bdist.win32\winexe\temp\bz2.py to bz2.pyc byte-compiling C:\Tutorial\build\bdist.win32\winexe\temp\unicodedata.py to unicodedata.pyc byte-compiling C:\Tutorial\build\bdist.win32\winexe\temp\zlib.py to zlib.pyc skipping byte-compilation of c:\Python24\lib\StringIO.py to StringIO.pyc  [skipping many lines for brevity]  skipping byte-compilation of c:\Python24\lib\warnings.py to warnings.pyc *** copy extensions *** *** copy dlls *** copying c:\Python24\lib\site-packages\py2exe\run.exe -> C:\Tutorial\dist\hello.exe  *** binary dependencies *** Your executable(s) also depend on these dlls which are not included, you may or may not need to distribute them.  Make sure you have the license if you distribute any of them, and make sure you don't distribute files belonging to the operating system.   ADVAPI32.dll - C:\WINDOWS\system32\ADVAPI32.dll  USER32.dll - C:\WINDOWS\system32\USER32.dll  SHELL32.dll - C:\WINDOWS\system32\SHELL32.dll  KERNEL32.dll - C:\WINDOWS\system32\KERNEL32.dll  C:\Tutorial>

Two directories will be created when you run your setup script, build and dist. The build directory is used as working space while your application is being packaged. It is safe to delete the build directory after your setup script has finished running. The files in the dist directory are the ones needed to run your application.

 

 

4. Test your executable

Now that the package has been created it is ready to test:

 

C:\Tutorial>cd dist
 C:\Tutorial\dist>hello.exe Hello World

Excellent, it works!!!

 

 

5. Providing the Microsoft Visual C runtime DLL

The Python interpreter was compiled using Microsoft Visual C, so your new program needs the Microsoft Visual C runtime DLL to run. If you have installed appropriate versions of Python or Visual Studio, then you will already have this DLL on your computer. If some of your users might not already have this DLL, then they will not be able to run your program. The methods you may use to solve this depend on the version of Python you are using:

 

 

5.1. Python 2.4 or 2.5

If you are using Python 2.4 or 2.5, then the DLL you need is called MSVCR71.dll. This DLL will probably already have been included in your dist directory, in which case you need do nothing more.

However, the copyright on this file is owned by Microsoft, and you need to check whether you have the legal right to redistribute it. If you have a copy of Visual Studio, check the file redist.txt provided within the installation to see whether you have redistribution rights for this DLL. Generally you have the right to redistribute it if you own a license for Microsoft Visual C++, but not if you use the Express Editions.

If you do not have the rights to redistribute MSVCR71.dll, then your users must install it for themselves, using the Microsoft Visual C++ 2005 Redistributable Package (vcredist_x86.exe).

Either you can instruct your users to download and run this themselves, or you could create an installer for your application (see Step 6 below), that includes vcredist_x86.exe (which is itself redistributable by anyone), and then run that as part of your application installation.

 

 

5.2. Python 2.6, 2.7, 3.0, 3.1

For Python 2.6, the DLL you need is called MSVCR90.dll. Py2exe is not able to automatically include this DLL in your dist directory, so you must provide it yourself.

To complicate things, there is more than one version of this DLL in existance, each with the same filename. You need the same version that the Python interpreter was compiled with, which is version 9.0.21022.8. Through the remainder of these instructions, hover your mouse over the dll file (or the vcredist_x86.exe installer executable) to confirm which version you've got. You'll need the vcredist_x86.exe that contains the Microsoft Visual C++ 2008 Redistributable Package published 29-11-2007, so not the VS2008 SP1 one (tested with Python 2.7.1).

As for older versions of Python, you need to check redist.txt within your Visual Studio installation to see whether you have the legal right to redistribute this DLL. If you do have these rights, then you have the option to bundle the C runtime DLL with you application. If you don't have the rights, then you must have your users run the redistributable C runtime installer on their machines.

 

 

5.2.1. Bundling the C runtime DLL

If you do have the rights to redistribute MSVCR90.dll, there should be a copy of it in your Visual Studio install, under VC\redist\x86\Microsoft.VC90.CRT. Since Visual Studio 2008, you can't just copy this DLL file - you also need the manifest file that you'll find there. The redist.txt file states that you must distribute all three dlls and the unmodified manifest file and it is a violation of the license agreement to distribute only one of the dlls without the others (though py2exe only needs MSVCR90.dll.) The pertinent passage from the redist.txt file is as follows:

  • "For your convenience, we have provided the following folders for use when redistributing VC++ runtime files. Subject to the license terms for the software, you may redistribute the folder (unmodified) in the application local folder as a sub-folder with no change to the folder name. You may also redistribute all the files (*.dll and *.manifest) within a folder, listed below the folder for your convenience, as an entire set."

You must make py2exe copy the three dlls and the manifest file into your project's dist directory, in a subdirectory called 'Microsoft.VC90.CRT'. To achieve this, add a data_files option to your project's setup.py:

 

  from glob import glob
 data_files = [("Microsoft.VC90.CRT", glob(r'C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\*.*'))]  setup(  data_files=data_files,  etc  )

With this in place, running py2exe should put the files into your dist directory:

 

  dist
 |  +-Microsoft.VC90.CRT  | |  | +-Microsoft.VC90.CRT.manifest  | +-msvcm90.dll  | +-msvcp90.dll  | +-msvcr90.dll  |  |-etc

Now, simply copying the whole dist directory to your users machines should now allow your application to run, even on machines that don't have their own copy of the C++ runtime.

Note that this method of including the C runtime is used by several Visual C++ applications - if you search your Program Files folder for msvcr90.dll, you may find several applications that have this DLL and the associated manifest bundled alongside their executable like this.

Also note that despite all the above, py2exe will complain that it cannot find MSVCP90.dll. You must edit your setup.py to add the path to the dlls to the sys.path, e.g.

 

    sys.path.append("C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\redist\\x86\\Microsoft.VC90.CRT")

 

 

5.2.1.1 win32ui special case

win32ui needs MFC DLLs to run .exe, see Py2exeAndWin32ui for extra informations

 

 

5.2.2. Running the redistributable C runtime installer

If you don't have rights to redistribute MSVCR90.dll, then your users may install it on their machine by running the Microsoft Visual C++ 2008 Redistributable Package (vcredist_x86.exe). It is important not to use the SP1 version of this installer, which contains the wrong version of MSVCR90.dll.

Either you can instruct your users to download and run this themselves, or you could create an installer for your application (see step 6 below), that includes vcredist_x86.exe (which is itself redistributable by anyone), and then run that as part of your application installation.

The installer puts a copy of the DLLs in the directory C:\WINDOWS\WinSxS (XP), inside subdirectories with mangled names. The manifest file is in the 'Manifests' subdirectory, again this will have a mangled filename. You can still discern the text 'Microsoft.VC90.CRT' and '9.0.21022.8' within the mangled file and directory names, to find the files. It is possible to take a copy of these files and remove the filename mangling, to embed them in your application as described in 5.2.1.

 

 

6. Build an installer if applicable

py2exe is not an installer builder - it merely assembles the files needed to run your Python program. There are plenty of good installer builders out there including some that are open source (e.g., NSIS) and some that are free (e.g., Inno Setup).

 

 

 

 

-----------------------------------------------------------------------------

https://github.com/cycleuser/Kivy-CN/blob/master/13-Kivy-Pack-Windows.md

Title: Kivy Pack Windows Date: 2017-03-01 Category: Kivy Tags: Python,Kivy

Kivy中文編程指南:打包為 Windows 系統可執行文件

英文原文

特別注意

本文檔僅適用於1.9.1以及更新版本的 Kivy。

要打包 Windows 平台的應用程序,只能在 Windows 操作系統下完成。另外一定要注意,本文后續內容中都是在 wheels 安裝的 Kivy 下通過測試的,如果你用其他安裝方法,參考結尾部分吧。

打包出來的程序是 32 位還是 64 位只取決於你打包使用的 Python,而不取決於 Windows 操作系統的版本。

依賴包

  • 最新版本的Kivy (參考安裝指南 Installation on Windows
  • PyInstaller 3.1或者更新的版本 (pip install --upgrade pyinstaller)。

(譯者注:PyInstaller 目前(2017年03月01日)還不支持 Python 3.6 哦~,好多朋友都坑到這里了,所以推薦使用 3.5.2。)

PyInstaller 的基本用法

本節內容是要讓 PyInstaller(3.1或者更新版本)包含 Kivy 的 Hook(鈎子, Windows 消息處理機制的一個平台)。要覆蓋默認的 Hook ,下面的樣例代碼需要稍微修改一下。參考 覆蓋默認 Hook

打包一個簡單的 APP

這個例子里面,咱們要把樣例中的 touchtracer 這個項目進行打包,並且添加一個自定義圖標。這里 Kivy 的樣例目錄要注意,如果是用 wheels 安裝的,在 python\\share\\kivy-examples 這個位置,如果從 github 上面下載的,就在 kivy\\examples 這個位置。為了避免混亂,這里就用 examples-path 來指代這個目錄的完整路徑。然后 touchtracer 這個樣例在 examples-path\\demo\\touchtracer 這個文件夾里,代碼文件是 main.py

###1 確保 Python 打開命令行確保 Python 包含在環境變量內,也就是說,輸入 python 會出現解釋器提示符。(譯者注:cmd 或者 powershell 都可以,更推薦用后者,語法和 Bash 比較相似。)

###2 創建文件夾 在要打包 APP 的位置創建一個文件夾。比如咱們這次就創建一個名字為 TouchApp 的文件夾,然后用類似 cd TouchApp 這樣的命令進入到這個新建目錄內。之后輸入:

python -m PyInstaller --name touchtracer examples-path\demo\touchtracer\main.py

還可以增加一個 icon.ico 文件到這個應用目錄,這樣就可以讓程序有自己的圖標了。如果沒有自己的 .ico 圖標文件,可以把你的 icon.png 文件轉換成 ico,用這個 ConvertICO 在線的應用就可以了。保存 icon.ico 到 touchtracer 這個目錄里面,然后輸入:

python -m PyInstaller --name touchtracer --icon examples-path\demo\touchtracer\icon.ico examples-path\demo\touchtracer\main.py

更多其它選項,請參考 PyInstaller 官方說明

###3 編輯配置文件 在 TouchApp 里面會有一個配置文件 touchtracer.spec。咱們需要編輯修改一下這個文件,在里面增加一些依賴包的 hook,這樣才能保證正確創建 exe。接下來就是打開編輯器了,愛用啥都行,然后在配置文件的開頭添加上下面這句:(這里是假設用的是 sdl2, 現在 Kivy 默認使用這個)

from kivy.deps import sdl2, glew

然后,用搜索,找到 COLLECT() 這個位置,添加上 touchtracer 用到的其他文件(touchtracer.kv, particle.png,等等):修改示例中的行位置,添加一個 Tree() 對象,例如這里的是 Tree('examples-path\\demo\\touchtracer\\')。這個 Tree() 會搜索在當前這個 touchtracer 文件夾的所有文件,並添加到你最終打包的程序中。

要添加額外的依賴包,就要在 COLLECT 的第一個關鍵詞參數的前面,為每一個依賴包的路徑添加一個 Tree 對象。例如下面的就是以 *[Tree(p) for p in(sdl2.dep_bins + glew.dep_bins)] 為例:

coll = COLLECT(exe, Tree('examples-path\\demo\\touchtracer\\'), a.binaries, a.zipfiles, a.datas, *[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)], strip=False, upx=True, name='touchtracer')

###4 進行構建 接下來就用 TouchApp 里面這個 spec 配置文件來進行構建了:

python -m PyInstaller touchtracer.spec

###5 生成位置 編譯好的包會在 TouchApp\dist\touchtracer 這個目錄。

使用 gstreamer 創建一個視頻應用

接下來就是修改一下上面的這個樣例了,這回要打包的 APP 是一個使用了 gstreamer 的視頻應用。咱們這回用樣例中的視頻播放器的例子 videoplayer,代碼在examples-path\widgets\videoplayer.py。另外創建一個名字為 VideoPlayer 的文件夾,然后在命令行中進入到這個文件夾,之后操作如下:

python -m PyInstaller --name gstvideo examples-path\widgets\videoplayer.py

這回要修改 gstvideo.spec 這個文件。跟上文的方法類似,也就是把 gstreamer 的依賴包放進去:

from kivy.deps import sdl2, glew, gstreamer

然后就是增加 Tree() 來包含好要用的視頻文件,Tree('examples-path\\widgets') 和 gstreamer 依賴都得弄好,大概如下所示:

coll = COLLECT(exe, Tree('examples-path\\widgets'), a.binaries, a.zipfiles, a.datas, *[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins + gstreamer.dep_bins)], strip=False, upx=True, name='gstvideo')

接下來就是使用 VideoPlayer 文件夾中的這個 spec 配置文件來進行構建了:

python -m PyInstaller gstvideo.spec

然后你就能在 VideoPlayer\dist\gstvideo 這個位置找到 gstvideo.exe 這個文件了,運行一下就能播放視頻了。

特別注意

如果你用了 Pygame,或者你打包的程序需要 Pygame,那在你的 spec 文件里面就還得添加如下的代碼,在 import 導入語句的后面添加(詳情參考 kivy issue #1638):

def getResource(identifier, *args, **kwargs): if identifier == 'pygame_icon.tiff': raise IOError() return _original_getResource(identifier, *args, **kwargs) import pygame.pkgdata _original_getResource = pygame.pkgdata.getResource pygame.pkgdata.getResource = getResource

覆蓋默認 Hook

包含/移除視頻音頻以及縮小應用體積

PyInstallers 默認會將 Kivy 用到的所有核心模塊和這些模塊的依賴包,全部都添加成 hook,比如音頻,視頻,拼寫等等(然而 gstreamer 的 dll 還是需要你用 Tree() 來手動添加,參考上文)。有的 Hook 並沒有用到或者想要縮小應用的體積,就都可以嘗試着移除一些模塊,比如如果沒有用到音頻和視頻,就可以用自定義的 Hook了。

Kivy 在hookspath() 提供了可選的 Hook。

此外,當且僅當 PyInstaller 沒有默認的 hook 的時候,就必須得提供一個runtime_hooks()。 覆蓋 hook的時候,這個runtime_hooks() 不需要覆蓋。

可選自定義的hookspath() hook不包含任何 Kivy 的 provider。要添加電話,就要用get_deps_minimal() 或者 get_deps_all()來添加。可以看看相關的文檔以及pyinstaller_hooks來了解更多信息。不過get_deps_all()跟默認的 hook一樣,都是把所有 provider 都添加進去;而get_deps_minimal() 只添加在應用程序運行的時候加載了的內容。

這兩個方法都提供了一個 Kivy 隱藏導入列表,以及排除的導入,可以傳遞出來給 Analysis

還可以生成一個自定義 hook,一個個列出每一個 kivy 的 provider 模塊,然后把其中用不上的就注釋掉就行了。

參考 pyinstaller_hooks.

要在上面的例子中使用自定義 hook,要按照下面給出的范例來修改,以hookspath()runtime_hooks(必要情況下),然后是**get_deps_minimal() 或者 **get_deps_all()來制定好各種 provider。

例如,增加了導入語句 from kivy.tools.packaging.pyinstaller_hooks import  get_deps_minimal, get_deps_all, hookspath,runtime_hooks ,然后按照如下方式修改Analysis

a = Analysis(['examples-path\\demo\\touchtracer\\main.py'], ... hookspath=hookspath(), runtime_hooks=runtime_hooks(), ... **get_deps_all())

上面這個實際上跟默認 hook 一樣包含全部了。或者可以:

a = Analysis(['examples-path\\demo\\touchtracer\\main.py'], ... hookspath=hookspath(), runtime_hooks=runtime_hooks(), ... **get_deps_minimal(video=None, audio=None))

這樣就是移除了聲音視頻的 provider,這就只加載了用到的核心模塊了。

關鍵就是要提供自定義的 hookspath(),這個默認並不會列出全部的 kivy provider,而是手動的來設定隱藏導入的模塊和需要用的 provider,通過get_deps_minimal()來移除用不上的模塊 (比如上面的是聲音影像)。

其他安裝方式

前面的這些例子都用到了 *[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins + gstreamer.dep_bins)], 這樣的語句來保證 PyInstaller 把所有依賴包用到的 dll 都添加進去。如果不是用 wheel 的方法安裝的 Kivy,那么這些命令就很可能失敗,比如 kivy.deps.sdl2 可能就無法導入。這時候,你就必須得找到這些 dll 文件的位置,然后手動地一個個傳遞給 Tree 類,傳遞方法和上面說的基本差不多了。

(譯者注:Windows 平台還是推薦用 wheel 二進制安裝,省心多了。)

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM