Generate py as an EXE file

Source: Internet
Author: User
Tags glob
Using py2exe

Assuming you have written a Python scriptMyscript. pyWhich you want to convert into an executable windows program, able to run on systems without a python installation. If you don't already have writtenDistutilsSetup-script, write one, and insert the statementImport py2exeBefore the call to the setup function:

# setup.pyfrom distutils.core import setupimport py2exesetup(console=["myscript.py"])

Running

python setup.py py2exe --help

Will display all available command-line flags toPy2exeCommand.

Now you can call the setup script like in this way:

python setup.py py2exe

And a subdirectoryDistWill be created, containing the filesMyscript.exe,Python23.dll, AndLibrary.zip. If your script uses compiled C extension modules, they will be copied here as well, also all DLLs needed at runtime (wait t the system DLLs ).

These files include everything that is needed for your program, and you shoshould distribute the whole directory contents.

The above setup script creates a console program, if you want a GUI program without the console window, simply replaceConsole = ["myscript. py"]WithWindows = ["myscript. py"].

Py2exeCan create more than one EXE file in one run, this is useful if you have a couple of related scripts. Pass a list Of all scripts inConsoleAnd/orWindowsKeyword argument.

Specifying additional files

Some applications need additional files at runtime, like configuration files, fonts, or bitmaps.

Py2exeCan copy these files into subdirectoriesDistIf they are specified in the setup script withData_filesOption.Data_filesShocould contain a sequence(Target-Dir, files)Tuples, where files is a sequence of files to be copied.

Here's an example:

# setup.pyfrom distutils.core import setupimport globimport py2exesetup(console=["myscript.py"],      data_files=[("bitmaps",                   ["bm/large.gif", "bm/small.gif"]),                  ("fonts",                   glob.glob("fonts//*.fnt"))],)

This wocould create a subdirectoryDist/bitmaps, Containing the two. GifFiles, and a subdirectoryDist/Fonts, Containing all. FntFiles.

Windows NT Services

You can build windows NT services by passingServiceKeyword argument toSetupFunction, the value must be a list of Python module names containing a service class (identified by_ Svc_name _Attribute ):

# setup.pyfrom distutils.core import setupimport py2exesetup(service=["MyService"])

The built service executables are able to install and remove themselves by calling them with certain command line flags, run the EXE with-HelpArgument to find out more.

Com servers

Com servers are built by passingCom_serverKeyword argument to the setup function, again the value must be a list of Python module names containing one or more COM server classes (identified by their_ Reg_progid _Attribute ):

# setup.pyfrom distutils.core import setupimport py2exesetup(com_server=["win32com.server.interp"])

By default both DLL and exe servers are built, you should delete those you don't need.

The bundle Option

By default py2exe creates these files inDistDirectory which you must deploy:

  1. One (or more). EXE files
  2. The Python #. dll
  3. A couple of. PYD files which are the compiled extensions that the EXE files need, plus any other. DLL files that the extensions need.
  4. ALibrary.zipFile which contains the compiled pure Python modules. pyC or. pyo files (if you have specified 'zipfile = none' in the setup script this file is append to. EXE files and not present in the dist-directory ).

The-- Bundle <level>Or-B <level>Command line switch will create less files because binary extensions, runtime DLLs, and even the python-DLL itself is bundled into the executable itself, or inside the library-archive if you prefer that.

The bundled pyds and DLLs areNeverUnpacked to the file system, instead they are transparently loaded at runtime from the bundle. The resulting executableAppearsTo be statically linked.

Specifying a level2Provided des. PYD and. DLL files into the zip-archive or the executable. thus, the DIST directory will contain your EXE file (s), the library.zip file (if you haven't specified 'zipfile = none'), and the python DLL. the advantage of this scheme is that the application can still LOAD extension modules from the file system if you extendSYS. PathAt runtime.

Using a level1Provided des. PYD and. DLL files into the zip-archive or the executable itself, and does the same for pythonxy. DLL. the advantage is that you only need to distribute one file per EXE, which will however be quite large. another advantage is that inproc com servers will run completely isolated from other Python interpreters in the same exe. the disadvantage of this scheme is that it is impossible to load other extensions from the file system, the application will crash with a fatal Python error if you try this. I have still to find a way to prevent this and raise an importerror instead-Any suggestions how this can be implemented wocould be very welcome.

The bundle-option has been tested with some popular extensions, but of course there's no guarantee that any extension will work in bundled form-be sure to test the executable (which you shoshould do anyway ).

The bundle option achieves its magic by code which emulates the Windows loadlibrary API, It is compiled into the exe-stubs that py2exe uses. for experimentation, it is also installed as a normal Python Extension_ Memimporter. PYDInLIB/Site-packagesDirectory. The Python ModuleZipextimported. pyIn the same directory demonstrates how it can be used to load binary extensions from zip-files.

Samples

ThePy2exe-Installer installsome examples intoLIB/Site-packages/py2exe/SamplesDirectory, demonstrating Several simple and advances features.

TheSinglefileSubdirectory contains two samples which are built as single-file executables: a trivial wxpython GUI program, and a pywin32 dll com server module.

How does it work?

Py2exeUses Python'sModulefinderTo examine your script and find all Python and extension modules needed to run it. Pure Python modules are compiled. PyCOr. PyoFiles in a temporary directory. Compiled extension modules (. PYD) Are also found and parsed for Binary dependencies.

A zip-compatible archive is built, containing all Python files from this directory. your main script is inserted as a resource into a custom embedded Python interpreter supplied with py2exe, and the zip-archive is installed as the only item onSYS. Path.

In simple cases, onlyPythonxx. dllIs needed in additionMyscript.exe. If, however, your script needs extension modules, unfortunately those cannot be encoded or imported from the zip-archive, so they are needed as separate files (and are copied intoDistDirectory ).

Attention:Py2exeTries to track down all binary dependencies for all pyds and DLLs copied to the DIST directory recursively, and copies all these dependend files into the DIST directory.Py2exeHas a builtin list of some system DLLs which are not copied, but this list can never be complete.

Installing py2exe

Download and run the installer py2exe-0.6.3.win32-py2.3.exe (for python 2.3), or py2exe-0.6.3.win32-py2.4.exe (for python 2.4 ).

This instilsPy2exeTogether with some samples, the samples are inLIB/Site-packages/py2exe/SamplesSubdirectory.

ForWindows 95/98/me, You needMicrosoft layer for Unicode on Windows 95/98/me systems (mslu)DLL from here (Internet Explorer is required to download it: scroll down to the Win95/98/me section ).

Download and run the self-extractingUnicows.exeFile, and copy the unpackedUnicows. dllFile in the directory which contains yourPython.exe. Note that this is only needed on the machine where you want to build executablesPy2exe, It is not required on the machine where you want to run the created programs.

If you usePy2exeTo build COM clients or servers, win32all build 163 (or later) is stronugly recommened-it contains much better support for frozen executables.

This article is from www.py2exe.org

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.