Eel 0.14.0
Содержание:
Using a Console Window¶
By default the bootloader creates a command-line console
(a terminal window in GNU/Linux and Mac OS, a command window in Windows).
It gives this window to the Python interpreter for its standard input and output.
Your script’s use of and are directed here.
Error messages from Python and default logging output
also appear in the console window.
An option for Windows and Mac OS is to tell PyInstaller to not provide a console window.
The bootloader starts Python with no target for standard output or input.
Do this when your script has a graphical interface for user input and can properly
report its own diagnostics.
Analysis: Finding the Files Your Program Needs¶
What other modules and libraries does your script need in order to run?
(These are sometimes called its “dependencies”.)
To find out, PyInstaller finds all the statements
in your script.
It finds the imported modules and looks in them for
statements, and so on recursively, until it has a complete list of
modules your script may use.
PyInstaller understands the “egg” distribution format often used
for Python packages.
If your script imports a module from an “egg”, PyInstaller adds
the egg and its dependencies to the set of needed files.
PyInstaller also knows about many major Python packages,
including the GUI packages
Qt (imported via PyQt or PySide), WxPython, TkInter, Django,
and other major packages.
For a complete list, see Supported Packages.
Some Python scripts import modules in ways that PyInstaller cannot detect:
for example, by using the function with variable data,
using ,
or manipulating the value at run time.
If your script requires files that PyInstaller does not know about,
you must help it:
- You can give additional files on the command line.
- You can give additional import paths on the command line.
- You can edit the file
that PyInstaller writes the first time you run it for your script.
In the spec file you can tell PyInstaller about code modules
that are unique to your script. - You can write “hook” files that inform PyInstaller of hidden imports.
If you create a “hook” for a package that other users might also use,
you can contribute your hook file to PyInstaller.
If your program depends on access to certain data files,
you can tell PyInstaller to include them in the bundle as well.
You do this by modifying the spec file, an advanced topic that is
covered under .
In order to locate included files at run time,
your program needs to be able to learn its path at run time
in a way that works regardless of
whether or not it is running from a bundle.
This is covered under .
More comprehensive example
This is based on the Inno sample code in the py2exe distribution. It has worked successfully for a rather complicated PyGTK/Twisted app requiring extra data at runtime (GTK runtime data, GtkBuilder files, images, text data) that just wouldn’t work with bundle_files.
The exe file it produces will:
- Display a dialog while extracting the data to a temporary directory
- Hide itself when the app launches
- Automatically clean up and close afterwards
Sanity check: If your app is large and might be used repeatedly, you should probably think about just making a proper installer. This is for those times when you know someone just needs to «fire and forget»!
setup.py
import os, os.path
import subprocess
from distutils.core import setup
from py2exe.build_exe import py2exe
NSIS_SCRIPT_TEMPLATE = r"""
!define py2exeOutputDirectory '{output_dir}\'
!define exe '{program_name}.exe'
; Uses solid LZMA compression. Can be slow, use discretion.
SetCompressor /SOLID lzma
; Sets the title bar text (although NSIS seems to append "Installer")
Caption "{program_desc}"
Name '{program_name}'
OutFile ${{exe}}
Icon '{icon_location}'
; Use XPs styles where appropriate
XPStyle on
; You can opt for a silent install, but if your packaged app takes a long time
; to extract, users might get confused. The method used here is to show a dialog
; box with a progress bar as the installer unpacks the data.
;SilentInstall silent
AutoCloseWindow true
ShowInstDetails nevershow
Section
DetailPrint "Extracting application..."
SetDetailsPrint none
InitPluginsDir
SetOutPath '$PLUGINSDIR'
File /r '${{py2exeOutputDirectory}}\*'
GetTempFileName $0
;DetailPrint $0
Delete $0
StrCpy $0 '$0.bat'
FileOpen $1 $0 'w'
FileWrite $1 '@echo off$\r$\n'
StrCpy $2 $TEMP 2
FileWrite $1 '$2$\r$\n'
FileWrite $1 'cd $PLUGINSDIR$\r$\n'
FileWrite $1 '${{exe}}$\r$\n'
FileClose $1
; Hide the window just before the real app launches. Otherwise you have two
; programs with the same icon hanging around, and it's confusing.
HideWindow
nsExec::Exec $0
Delete $0
SectionEnd
"""
class NSISScript(object):
NSIS_COMPILE = "makensis"
def __init__(self, program_name, program_desc, dist_dir, icon_loc):
self.program_name = program_name
self.program_desc = program_desc
self.dist_dir = dist_dir
self.icon_loc = icon_loc
self.pathname = "setup_%s.nsi" % self.program_name
def create(self):
contents = NSIS_SCRIPT_TEMPLATE.format(
program_name = self.program_name,
program_desc = self.program_desc,
output_dir = self.dist_dir,
icon_location = os.path.join(self.dist_dir, self.icon_loc))
with open(self.pathname, "w") as outfile:
outfile.write(contents)
def compile(self):
subproc = subprocess.Popen(
# "/P5" uses realtime priority for the LZMA compression stage.
# This can get annoying though.
[self.NSIS_COMPILE, self.pathname, "/P5"], env=os.environ)
subproc.communicate()
retcode = subproc.returncode
if retcode:
raise RuntimeError("NSIS compilation return code: %d" % retcode)
class build_installer(py2exe):
# This class first builds the exe file(s), then creates an NSIS installer
# that runs your program from a temporary directory.
def run(self):
# First, let py2exe do it's work.
py2exe.run(self)
lib_dir = self.lib_dir
dist_dir = self.dist_dir
# Create the installer, using the files py2exe has created.
script = NSISScript(PROGRAM_NAME,
PROGRAM_DESC,
dist_dir,
os.path.join('path', 'to, 'my_icon.ico'))
print "*** creating the NSIS setup script***"
script.create()
print "*** compiling the NSIS setup script***"
script.compile()
zipfile = r"lib\shardlib"
setup(
name = 'MyApp',
description = 'My Application',
version = '1.0',
window = ,
'dest_base': PROGRAM_NAME,
},
]
options = {
'py2exe': {
# Py2exe options...
}
},
zipfile = zipfile,
data_files = # etc...
cmdclass = {"py2exe": build_installer},
)
Notes:
-
I couldn’t figure out how to use pywin32 or ctypes to invoke the NSIS compiler, so I used subprocess
-
That means that you need to add the NSIS compiler dir to your PATH
-
The icon location could probably be deduced from the py2exe class
-
This produces the setup_program_name.nsi file and the program_name.exe in the working directory, not in dist\
Project details
Homepage
Meta
License: GNU General Public License v2 (GPLv2) (GPL license with a special exception which allows to use PyInstaller to build and distribute non-free programs (including commercial ones))
Author: Giovanni Bajo, Hartmut Goebel, David Vierra, David Cortesi, Martin Zibricky
Classifiers
-
Development Status
6 — Mature
-
Environment
Console
-
Intended Audience
-
Developers
-
Other Audience
-
System Administrators
-
-
License
OSI Approved :: GNU General Public License v2 (GPLv2)
-
Natural Language
English
-
Operating System
-
MacOS :: MacOS X
-
Microsoft :: Windows
-
POSIX
-
POSIX :: AIX
-
POSIX :: BSD
-
POSIX :: Linux
-
POSIX :: SunOS/Solaris
-
-
Programming Language
-
C
-
Python
-
Python :: 2
-
Python :: 2.7
-
Python :: 3
-
Python :: 3.3
-
Python :: 3.4
-
Python :: 3.5
-
Python :: Implementation :: CPython
-
-
Topic
-
Software Development
-
Software Development :: Build Tools
-
Software Development :: Interpreters
-
Software Development :: Libraries :: Python Modules
-
System :: Installation/Setup
-
System :: Software Distribution
-
Utilities
-
Capturing Windows Version Data¶
A Windows app may require a Version resource file.
A Version resource contains a group of data structures,
some containing binary integers and some containing strings,
that describe the properties of the executable.
For details see the Microsoft Version Information Structures page.
Version resources are complex and
some elements are optional, others required.
When you view the version tab of a Properties dialog,
there’s no simple relationship between
the data displayed and the structure of the resource.
For this reason PyInstaller includes the command.
It is invoked with the full path name of any Windows executable
that has a Version resource:
The command writes text that represents
a Version resource in readable form to standard output.
You can copy it from the console window or redirect it to a file.
Then you can edit the version information to adapt it to your program.
Using you can find an executable that displays the kind of
information you want, copy its resource data, and modify it to suit your package.
The version text file is encoded UTF-8 and may contain non-ASCII characters.
(Unicode characters are allowed in Version resource string fields.)
Be sure to edit and save the text file in UTF-8 unless you are
certain it contains only ASCII string values.
Your edited version text file can be given with the
option to or .
The text data is converted to a Version resource and
installed in the bundled app.
In a Version resource there are two 64-bit binary values,
and .
In the version text file these are given as four-element tuples,
for example:
filevers=(2, , 4, ), prodvers=(2, , 4, ),
The elements of each tuple represent 16-bit values
from most-significant to least-significant.
For example the value resolves to
in hex.
You can also install a Version resource from a text file after
the bundled app has been created, using the command:
The utility reads a version text file as written
by , converts it to a Version resource,
and installs that resource in the executable_file specified.
How does it work?
py2exe uses python’s modulefinder to examine your script and
find all python and extension modules needed to run it. Pure python
modules are compiled into .pyc or .pyo files 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 on sys.path.
In simple cases, only pythonxx.dll is needed in addition to
myscript.exe. If, however, your script needs extension modules,
unfortunately those cannot be included or imported from the
zip-archive, so they are needed as separate files (and are copied into
the dist directory).
How the One-Folder Program Works¶
A bundled program always starts execution in the PyInstaller bootloader.
This is the heart of the executable in the folder.
The PyInstaller bootloader is a binary
executable program for the active platform
(Windows, GNU/Linux, Mac OS X, etc.).
When the user launches your program, it is the bootloader that runs.
The bootloader creates a temporary Python environment
such that the Python interpreter will find all imported modules and
libraries in the folder.
The bootloader starts a copy of the Python interpreter
to execute your script.
Everything follows normally from there, provided
that all the necessary support files were included.
Tips and Tricks
General
-
ListOfOptions How to see the list of available options for your setup.py script
-
RunningSetup How to run the setup script once you’ve written it
-
EncodingsAgain Problem with encodings and when they are not found in a standalone executable
-
EvenMoreEncodings They really keep bugging. Solution to problem with different site.py
-
AddingConfigFiles How can you add arbitrary files to your Py2Exe-Setup?
-
PathModul Using Jason Orendorffs python PathModul together with Py2Exe 0.5
-
PassingOptionsToPy2Exe Avoid using sys.argv to pass options
-
SubclassingPy2Exe Customizing the build process
-
CustomIcons How to get your own icons with Py2Exe 0.5
-
TkInter I do not need any tkinter / tcl-Libs in my Setup
-
FilenameCaseMatters Some windows filing systems mangle case, break py2exe programs
-
WinBatch A short Windows Batch File to fast provide the EXE File
-
ExcludingDlls Stopping py2exe from picking up unwanted DLLs
-
ShippingEmbedded How to use py2exe to ship embedded Python modules
-
SingleFileExecutable with NSIS
-
OptimizedBytecode How to get optimized bytecode for all modules
-
CustomDataInExe Add custom data in the executable?
-
HowToDetermineIfRunningFromExe Simple functions to determine if you’re in an .exe or .py
-
WhereAmI sometimes you need to now where your exe is within the filesystem
py2exe and PyXML
Py2exeAndPyXML If you’re getting File «xml\sax\saxexts.pyc», line 77, in make_parser; xml.sax._exceptions.SAXReaderNotAvailable: No parsers found, read this.
py2exe and win32com
-
Py2exeAndWin32com Creating a win32com exe and/or dll com server
-
WinShell Using win32com.shell with py2exe 0.5
-
IncludingTypelibs Allowing use of makepy generated typelibs
py2exe and ctypes.com
-
Py2exeAndCtypesComDllServer Creating a ctypes.com dll com server
-
Py2exeAndCtypesComExeServer Creating a ctypes.com exe com server
py2exe and Innosetup
-
BetterCompression Getting complete wxPython Programs down to around 4 Megabytes
-
SetupLanguage How to localize the language with py2exe and InnoSetup
-
QuickStartIcons How to add Startup-Links to the Quickstart-Bar & the Desktop using InnoSetup together with Py2Exe
py2exe and SciPy
ScipyImportProblems Using py2exe with scipy ends up with missing cephes and __cvs_version__ messages. Here is a fix.
py2exe and Quixote
Quixote is a pythonivc toolkit for web pages which allows one to execute ptl files using ihooks. You can distribute your web application with medusa or twisted and hence you can create a web application without IIS or Apache.
I like to distribute my application with py2exe but I can not make py2exe setup script to recognize that x.ptl is a valid python files. Any idea how to do this? — impossible: py2exeAndQuixote HAM20040602
py2exe and NumPy
If you’re getting No scipy-style subpackage ‘xxx’ found in c:\…\library.zip\numpy. Ignoring, try —skip-archive option.
Лучшие практики для исправления проблем с python
Аккуратный и опрятный компьютер — это главное требование для избежания проблем с python. Для этого требуется регулярная проверка компьютера на вирусы, очистка жесткого диска, используя cleanmgr и sfc /scannow, удаление программ, которые больше не нужны, проверка программ, которые запускаются при старте Windows (используя msconfig) и активация Автоматическое обновление Windows. Всегда помните о создании периодических бэкапов, или в крайнем случае о создании точек восстановления.
Если у вас актуальные проблемы, попробуйте вспомнить, что вы делали в последнее время, или последнюю программу, которую вы устанавливали перед тем, как появилась впервые проблема. Используйте команду resmon, чтобы определить процесс, который вызывает проблемы. Даже если у вас серьезные проблемы с компьютером, прежде чем переустанавливать Windows, лучше попробуйте восстановить целостность установки ОС или для Windows 8 и более поздних версий Windows выполнить команду DISM.exe /Online /Cleanup-image /Restorehealth. Это позволит восстановить операционную систему без потери данных.