cx_Freeze-4.3.1/0000755000000000000000000000000012053761027012132 5ustar rootrootcx_Freeze-4.3.1/source/0000755000000000000000000000000012053761027013432 5ustar rootrootcx_Freeze-4.3.1/source/util.c0000664000076600012760000004143212000121627013000 0ustar //----------------------------------------------------------------------------- // util.c // Shared library for use by cx_Freeze. //----------------------------------------------------------------------------- #include #ifdef MS_WINDOWS #include #include #include #pragma pack(2) typedef struct { BYTE bWidth; // Width, in pixels, of the image BYTE bHeight; // Height, in pixels, of the image BYTE bColorCount; // Number of colors in image BYTE bReserved; // Reserved ( must be 0) WORD wPlanes; // Color Planes WORD wBitCount; // Bits per pixel DWORD dwBytesInRes; // How many bytes in this resource? DWORD dwImageOffset; // Where in the file is this image? } ICONDIRENTRY; typedef struct { WORD idReserved; // Reserved (must be 0) WORD idType; // Resource Type (1 for icons) WORD idCount; // How many images? ICONDIRENTRY idEntries[0]; // An entry for each image } ICONDIR; typedef struct { BYTE bWidth; // Width, in pixels, of the image BYTE bHeight; // Height, in pixels, of the image BYTE bColorCount; // Number of colors in image BYTE bReserved; // Reserved ( must be 0) WORD wPlanes; // Color Planes WORD wBitCount; // Bits per pixel DWORD dwBytesInRes; // How many bytes in this resource? WORD nID; // resource ID } GRPICONDIRENTRY; typedef struct { WORD idReserved; // Reserved (must be 0) WORD idType; // Resource Type (1 for icons) WORD idCount; // How many images? GRPICONDIRENTRY idEntries[0]; // An entry for each image } GRPICONDIR; #endif //----------------------------------------------------------------------------- // Globals //----------------------------------------------------------------------------- #ifdef MS_WINDOWS static PyObject *g_BindErrorException = NULL; static PyObject *g_ImageNames = NULL; #endif // define PyInt_* macros for Python 3.x #ifndef PyInt_Check #define PyInt_Check PyLong_Check #define PyInt_FromLong PyLong_FromLong #endif #ifdef MS_WINDOWS //----------------------------------------------------------------------------- // BindStatusRoutine() // Called by BindImageEx() at various points. This is used to determine the // dependency tree which is later examined by cx_Freeze. //----------------------------------------------------------------------------- static BOOL __stdcall BindStatusRoutine( IMAGEHLP_STATUS_REASON reason, // reason called PSTR imageName, // name of image being examined PSTR dllName, // name of DLL ULONG virtualAddress, // computed virtual address ULONG parameter) // parameter (value depends on reason) { char imagePath[MAX_PATH + 1]; char fileName[MAX_PATH + 1]; switch (reason) { case BindImportModule: strcpy(imagePath, imageName); PathRemoveFileSpec(imagePath); if (!SearchPath(imagePath, dllName, NULL, sizeof(fileName), fileName, NULL)) { if (!SearchPath(NULL, dllName, NULL, sizeof(fileName), fileName, NULL)) return FALSE; } Py_INCREF(Py_None); if (PyDict_SetItemString(g_ImageNames, fileName, Py_None) < 0) return FALSE; break; default: break; } return TRUE; } //----------------------------------------------------------------------------- // GetFileData() // Return the data for the given file. //----------------------------------------------------------------------------- static int GetFileData( const char *fileName, // name of file to read char **data) // pointer to data (OUT) { DWORD numberOfBytesRead, dataSize; HANDLE file; file = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (file == INVALID_HANDLE_VALUE) return -1; dataSize = GetFileSize(file, NULL); if (dataSize == INVALID_FILE_SIZE) { CloseHandle(file); return -1; } *data = PyMem_Malloc(dataSize); if (!*data) { CloseHandle(file); return -1; } if (!ReadFile(file, *data, dataSize, &numberOfBytesRead, NULL)) { CloseHandle(file); return -1; } CloseHandle(file); return 0; } //----------------------------------------------------------------------------- // CreateGroupIconResource() // Return the group icon resource given the icon file data. //----------------------------------------------------------------------------- static GRPICONDIR *CreateGroupIconResource( ICONDIR *iconDir, // icon information DWORD *resourceSize) // size of resource (OUT) { GRPICONDIR *groupIconDir; int i; *resourceSize = sizeof(GRPICONDIR) + sizeof(GRPICONDIRENTRY) * iconDir->idCount; groupIconDir = PyMem_Malloc(*resourceSize); if (!groupIconDir) return NULL; groupIconDir->idReserved = iconDir->idReserved; groupIconDir->idType = iconDir->idType; groupIconDir->idCount = iconDir->idCount; for (i = 0; i < iconDir->idCount; i++) { groupIconDir->idEntries[i].bWidth = iconDir->idEntries[i].bWidth; groupIconDir->idEntries[i].bHeight = iconDir->idEntries[i].bHeight; groupIconDir->idEntries[i].bColorCount = iconDir->idEntries[i].bColorCount; groupIconDir->idEntries[i].bReserved = iconDir->idEntries[i].bReserved; groupIconDir->idEntries[i].wPlanes = iconDir->idEntries[i].wPlanes; groupIconDir->idEntries[i].wBitCount = iconDir->idEntries[i].wBitCount; groupIconDir->idEntries[i].dwBytesInRes = iconDir->idEntries[i].dwBytesInRes; groupIconDir->idEntries[i].nID = i + 1; } return groupIconDir; } //----------------------------------------------------------------------------- // ExtAddIcon() // Add the icon as a resource to the specified file. //----------------------------------------------------------------------------- static PyObject *ExtAddIcon( PyObject *self, // passthrough argument PyObject *args) // arguments { char *executableName, *iconName, *data, *iconData; GRPICONDIR *groupIconDir; DWORD resourceSize; ICONDIR *iconDir; BOOL succeeded; HANDLE handle; int i; if (!PyArg_ParseTuple(args, "ss", &executableName, &iconName)) return NULL; // begin updating the executable handle = BeginUpdateResource(executableName, FALSE); if (!handle) { PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError, GetLastError(), executableName); return NULL; } // first attempt to get the data from the icon file data = NULL; succeeded = TRUE; groupIconDir = NULL; if (GetFileData(iconName, &data) < 0) succeeded = FALSE; iconDir = (ICONDIR*) data; // next, attempt to add a group icon resource if (succeeded) { groupIconDir = CreateGroupIconResource(iconDir, &resourceSize); if (groupIconDir) succeeded = UpdateResource(handle, RT_GROUP_ICON, MAKEINTRESOURCE(1), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), groupIconDir, resourceSize); else succeeded = FALSE; } // next, add each icon as a resource if (succeeded) { for (i = 0; i < iconDir->idCount; i++) { iconData = &data[iconDir->idEntries[i].dwImageOffset]; resourceSize = iconDir->idEntries[i].dwBytesInRes; succeeded = UpdateResource(handle, RT_ICON, MAKEINTRESOURCE(i + 1), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), iconData, resourceSize); if (!succeeded) break; } } // finish writing the resource (or discarding the changes upon an error) if (!EndUpdateResource(handle, !succeeded)) { if (succeeded) { succeeded = FALSE; PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError, GetLastError(), executableName); } } // clean up if (groupIconDir) PyMem_Free(groupIconDir); if (data) PyMem_Free(data); if (!succeeded) return NULL; Py_INCREF(Py_None); return Py_None; } //----------------------------------------------------------------------------- // ExtBeginUpdateResource() // Wrapper for BeginUpdateResource(). //----------------------------------------------------------------------------- static PyObject *ExtBeginUpdateResource( PyObject *self, // passthrough argument PyObject *args) // arguments { BOOL deleteExistingResources; char *fileName; HANDLE handle; deleteExistingResources = TRUE; if (!PyArg_ParseTuple(args, "s|i", &fileName, &deleteExistingResources)) return NULL; handle = BeginUpdateResource(fileName, deleteExistingResources); if (!handle) { PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError, GetLastError(), fileName); return NULL; } return PyInt_FromLong((long) handle); } //----------------------------------------------------------------------------- // ExtUpdateResource() // Wrapper for UpdateResource(). //----------------------------------------------------------------------------- static PyObject *ExtUpdateResource( PyObject *self, // passthrough argument PyObject *args) // arguments { int resourceType, resourceId, resourceDataSize; char *resourceData; HANDLE handle; if (!PyArg_ParseTuple(args, "iiis#", &handle, &resourceType, &resourceId, &resourceData, &resourceDataSize)) return NULL; if (!UpdateResource(handle, MAKEINTRESOURCE(resourceType), MAKEINTRESOURCE(resourceId), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), resourceData, resourceDataSize)) { PyErr_SetExcFromWindowsErr(PyExc_WindowsError, GetLastError()); return NULL; } Py_INCREF(Py_None); return Py_None; } //----------------------------------------------------------------------------- // ExtEndUpdateResource() // Wrapper for EndUpdateResource(). //----------------------------------------------------------------------------- static PyObject *ExtEndUpdateResource( PyObject *self, // passthrough argument PyObject *args) // arguments { BOOL discardChanges; HANDLE handle; discardChanges = FALSE; if (!PyArg_ParseTuple(args, "i|i", &handle, &discardChanges)) return NULL; if (!EndUpdateResource(handle, discardChanges)) { PyErr_SetExcFromWindowsErr(PyExc_WindowsError, GetLastError()); return NULL; } Py_INCREF(Py_None); return Py_None; } //----------------------------------------------------------------------------- // ExtGetDependentFiles() // Return a list of files that this file depends on. //----------------------------------------------------------------------------- static PyObject *ExtGetDependentFiles( PyObject *self, // passthrough argument PyObject *args) // arguments { PyObject *results; char *imageName; if (!PyArg_ParseTuple(args, "s", &imageName)) return NULL; g_ImageNames = PyDict_New(); if (!g_ImageNames) return NULL; if (!BindImageEx(BIND_NO_BOUND_IMPORTS | BIND_NO_UPDATE | BIND_ALL_IMAGES, imageName, NULL, NULL, BindStatusRoutine)) { Py_DECREF(g_ImageNames); PyErr_SetExcFromWindowsErrWithFilename(g_BindErrorException, GetLastError(), imageName); return NULL; } results = PyDict_Keys(g_ImageNames); Py_DECREF(g_ImageNames); return results; } //----------------------------------------------------------------------------- // ExtGetSystemDir() // Return the Windows system directory (C:\Windows\system for example). //----------------------------------------------------------------------------- static PyObject *ExtGetSystemDir( PyObject *self, // passthrough argument PyObject *args) // arguments (ignored) { #if PY_MAJOR_VERSION >= 3 OLECHAR dir[MAX_PATH + 1]; if (GetSystemDirectoryW(dir, sizeof(dir))) return PyUnicode_FromUnicode(dir, wcslen(dir)); #else char dir[MAX_PATH + 1]; if (GetSystemDirectory(dir, sizeof(dir))) return PyString_FromString(dir); #endif PyErr_SetExcFromWindowsErr(PyExc_RuntimeError, GetLastError()); return NULL; } //----------------------------------------------------------------------------- // ExtGetWindowsDir() // Return the Windows directory (C:\Windows for example). //----------------------------------------------------------------------------- static PyObject *ExtGetWindowsDir( PyObject *self, // passthrough argument PyObject *args) // arguments (ignored) { #if PY_MAJOR_VERSION >= 3 OLECHAR dir[MAX_PATH + 1]; if (GetWindowsDirectoryW(dir, sizeof(dir))) return PyUnicode_FromUnicode(dir, wcslen(dir)); #else char dir[MAX_PATH + 1]; if (GetWindowsDirectory(dir, sizeof(dir))) return PyString_FromString(dir); #endif PyErr_SetExcFromWindowsErr(PyExc_RuntimeError, GetLastError()); return NULL; } #endif //----------------------------------------------------------------------------- // ExtSetOptimizeFlag() // Set the optimize flag as needed. //----------------------------------------------------------------------------- static PyObject *ExtSetOptimizeFlag( PyObject *self, // passthrough argument PyObject *args) // arguments { if (!PyArg_ParseTuple(args, "i", &Py_OptimizeFlag)) return NULL; Py_INCREF(Py_None); return Py_None; } //----------------------------------------------------------------------------- // Methods //----------------------------------------------------------------------------- static PyMethodDef g_ModuleMethods[] = { { "SetOptimizeFlag", ExtSetOptimizeFlag, METH_VARARGS }, #ifdef MS_WINDOWS { "BeginUpdateResource", ExtBeginUpdateResource, METH_VARARGS }, { "UpdateResource", ExtUpdateResource, METH_VARARGS }, { "EndUpdateResource", ExtEndUpdateResource, METH_VARARGS }, { "AddIcon", ExtAddIcon, METH_VARARGS }, { "GetDependentFiles", ExtGetDependentFiles, METH_VARARGS }, { "GetSystemDir", ExtGetSystemDir, METH_NOARGS }, { "GetWindowsDir", ExtGetWindowsDir, METH_NOARGS }, #endif { NULL } }; #if PY_MAJOR_VERSION >= 3 //----------------------------------------------------------------------------- // Declaration of module definition for Python 3.x. //----------------------------------------------------------------------------- static struct PyModuleDef g_ModuleDef = { PyModuleDef_HEAD_INIT, "cx_Freeze.util", NULL, -1, g_ModuleMethods, // methods NULL, // m_reload NULL, // traverse NULL, // clear NULL // free }; #endif //----------------------------------------------------------------------------- // Module_Initialize() // Initialization routine for the module. //----------------------------------------------------------------------------- static PyObject *Module_Initialize(void) { PyObject *module; #if PY_MAJOR_VERSION >= 3 module = PyModule_Create(&g_ModuleDef); #else module = Py_InitModule("cx_Freeze.util", g_ModuleMethods); #endif if (!module) return NULL; #ifdef MS_WINDOWS g_BindErrorException = PyErr_NewException("cx_Freeze.util.BindError", NULL, NULL); if (!g_BindErrorException) return NULL; if (PyModule_AddObject(module, "BindError", g_BindErrorException) < 0) return NULL; #endif return module; } //----------------------------------------------------------------------------- // Entry point for the module. //----------------------------------------------------------------------------- #if PY_MAJOR_VERSION >= 3 PyMODINIT_FUNC PyInit_util(void) { return Module_Initialize(); } #else void initutil(void) { Module_Initialize(); } #endif cx_Freeze-4.3.1/source/bases/0000755000000000000000000000000012053761027014527 5ustar rootrootcx_Freeze-4.3.1/source/bases/manifest.rc0000664000076600012760000000006711776175123015132 0ustar #include "dummy.rc" 1 24 source/bases/manifest.txt cx_Freeze-4.3.1/source/bases/ConsoleKeepPath.c0000664000076600012760000000050412051341233016142 0ustar //----------------------------------------------------------------------------- // ConsoleKeepPath.c // Main routine for frozen programs which need a Python installation to do // their work. //----------------------------------------------------------------------------- #define CX_FREEZE_KEEP_PATH #include "Console.c" cx_Freeze-4.3.1/source/bases/Win32GUI.c0000664000076600012760000002450312053100321014363 0ustar //----------------------------------------------------------------------------- // Win32GUI.c // Main routine for frozen programs written for the Win32 GUI subsystem. //----------------------------------------------------------------------------- #include #include #include // define PyInt_* macros for Python 3.x #ifndef PyInt_Check #define PyInt_Check PyLong_Check #define PyInt_AsLong PyLong_AsLong #endif // define methods for manipulating strings #if PY_MAJOR_VERSION >= 3 #define cxString_Check PyUnicode_Check #define cxString_Format PyUnicode_Format #define cxString_FromAscii(str) \ PyUnicode_DecodeASCII(str, strlen(str), NULL) #define cxString_Join PyUnicode_Join #else #define cxString_Check PyString_Check #define cxString_Format PyString_Format #define cxString_FromAscii(str) PyString_FromString(str) #define cxString_Join _PyString_Join #endif //----------------------------------------------------------------------------- // FatalError() // Handle a fatal error. //----------------------------------------------------------------------------- static int FatalError( char *a_Message) // message to display { MessageBox(NULL, a_Message, "cx_Freeze Fatal Error", MB_ICONERROR); Py_Finalize(); return -1; } //----------------------------------------------------------------------------- // DisplayMessageFromPythonObjects() // Display message from Python objects. The Python objects are expected to be // of the correct type (Unicode for Python 3.x and string for Python 2.x). The // method returns -1 as a convenience to the caller. //----------------------------------------------------------------------------- static int DisplayMessageFromPythonObjects( PyObject *caption, // caption PyObject *message) // message { #if PY_MAJOR_VERSION >= 3 MessageBoxW(NULL, PyUnicode_AS_UNICODE(message), PyUnicode_AS_UNICODE(caption), MB_ICONERROR); #else MessageBox(NULL, PyString_AS_STRING(message), PyString_AS_STRING(caption), MB_ICONERROR); #endif return -1; } //----------------------------------------------------------------------------- // ArgumentValue() // Return a suitable argument value by replacing NULL with Py_None. //----------------------------------------------------------------------------- static PyObject *ArgumentValue( PyObject *object) // argument to massage { if (object) { Py_INCREF(object); return object; } Py_INCREF(Py_None); return Py_None; } //----------------------------------------------------------------------------- // FatalPythonErrorNoTraceback() // Handle a fatal Python error without traceback. //----------------------------------------------------------------------------- static int FatalPythonErrorNoTraceback( PyObject *origValue, // exception value char *contextMessage) // context message to display { PyObject *contextMessageObj, *message, *format, *formatArgs, *caption; PyObject *type, *value, *traceback; // create caption and message objects PyErr_Fetch(&type, &value, &traceback); PyErr_NormalizeException(&type, &value, &traceback); contextMessageObj = cxString_FromAscii(contextMessage); if (!contextMessageObj) return FatalError("Cannot create context message string object."); format = cxString_FromAscii("%s\nException: %s\nOriginal Exception: %s"); if (!format) return FatalError("Cannot create format string object."); formatArgs = PyTuple_New(3); if (!formatArgs) return FatalError("Cannot create format args tuple."); PyTuple_SET_ITEM(formatArgs, 0, ArgumentValue(contextMessageObj)); PyTuple_SET_ITEM(formatArgs, 1, ArgumentValue(value)); PyTuple_SET_ITEM(formatArgs, 2, ArgumentValue(origValue)); message = cxString_Format(format, formatArgs); if (!message) return FatalError("Cannot format exception values."); caption = cxString_FromAscii("cx_Freeze: Python error in main script " "(traceback unavailable)"); if (!caption) return FatalError("Cannot create caption string object."); // display message box return DisplayMessageFromPythonObjects(caption, message); } //----------------------------------------------------------------------------- // HandleSystemExitException() // Handles a system exit exception differently. If an integer value is passed // through then that becomes the exit value; otherwise the string value of the // value passed through is displayed in a message box. //----------------------------------------------------------------------------- static int HandleSystemExitException() { PyObject *caption, *message, *type, *value, *traceback, *code; int exitCode = 0; PyErr_Fetch(&type, &value, &traceback); PyErr_NormalizeException(&type, &value, &traceback); caption = PyObject_GetAttrString(value, "caption"); if (!caption || !cxString_Check(caption)) { PyErr_Clear(); caption = cxString_FromAscii("cx_Freeze: Application Terminated"); if (!caption) return FatalError("Cannot create caption string object."); } code = PyObject_GetAttrString(value, "code"); if (!code) PyErr_Clear(); else { value = code; if (value == Py_None) Py_Exit(0); } if (PyInt_Check(value)) exitCode = PyInt_AsLong(value); else { message = PyObject_Str(value); if (!message) return FatalError("Cannot get string representation of messsage."); DisplayMessageFromPythonObjects(caption, message); exitCode = 1; } Py_Exit(exitCode); return -1; } //----------------------------------------------------------------------------- // FatalScriptError() // Handle a fatal Python error with traceback. //----------------------------------------------------------------------------- static int FatalScriptError() { PyObject *type, *value, *traceback, *argsTuple, *module, *method, *result; PyObject *caption, *hook, *origHook, *emptyString, *message; // if a system exception, handle it specially if (PyErr_ExceptionMatches(PyExc_SystemExit)) return HandleSystemExitException(); // get the exception details PyErr_Fetch(&type, &value, &traceback); PyErr_NormalizeException(&type, &value, &traceback); argsTuple = PyTuple_New(3); if (!argsTuple) return FatalPythonErrorNoTraceback(value, "Cannot create args tuple."); PyTuple_SET_ITEM(argsTuple, 0, ArgumentValue(type)); PyTuple_SET_ITEM(argsTuple, 1, ArgumentValue(value)); PyTuple_SET_ITEM(argsTuple, 2, ArgumentValue(traceback)); // call the exception hook hook = PySys_GetObject("excepthook"); origHook = PySys_GetObject("__excepthook__"); if (hook && hook != origHook) { result = PyObject_CallObject(hook, argsTuple); if (!result) return FatalPythonErrorNoTraceback(value, "Error in sys.excepthook."); return -1; } // import the traceback module module = PyImport_ImportModule("traceback"); if (!module) return FatalPythonErrorNoTraceback(value, "Cannot import traceback module."); // get the format_exception method method = PyObject_GetAttrString(module, "format_exception"); if (!method) return FatalPythonErrorNoTraceback(value, "Cannot get format_exception method."); // call the format_exception method result = PyObject_CallObject(method, argsTuple); if (!result) return FatalPythonErrorNoTraceback(value, "Exception raised when calling format_exception."); // convert to string emptyString = cxString_FromAscii(""); if (!emptyString) return FatalPythonErrorNoTraceback(value, "Cannot create empty string object."); message = cxString_Join(emptyString, result); if (!message) return FatalPythonErrorNoTraceback(value, "Cannot join exception strings."); // acquire caption caption = PyObject_GetAttrString(value, "caption"); if (!caption || !cxString_Check(caption)) { PyErr_Clear(); caption = cxString_FromAscii("cx_Freeze: Python error in main script"); if (!caption) return FatalPythonErrorNoTraceback(value, "Cannot create default caption string."); } // display message box return DisplayMessageFromPythonObjects(caption, message); } #include "Common.c" #include "BaseModules.c" //----------------------------------------------------------------------------- // WinMain() // Main routine for the executable in Windows. //----------------------------------------------------------------------------- int WINAPI WinMain( HINSTANCE instance, // handle to application HINSTANCE prevInstance, // previous handle to application LPSTR commandLine, // command line int showFlag) // show flag { #if PY_MAJOR_VERSION >= 3 char fileName[MAXPATHLEN + 1]; wchar_t **wargv, *wfileName; int i, size; #else const char *fileName; #endif int status; // initialize Python Py_NoSiteFlag = 1; Py_FrozenFlag = 1; Py_IgnoreEnvironmentFlag = 1; PyImport_FrozenModules = gFrozenModules; #if PY_MAJOR_VERSION >= 3 setlocale(LC_CTYPE, ""); Py_SetPythonHome(L""); wargv = PyMem_Malloc(sizeof(wchar_t*) * __argc); if (!wargv) return 2; for (i = 0; i < __argc; i++) { size = strlen(__argv[i]); wargv[i] = PyMem_Malloc(sizeof(wchar_t) * (size + 1)); if (!wargv[i]) return 2; mbstowcs(wargv[i], __argv[i], size + 1); } Py_SetProgramName(wargv[0]); wfileName = Py_GetProgramFullPath(); wcstombs(fileName, wfileName, MAXPATHLEN); Py_Initialize(); PySys_SetArgv(__argc, wargv); #else Py_SetPythonHome(""); Py_SetProgramName(__argv[0]); fileName = Py_GetProgramFullPath(); Py_Initialize(); PySys_SetArgv(__argc, __argv); #endif // do the work status = 0; if (ExecuteScript(fileName) < 0) status = 1; // terminate Python Py_Finalize(); return status; } cx_Freeze-4.3.1/source/bases/Common.c0000664000076600012760000002623512000121626014353 0ustar //----------------------------------------------------------------------------- // Common.c // Routines which are common to running frozen executables. //----------------------------------------------------------------------------- #include #include #include // define macro for converting a C string to a Python string (Unicode for 3.x) #if PY_MAJOR_VERSION >= 3 #define cxString_FromStringAndSize(str, size) \ PyUnicode_Decode(str, size, Py_FileSystemDefaultEncoding, NULL) #define cxString_FromString(str) \ PyUnicode_Decode(str, strlen(str), Py_FileSystemDefaultEncoding, \ NULL) #else #define cxString_FromStringAndSize(str, size) \ PyString_FromStringAndSize(str, size); #define cxString_FromString(str) \ PyString_FromString(str) #endif // global variables (used for simplicity) static PyObject *g_FileName = NULL; static PyObject *g_DirName = NULL; static PyObject *g_ExclusiveZipFileName = NULL; static PyObject *g_SharedZipFileName = NULL; static PyObject *g_InitScriptZipFileName = NULL; //----------------------------------------------------------------------------- // cxString_ToString() // Convert an object to a C string. //----------------------------------------------------------------------------- static int cxString_ToString( PyObject *obj, // object to convert to C string PyObject **encodedObj, // encoded object const char **str) // C string { #if PY_MAJOR_VERSION >= 3 *encodedObj = PyUnicode_AsEncodedString(obj, Py_FileSystemDefaultEncoding, NULL); if (!*encodedObj) return FatalError("unable to encode string"); *str = PyBytes_AS_STRING(*encodedObj); #else Py_INCREF(obj); *encodedObj = obj; *str = PyString_AS_STRING(obj); #endif return 0; } //----------------------------------------------------------------------------- // GetDirName() // Return the directory name of the given path. //----------------------------------------------------------------------------- static int GetDirName( const char *path, // path to calculate dir name for PyObject **dirName) // directory name (OUT) { size_t i; for (i = strlen(path); i > 0 && path[i] != SEP; --i); *dirName = cxString_FromStringAndSize(path, i); if (!*dirName) return FatalError("cannot create string for directory name"); return 0; } //----------------------------------------------------------------------------- // SetExecutableName() // Set the script to execute and calculate the directory in which the // executable is found as well as the exclusive (only for this executable) and // shared zip file names. //----------------------------------------------------------------------------- static int SetExecutableName( const char *fileName) // script to execute { char temp[MAXPATHLEN + 12], *ptr; const char *tempStr = NULL; PyObject *encodedObj; #ifndef MS_WINDOWS char linkData[MAXPATHLEN + 1]; struct stat statData; size_t linkSize, i; PyObject *dirName; #endif // store file name g_FileName = cxString_FromString(fileName); if (!g_FileName) return FatalError("cannot create string for file name"); #ifndef MS_WINDOWS for (i = 0; i < 25; i++) { if (cxString_ToString(g_FileName, &encodedObj, &fileName) < 0) return -1; if (lstat(fileName, &statData) < 0) { PyErr_SetFromErrnoWithFilename(PyExc_OSError, (char*) fileName); return FatalError("unable to stat file"); } if (!S_ISLNK(statData.st_mode)) break; linkSize = readlink(fileName, linkData, sizeof(linkData)); if (linkSize < 0) { PyErr_SetFromErrnoWithFilename(PyExc_OSError, (char*) fileName); return FatalError("unable to stat file"); } Py_DECREF(encodedObj); if (linkData[0] == '/') { Py_DECREF(g_FileName); g_FileName = cxString_FromStringAndSize(linkData, linkSize); } else { if (cxString_ToString(g_FileName, &encodedObj, &fileName) < 0) return -1; if (GetDirName(fileName, &dirName) < 0) { Py_DECREF(encodedObj); return -1; } Py_DECREF(encodedObj); if (cxString_ToString(dirName, &encodedObj, &tempStr) < 0) return -1; if (strlen(tempStr) + linkSize + 1 > MAXPATHLEN) { Py_DECREF(dirName); Py_DECREF(encodedObj); return FatalError("cannot dereference link, path too large"); } strcpy(temp, tempStr); Py_DECREF(encodedObj); strcat(temp, "/"); strncat(temp, linkData, linkSize); Py_DECREF(g_FileName); g_FileName = cxString_FromString(temp); } if (!g_FileName) return FatalError("cannot create string for linked file name"); } #endif // calculate and store directory name if (GetDirName(fileName, &g_DirName) < 0) return -1; // calculate and store exclusive zip file name strcpy(temp, fileName); ptr = temp + strlen(temp) - 1; while (ptr > temp && *ptr != SEP && *ptr != '.') ptr--; if (*ptr == '.') *ptr = '\0'; strcat(temp, ".zip"); g_ExclusiveZipFileName = cxString_FromString(temp); if (!g_ExclusiveZipFileName) return FatalError("cannot create string for exclusive zip file name"); // calculate and store shared zip file name if (cxString_ToString(g_DirName, &encodedObj, &tempStr) < 0) return -1; strcpy(temp, tempStr); Py_DECREF(encodedObj); ptr = temp + strlen(temp); *ptr++ = SEP; strcpy(ptr, "library.zip"); g_SharedZipFileName = cxString_FromString(temp); if (!g_SharedZipFileName) return FatalError("cannot create string for shared zip file name"); return 0; } //----------------------------------------------------------------------------- // SetPathToSearch() // Set the path to search. This includes the file (for those situations where // a zip file is attached to the executable itself), the directory where the // executable is found (to search for extensions), the exclusive zip file // name and the shared zip file name. //----------------------------------------------------------------------------- static int SetPathToSearch(void) { PyObject *pathList; pathList = PySys_GetObject("path"); if (!pathList) return FatalError("cannot acquire sys.path"); if (PyList_Insert(pathList, 0, g_FileName) < 0) return FatalError("cannot insert file name into sys.path"); if (PyList_Insert(pathList, 1, g_DirName) < 0) return FatalError("cannot insert directory name into sys.path"); if (PyList_Insert(pathList, 2, g_ExclusiveZipFileName) < 0) return FatalError("cannot insert exclusive zip name into sys.path"); if (PyList_Insert(pathList, 3, g_SharedZipFileName) < 0) return FatalError("cannot insert shared zip name into sys.path"); return 0; } //----------------------------------------------------------------------------- // GetImporterHelper() // Helper which is used to locate the importer for the initscript. //----------------------------------------------------------------------------- static PyObject *GetImporterHelper( PyObject *module, // zipimport module PyObject *fileName) // name of file to search { PyObject *importer; importer = PyObject_CallMethod(module, "zipimporter", "O", fileName); if (importer) g_InitScriptZipFileName = fileName; else PyErr_Clear(); return importer; } //----------------------------------------------------------------------------- // GetImporter() // Return the importer which will be used for importing the initialization // script. The executable itself is searched first, followed by the exclusive // zip file and finally by the shared zip file. //----------------------------------------------------------------------------- static int GetImporter( PyObject **importer) // importer (OUT) { PyObject *module; module = PyImport_ImportModule("zipimport"); if (!module) return FatalError("cannot import zipimport module"); *importer = GetImporterHelper(module, g_FileName); if (!*importer) { *importer = GetImporterHelper(module, g_ExclusiveZipFileName); if (!*importer) *importer = GetImporterHelper(module, g_SharedZipFileName); } Py_DECREF(module); if (!*importer) return FatalError("cannot get zipimporter instance"); return 0; } //----------------------------------------------------------------------------- // PopulateInitScriptDict() // Return the dictionary used by the initialization script. //----------------------------------------------------------------------------- static int PopulateInitScriptDict( PyObject *dict) // dictionary to populate { if (!dict) return FatalError("unable to create temporary dictionary"); if (PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins()) < 0) return FatalError("unable to set __builtins__"); if (PyDict_SetItemString(dict, "FILE_NAME", g_FileName) < 0) return FatalError("unable to set FILE_NAME"); if (PyDict_SetItemString(dict, "DIR_NAME", g_DirName) < 0) return FatalError("unable to set DIR_NAME"); if (PyDict_SetItemString(dict, "EXCLUSIVE_ZIP_FILE_NAME", g_ExclusiveZipFileName) < 0) return FatalError("unable to set EXCLUSIVE_ZIP_FILE_NAME"); if (PyDict_SetItemString(dict, "SHARED_ZIP_FILE_NAME", g_SharedZipFileName) < 0) return FatalError("unable to set SHARED_ZIP_FILE_NAME"); if (PyDict_SetItemString(dict, "INITSCRIPT_ZIP_FILE_NAME", g_InitScriptZipFileName) < 0) return FatalError("unable to set INITSCRIPT_ZIP_FILE_NAME"); return 0; } //----------------------------------------------------------------------------- // ExecuteScript() // Execute the script found within the file. //----------------------------------------------------------------------------- static int ExecuteScript( const char *fileName) // name of file containing Python code { PyObject *importer, *dict, *code, *temp; if (SetExecutableName(fileName) < 0) return -1; if (SetPathToSearch() < 0) return -1; importer = NULL; if (GetImporter(&importer) < 0) return -1; // create and populate dictionary for initscript module dict = PyDict_New(); if (PopulateInitScriptDict(dict) < 0) { Py_XDECREF(dict); Py_DECREF(importer); return -1; } // locate and execute script code = PyObject_CallMethod(importer, "get_code", "s", "cx_Freeze__init__"); Py_DECREF(importer); if (!code) return FatalError("unable to locate initialization module"); temp = PyEval_EvalCode( (PyCodeObject*) code, dict, dict); Py_DECREF(code); Py_DECREF(dict); if (!temp) return FatalScriptError(); Py_DECREF(temp); return 0; } cx_Freeze-4.3.1/source/bases/Win32Service.c0000664000076600012760000005424412000121627015350 0ustar //----------------------------------------------------------------------------- // Win32Service.c // Base executable for handling Windows services. //----------------------------------------------------------------------------- #include #include #include #include // define constants #define CX_LOGGING_SECTION_NAME "Logging" #define CX_LOGGING_FILE_NAME_KEY "FileName" #define CX_LOGGING_LEVEL_KEY "Level" #define CX_LOGGING_MAX_FILES_KEY "MaxFiles" #define CX_LOGGING_MAX_FILE_SIZE_KEY "MaxFileSize" #define CX_LOGGING_PREFIX_KEY "Prefix" #define CX_SERVICE_MODULE_NAME "MODULE_NAME" #define CX_SERVICE_CLASS_NAME "CLASS_NAME" #define CX_SERVICE_NAME "NAME" #define CX_SERVICE_DISPLAY_NAME "DISPLAY_NAME" #define CX_SERVICE_DESCRIPTION "DESCRIPTION" #define CX_SERVICE_AUTO_START "AUTO_START" #define CX_SERVICE_SESSION_CHANGES "SESSION_CHANGES" // the following was copied from cx_Interface.c, which is where this // declaration normally happens #ifndef PATH_MAX #define PATH_MAX _MAX_PATH #endif //define structure for holding information about the service typedef struct { PyObject *cls; PyObject *nameFormat; PyObject *displayNameFormat; PyObject *description; DWORD startType; int sessionChanges; } udt_ServiceInfo; // define globals static HANDLE gControlEvent = NULL; static SERVICE_STATUS_HANDLE gServiceHandle; static PyInterpreterState *gInterpreterState = NULL; static PyObject *gInstance = NULL; static char gIniFileName[PATH_MAX + 1]; //----------------------------------------------------------------------------- // FatalError() // Called when an attempt to initialize the module zip fails. //----------------------------------------------------------------------------- static int FatalError( const char *message) // message to print { return LogPythonException(message); } //----------------------------------------------------------------------------- // FatalScriptError() // Called when an attempt to import the initscript fails. //----------------------------------------------------------------------------- static int FatalScriptError(void) { return LogPythonException("initialization script didn't execute properly"); } #include "Common.c" #include "BaseModules.c" //----------------------------------------------------------------------------- // Service_SetStatus() // Set the status for the service. //----------------------------------------------------------------------------- static int Service_SetStatus( udt_ServiceInfo* info, // service information DWORD status) // status to set { SERVICE_STATUS serviceStatus; serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; serviceStatus.dwCurrentState = status; serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP; if (info->sessionChanges) serviceStatus.dwControlsAccepted |= SERVICE_ACCEPT_SESSIONCHANGE; serviceStatus.dwWin32ExitCode = 0; serviceStatus.dwServiceSpecificExitCode = 0; serviceStatus.dwCheckPoint = 0; serviceStatus.dwWaitHint = 0; if (!SetServiceStatus(gServiceHandle, &serviceStatus)) return -1; return 0; } //----------------------------------------------------------------------------- // Service_Stop() // Stop the service. Note that the controlling thread must be ended before // the main thread is ended or the control GUI does not understand that the // service has ended. //----------------------------------------------------------------------------- static int Service_Stop( udt_ServiceInfo* info) // service information { PyThreadState *threadState; PyObject *result; // indicate that the service is being stopped if (Service_SetStatus(info, SERVICE_STOP_PENDING) < 0) return LogWin32Error(GetLastError(), "cannot set service as stopping"); // create event for the main thread to wait on for the control thread gControlEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (!gControlEvent) return LogWin32Error(GetLastError(), "cannot create control event"); // create a new Python thread and acquire the global interpreter lock threadState = PyThreadState_New(gInterpreterState); if (!threadState) return LogPythonException("unable to create new thread state"); PyEval_AcquireThread(threadState); // call the "Stop" method result = PyObject_CallMethod(gInstance, "Stop", NULL); if (!result) return LogPythonException("exception calling Stop method"); Py_DECREF(result); // destroy the Python thread and release the global interpreter lock PyThreadState_Clear(threadState); PyEval_ReleaseThread(threadState); PyThreadState_Delete(threadState); // indicate that the service has stopped if (Service_SetStatus(info, SERVICE_STOPPED) < 0) return LogWin32Error(GetLastError(), "cannot set service as stopped"); // now set the control event if (!SetEvent(gControlEvent)) return LogWin32Error(GetLastError(), "cannot set control event"); return 0; } //----------------------------------------------------------------------------- // Service_SessionChange() // Called when a session has changed. //----------------------------------------------------------------------------- static int Service_SessionChange( DWORD sessionId, // session that has changed DWORD eventType) // event type { PyThreadState *threadState; PyObject *result; // create a new Python thread and acquire the global interpreter lock threadState = PyThreadState_New(gInterpreterState); if (!threadState) return LogPythonException("unable to create new thread state"); PyEval_AcquireThread(threadState); // call Python method result = PyObject_CallMethod(gInstance, "SessionChanged", "ii", sessionId, eventType); if (!result) return LogPythonException("exception calling SessionChanged method"); Py_DECREF(result); // destroy the Python thread and release the global interpreter lock PyThreadState_Clear(threadState); PyEval_ReleaseThread(threadState); PyThreadState_Delete(threadState); return 0; } //----------------------------------------------------------------------------- // Service_Control() // Function for controlling a service. Note that the controlling thread // must be ended before the main thread is ended or the control GUI does not // understand that the service has ended. //----------------------------------------------------------------------------- static DWORD WINAPI Service_Control( DWORD controlCode, // control code DWORD eventType, // event type LPVOID eventData, // event data LPVOID context) // context { udt_ServiceInfo *serviceInfo = (udt_ServiceInfo*) context; WTSSESSION_NOTIFICATION *sessionInfo; switch (controlCode) { case SERVICE_CONTROL_STOP: Service_Stop(serviceInfo); break; case SERVICE_CONTROL_SESSIONCHANGE: sessionInfo = (WTSSESSION_NOTIFICATION*) eventData; Service_SessionChange(sessionInfo->dwSessionId, eventType); break; } return NO_ERROR; } //----------------------------------------------------------------------------- // Service_StartLogging() // Initialize logging for the service. //----------------------------------------------------------------------------- static int Service_StartLogging( const char *fileName) // name of file for defaults { char defaultLogFileName[PATH_MAX + 1], logFileName[PATH_MAX + 1]; unsigned logLevel, maxFiles, maxFileSize; char *ptr, prefix[100]; size_t size; // determine the default log file name and ini file name ptr = strrchr(fileName, '.'); if (ptr) size = ptr - fileName; else size = strlen(fileName); strcpy(defaultLogFileName, fileName); strcpy(&defaultLogFileName[size], ".log"); if (strlen(gIniFileName) == 0) { strcpy(gIniFileName, fileName); strcpy(&gIniFileName[size], ".ini"); } // read the entries from the ini file logLevel = GetPrivateProfileInt(CX_LOGGING_SECTION_NAME, CX_LOGGING_LEVEL_KEY, LOG_LEVEL_ERROR, gIniFileName); GetPrivateProfileString(CX_LOGGING_SECTION_NAME, CX_LOGGING_FILE_NAME_KEY, defaultLogFileName, logFileName, sizeof(logFileName), gIniFileName); maxFiles = GetPrivateProfileInt(CX_LOGGING_SECTION_NAME, CX_LOGGING_MAX_FILES_KEY, 1, gIniFileName); maxFileSize = GetPrivateProfileInt(CX_LOGGING_SECTION_NAME, CX_LOGGING_MAX_FILE_SIZE_KEY, DEFAULT_MAX_FILE_SIZE, gIniFileName); GetPrivateProfileString(CX_LOGGING_SECTION_NAME, CX_LOGGING_PREFIX_KEY, "[%i] %d %t", prefix, sizeof(prefix), gIniFileName); // start the logging process return StartLogging(logFileName, logLevel, maxFiles, maxFileSize, prefix); } //----------------------------------------------------------------------------- // Service_SetupPython() // Setup Python usage for the service. //----------------------------------------------------------------------------- static int Service_SetupPython( char *programName, // name of the program (argv[0]) udt_ServiceInfo *info) // info about service (OUT) { PyObject *module, *serviceModule, *temp; PyThreadState *threadState; char *fileName; // initialize Python Py_NoSiteFlag = 1; Py_FrozenFlag = 1; Py_IgnoreEnvironmentFlag = 1; PyImport_FrozenModules = gFrozenModules; Py_SetPythonHome(""); Py_SetProgramName(programName); fileName = Py_GetProgramFullPath(); Py_Initialize(); // initialize logging if (Service_StartLogging(fileName) < 0) return -1; // ensure threading is initialized and interpreter state saved PyEval_InitThreads(); threadState = PyThreadState_Swap(NULL); if (!threadState) { LogMessage(LOG_LEVEL_ERROR, "cannot set up interpreter state"); Service_SetStatus(info, SERVICE_STOPPED); return -1; } gInterpreterState = threadState->interp; PyThreadState_Swap(threadState); // running base script LogMessage(LOG_LEVEL_DEBUG, "running base Python script"); if (ExecuteScript(fileName) < 0) return -1; // acquire the __main__ module module = PyImport_ImportModule("__main__"); if (!module) return LogPythonException("unable to import __main__"); // determine name to use for the service info->nameFormat = PyObject_GetAttrString(module, CX_SERVICE_NAME); if (!info->nameFormat) return LogPythonException("cannot locate service name"); // determine display name to use for the service info->displayNameFormat = PyObject_GetAttrString(module, CX_SERVICE_DISPLAY_NAME); if (!info->displayNameFormat) return LogPythonException("cannot locate service display name"); // determine description to use for the service (optional) info->description = PyObject_GetAttrString(module, CX_SERVICE_DESCRIPTION); if (!info->description) PyErr_Clear(); // determine if service should be automatically started (optional) info->startType = SERVICE_DEMAND_START; temp = PyObject_GetAttrString(module, CX_SERVICE_AUTO_START); if (!temp) PyErr_Clear(); else if (temp == Py_True) info->startType = SERVICE_AUTO_START; // determine if service should monitor session changes (optional) info->sessionChanges = 0; temp = PyObject_GetAttrString(module, CX_SERVICE_SESSION_CHANGES); if (!temp) PyErr_Clear(); else if (temp == Py_True) info->sessionChanges = 1; // import the module which implements the service temp = PyObject_GetAttrString(module, CX_SERVICE_MODULE_NAME); if (!temp) return LogPythonException("cannot locate service module name"); serviceModule = PyImport_Import(temp); Py_DECREF(temp); if (!serviceModule) return LogPythonException("cannot import service module"); // create an instance of the class which implements the service temp = PyObject_GetAttrString(module, CX_SERVICE_CLASS_NAME); if (!temp) return LogPythonException("cannot locate service class name"); info->cls = PyObject_GetAttr(serviceModule, temp); Py_DECREF(temp); if (!info->cls) return LogPythonException("cannot get class from service module"); return 0; } //----------------------------------------------------------------------------- // Service_Install() // Install the service with the given name. //----------------------------------------------------------------------------- static int Service_Install( char *programName, // name of program being run char *name, // name of service char *configFileName) // name of configuration file or NULL { PyObject *fullName, *displayName, *formatArgs, *command, *commandArgs; char fullPathConfigFileName[PATH_MAX + 1]; SC_HANDLE managerHandle, serviceHandle; SERVICE_DESCRIPTIONA sd; udt_ServiceInfo info; // set up Python if (Service_SetupPython(programName, &info) < 0) return -1; // determine name and display name to use for the service formatArgs = Py_BuildValue("(s)", name); if (!formatArgs) return LogPythonException("cannot create service name tuple"); fullName = PyString_Format(info.nameFormat, formatArgs); if (!fullName) return LogPythonException("cannot create service name"); displayName = PyString_Format(info.displayNameFormat, formatArgs); if (!displayName) return LogPythonException("cannot create display name"); // determine command to use for the service command = PyString_FromFormat("\"%s\"", Py_GetProgramFullPath()); if (!command) return LogPythonException("cannot create command"); if (configFileName) { if (!_fullpath(fullPathConfigFileName, configFileName, sizeof(fullPathConfigFileName))) return LogWin32Error(GetLastError(), "cannot calculate absolute path of config file name"); commandArgs = PyString_FromFormat(" \"%s\"", fullPathConfigFileName); if (!commandArgs) return LogPythonException("cannot create command args"); PyString_Concat(&command, commandArgs); if (!command) return LogPythonException("cannot append args to command"); } // open up service control manager managerHandle = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (!managerHandle) return LogWin32Error(GetLastError(), "cannot open service manager"); // create service serviceHandle = CreateService(managerHandle, PyString_AS_STRING(fullName), PyString_AS_STRING(displayName), SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, info.startType, SERVICE_ERROR_NORMAL, PyString_AS_STRING(command), NULL, NULL, NULL, NULL, NULL); if (!serviceHandle) return LogWin32Error(GetLastError(), "cannot create service"); // set the description of the service, if one was specified if (info.description) { sd.lpDescription = PyString_AS_STRING(info.description); if (!ChangeServiceConfig2(serviceHandle, SERVICE_CONFIG_DESCRIPTION, &sd)) return LogWin32Error(GetLastError(), "cannot set service description"); } // if the service is one that should be automatically started, start it if (info.startType == SERVICE_AUTO_START) { if (!StartService(serviceHandle, 0, NULL)) return LogWin32Error(GetLastError(), "cannot start service"); } // close the service handles CloseServiceHandle(serviceHandle); CloseServiceHandle(managerHandle); return 0; } //----------------------------------------------------------------------------- // Service_Uninstall() // Uninstall the service with the given name. //----------------------------------------------------------------------------- static int Service_Uninstall( char *programName, // name of program being run char *name) // name of service { SC_HANDLE managerHandle, serviceHandle; PyObject *fullName, *formatArgs; SERVICE_STATUS statusInfo; udt_ServiceInfo info; // set up Python if (Service_SetupPython(programName, &info) < 0) return -1; // determine name of the service formatArgs = Py_BuildValue("(s)", name); if (!formatArgs) return LogPythonException("cannot create service name tuple"); fullName = PyString_Format(info.nameFormat, formatArgs); if (!fullName) return LogPythonException("cannot create service name"); // open up service control manager managerHandle = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (!managerHandle) return LogWin32Error(GetLastError(), "cannot open service manager"); // create service serviceHandle = OpenService(managerHandle, PyString_AS_STRING(fullName), SERVICE_ALL_ACCESS); if (!serviceHandle) return LogWin32Error(GetLastError(), "cannot open service"); ControlService(serviceHandle, SERVICE_CONTROL_STOP, &statusInfo); if (!DeleteService(serviceHandle)) return LogWin32Error(GetLastError(), "cannot delete service"); CloseServiceHandle(serviceHandle); CloseServiceHandle(managerHandle); return 0; } //----------------------------------------------------------------------------- // Service_Run() // Initialize the service. //----------------------------------------------------------------------------- static int Service_Run( udt_ServiceInfo *info) // information about the service { PyObject *temp; // create an instance of the class which implements the service gInstance = PyObject_CallFunctionObjArgs(info->cls, NULL); if (!gInstance) return LogPythonException("cannot create instance of service class"); // initialize the instance implementing the service LogMessageV(LOG_LEVEL_DEBUG, "initializing with config file %s", gIniFileName); temp = PyObject_CallMethod(gInstance, "Initialize", "s", gIniFileName); if (!temp) return LogPythonException("failed to initialize instance properly"); Py_DECREF(temp); // run the service LogMessage(LOG_LEVEL_INFO, "starting up service"); if (Service_SetStatus(info, SERVICE_RUNNING) < 0) return LogWin32Error(GetLastError(), "cannot set service as started"); temp = PyObject_CallMethod(gInstance, "Run", NULL); if (!temp) return LogPythonException("exception running service"); Py_DECREF(temp); Py_DECREF(gInstance); gInstance = NULL; // ensure that the Python interpreter lock is NOT held as otherwise // waiting for events will take a considerable period of time! PyEval_SaveThread(); return 0; } //----------------------------------------------------------------------------- // Service_Main() // Main routine for the service. //----------------------------------------------------------------------------- static void WINAPI Service_Main( int argc, // number of arguments char **argv) // argument values { udt_ServiceInfo info; if (Service_SetupPython(argv[0], &info) < 0) return; // register the control function LogMessage(LOG_LEVEL_DEBUG, "registering control function"); gServiceHandle = RegisterServiceCtrlHandlerEx("", Service_Control, &info); if (!gServiceHandle) { LogWin32Error(GetLastError(), "cannot register service control handler"); return; } // run the service if (Service_Run(&info) < 0) { Service_SetStatus(&info, SERVICE_STOPPED); return; } // ensure that the main thread does not terminate before the control // thread does, as otherwise the service control mechanism does not // understand that the service has already ended if (gControlEvent) { if (WaitForSingleObject(gControlEvent, INFINITE) != WAIT_OBJECT_0) LogWin32Error(GetLastError(), "cannot wait for control thread to terminate"); // otherwise, the service terminated normally by some other means } else { LogMessage(LOG_LEVEL_INFO, "stopping service (internally)"); Service_SetStatus(&info, SERVICE_STOPPED); } } //----------------------------------------------------------------------------- // main() // Main routine for the service. //----------------------------------------------------------------------------- int main(int argc, char **argv) { char *configFileName = NULL; SERVICE_TABLE_ENTRY table[] = { { "", (LPSERVICE_MAIN_FUNCTION) Service_Main }, { NULL, NULL } }; gIniFileName[0] = '\0'; if (argc > 1) { if (stricmp(argv[1], "--install") == 0) { if (argc == 2) { fprintf(stderr, "Incorrect number of parameters.\n"); fprintf(stderr, "%s --install []", argv[0]); return 1; } if (argc > 3) configFileName = argv[3]; if (Service_Install(argv[0], argv[2], configFileName) < 0) { fprintf(stderr, "Service not installed. "); fprintf(stderr, "See log file for details."); return 1; } fprintf(stderr, "Service installed."); return 0; } else if (stricmp(argv[1], "--uninstall") == 0) { if (argc == 2) { fprintf(stderr, "Incorrect number of parameters.\n"); fprintf(stderr, "%s --uninstall ", argv[0]); return 1; } if (Service_Uninstall(argv[0], argv[2]) < 0) { fprintf(stderr, "Service not installed. "); fprintf(stderr, "See log file for details."); return 1; } fprintf(stderr, "Service uninstalled."); return 0; } strcpy(gIniFileName, argv[1]); } return StartServiceCtrlDispatcher(table); } cx_Freeze-4.3.1/source/bases/dummy.rc0000664000076600012760000000013211776175123014450 0ustar STRINGTABLE { 1, "Just to ensure that buggy EndUpdateResource doesn't fall over." } cx_Freeze-4.3.1/source/bases/manifest.txt0000664000076600012760000000171011776175123015341 0ustar cx_Freeze-4.3.1/source/bases/Console.c0000664000076600012760000000526412051340271014531 0ustar //----------------------------------------------------------------------------- // Console.c // Main routine for frozen programs which run in a console. //----------------------------------------------------------------------------- #include #include #ifdef MS_WINDOWS #include #endif // disable filename globbing on Windows #ifdef MS_WINDOWS int _CRT_glob = 0; #endif //----------------------------------------------------------------------------- // FatalError() // Prints a fatal error. //----------------------------------------------------------------------------- static int FatalError( const char *message) // message to print { PyErr_Print(); Py_FatalError(message); return -1; } //----------------------------------------------------------------------------- // FatalScriptError() // Prints a fatal error in the initialization script. //----------------------------------------------------------------------------- static int FatalScriptError(void) { PyErr_Print(); return -1; } #include "Common.c" #ifndef CX_FREEZE_KEEP_PATH #include "BaseModules.c" #endif //----------------------------------------------------------------------------- // main() // Main routine for frozen programs. //----------------------------------------------------------------------------- int main(int argc, char **argv) { #if PY_MAJOR_VERSION >= 3 char fileName[MAXPATHLEN + 1]; wchar_t **wargv, *wfileName; int i, size; #else const char *fileName; #endif int status; // initialize Python #ifndef CX_FREEZE_KEEP_PATH Py_NoSiteFlag = 1; Py_FrozenFlag = 1; Py_IgnoreEnvironmentFlag = 1; PyImport_FrozenModules = gFrozenModules; #endif #if PY_MAJOR_VERSION >= 3 setlocale(LC_CTYPE, ""); #ifndef CX_FREEZE_KEEP_PATH Py_SetPythonHome(L""); #endif wargv = PyMem_Malloc(sizeof(wchar_t*) * argc); if (!wargv) return 2; for (i = 0; i < argc; i++) { size = strlen(argv[i]); wargv[i] = PyMem_Malloc(sizeof(wchar_t) * (size + 1)); if (!wargv[i]) return 2; status = mbstowcs(wargv[i], argv[i], size + 1); if (status < 0) return 3; } Py_SetProgramName(wargv[0]); wfileName = Py_GetProgramFullPath(); wcstombs(fileName, wfileName, MAXPATHLEN); Py_Initialize(); PySys_SetArgv(argc, wargv); #else #ifndef CX_FREEZE_KEEP_PATH Py_SetPythonHome(""); #endif Py_SetProgramName(argv[0]); fileName = Py_GetProgramFullPath(); Py_Initialize(); PySys_SetArgv(argc, argv); #endif // do the work status = 0; if (ExecuteScript(fileName) < 0) status = 1; Py_Finalize(); return status; } cx_Freeze-4.3.1/cx_Freeze/0000755000000000000000000000000012053761025014042 5ustar rootrootcx_Freeze-4.3.1/cx_Freeze/finder.py0000664000076600012760000006251412050622734014130 0ustar """ Base class for finding modules. """ import dis import imp import marshal import opcode import os import pkgutil import sys import types import zipfile import cx_Freeze.hooks BUILD_LIST = opcode.opmap["BUILD_LIST"] INPLACE_ADD = opcode.opmap["INPLACE_ADD"] LOAD_CONST = opcode.opmap["LOAD_CONST"] IMPORT_NAME = opcode.opmap["IMPORT_NAME"] IMPORT_FROM = opcode.opmap["IMPORT_FROM"] IMPORT_STAR = opcode.opmap["IMPORT_STAR"] STORE_FAST = opcode.opmap["STORE_FAST"] STORE_NAME = opcode.opmap["STORE_NAME"] STORE_GLOBAL = opcode.opmap["STORE_GLOBAL"] STORE_OPS = (STORE_NAME, STORE_GLOBAL) __all__ = [ "Module", "ModuleFinder" ] class ModuleFinder(object): def __init__(self, includeFiles = None, excludes = [], path = None, replacePaths = None, copyDependentFiles = True, bootstrap = False, compress = True): self.includeFiles = includeFiles if includeFiles is None: self.includeFiles = [] self.excludes = dict.fromkeys(excludes) self.replacePaths = replacePaths if replacePaths is None: self.replacePaths = [] self.copyDependentFiles = copyDependentFiles self.compress = compress self.path = path or sys.path self.modules = [] self.aliases = {} self._modules = dict.fromkeys(excludes) self._builtinModules = dict.fromkeys(sys.builtin_module_names) self._badModules = {} self._zipFileEntries = {} self._zipFiles = {} cx_Freeze.hooks.initialize(self) initialExcludedModules = self.excludes.copy() self._AddBaseModules() if not bootstrap: self._ClearBaseModuleCode(initialExcludedModules) def _AddBaseModules(self): """Add the base modules to the finder. These are the modules that Python imports itself during initialization and, if not found, can result in behavior that differs from running from source; also include modules used within the bootstrap code""" self.ExcludeModule("cStringIO") self.ExcludeModule("doctest") self.ExcludeModule("getopt") self.ExcludeModule("logging") self.ExcludeModule("re") self.ExcludeModule("subprocess") self.IncludeModule("traceback") self.IncludeModule("warnings") self.IncludePackage("encodings") if sys.version_info[0] >= 3: self.IncludeModule("io") if sys.version_info[:2] >= (3, 3): self.AddAlias("_frozen_importlib", "importlib._bootstrap") self.IncludeModule("_frozen_importlib") if self.copyDependentFiles: self.IncludeModule("imp") self.IncludeModule("os") self.IncludeModule("sys") self.IncludeModule("zlib") def _AddModule(self, name): """Add a module to the list of modules but if one is already found, then return it instead; this is done so that packages can be handled properly.""" module = self._modules.get(name) if module is None: module = self._modules[name] = Module(name) self.modules.append(module) if name in self._badModules: del self._badModules[name] return module def _ClearBaseModuleCode(self, initialExcludedModules): """Clear the code for all of the base modules. This is done when not in bootstrap mode so that the base modules are not included in the zip file.""" for name in self.excludes: if name in initialExcludedModules: continue del self._modules[name] self.excludes = initialExcludedModules for module in self._modules.values(): if module is None: continue if module.code is not None: module.code = None module.file = None def _DetermineParent(self, caller): """Determine the parent to use when searching packages.""" if caller is not None: if caller.path is not None: return caller return self._GetParentByName(caller.name) def _EnsureFromList(self, caller, packageModule, fromList, deferredImports): """Ensure that the from list is satisfied. This is only necessary for package modules. If the package module has not been completely imported yet, defer the import until it has been completely imported in order to avoid spurious errors about missing modules.""" if packageModule.inImport and caller is not packageModule: deferredImports.append((caller, packageModule, fromList)) else: for name in fromList: if name in packageModule.globalNames: continue subModuleName = "%s.%s" % (packageModule.name, name) self._ImportModule(subModuleName, deferredImports, caller) def _FindModule(self, name, path, namespace): try: return imp.find_module(name, path) except ImportError: if namespace and name in sys.modules: module = sys.modules[name] info = ("", "", imp.PKG_DIRECTORY) return None, module.__path__[0], info if path is None: path = [] for location in path: if name in self._zipFileEntries: break if location in self._zipFiles: continue if os.path.isdir(location) or not zipfile.is_zipfile(location): self._zipFiles[location] = None continue zip = zipfile.ZipFile(location) for archiveName in zip.namelist(): baseName, ext = os.path.splitext(archiveName) if ext not in ('.pyc', '.pyo'): continue moduleName = ".".join(baseName.split("/")) if moduleName in self._zipFileEntries: continue self._zipFileEntries[moduleName] = (zip, archiveName) self._zipFiles[location] = None info = self._zipFileEntries.get(name) if info is not None: zip, archiveName = info fp = zip.read(archiveName) info = (".pyc", "rb", imp.PY_COMPILED) return fp, os.path.join(zip.filename, archiveName), info raise def _GetParentByName(self, name): """Return the parent module given the name of a module.""" pos = name.rfind(".") if pos > 0: parentName = name[:pos] return self._modules[parentName] def _ImportAllSubModules(self, module, deferredImports, recursive = True): """Import all sub modules to the given package.""" suffixes = [s[0] for s in imp.get_suffixes()] for path in module.path: try: fileNames = os.listdir(path) except os.error: continue for fileName in fileNames: fullName = os.path.join(path, fileName) if os.path.isdir(fullName): initFile = os.path.join(fullName, "__init__.py") if not os.path.exists(initFile): continue name = fileName else: # We need to run through these in order to correctly pick # up PEP 3149 library names (e.g. .cpython-32mu.so). for suffix in suffixes: if fileName.endswith(suffix): name = fileName[:-len(suffix)] break else: continue if name == "__init__": continue subModuleName = "%s.%s" % (module.name, name) subModule, returnError = \ self._InternalImportModule(subModuleName, deferredImports) if returnError and subModule is None: raise ImportError("No module named %r" % subModuleName) module.globalNames[name] = None if subModule.path and recursive: self._ImportAllSubModules(subModule, deferredImports, recursive) def _ImportDeferredImports(self, deferredImports, skipInImport = False): """Import any sub modules that were deferred, if applicable.""" while deferredImports: newDeferredImports = [] for caller, packageModule, subModuleNames in deferredImports: if packageModule.inImport and skipInImport: continue self._EnsureFromList(caller, packageModule, subModuleNames, newDeferredImports) deferredImports = newDeferredImports def _ImportModule(self, name, deferredImports, caller = None, relativeImportIndex = 0, namespace = False): """Attempt to find the named module and return it or None if no module by that name could be found.""" # absolute import (available in Python 2.5 and up) # the name given is the only name that will be searched if relativeImportIndex == 0: module, returnError = self._InternalImportModule(name, deferredImports, namespace = namespace) # old style relative import (only possibility in Python 2.4 and prior) # the name given is tried in all parents until a match is found and if # no match is found, the global namespace is searched elif relativeImportIndex < 0: parent = self._DetermineParent(caller) while parent is not None: fullName = "%s.%s" % (parent.name, name) module, returnError = self._InternalImportModule(fullName, deferredImports, namespace = namespace) if module is not None: parent.globalNames[name] = None return module parent = self._GetParentByName(parent.name) module, returnError = self._InternalImportModule(name, deferredImports, namespace = namespace) # new style relative import (available in Python 2.5 and up) # the index indicates how many levels to traverse and only that level # is searched for the named module elif relativeImportIndex > 0: parent = caller if parent.path is not None: relativeImportIndex -= 1 while parent is not None and relativeImportIndex > 0: parent = self._GetParentByName(parent.name) relativeImportIndex -= 1 if parent is None: module = None returnError = True elif not name: module = parent else: name = "%s.%s" % (parent.name, name) module, returnError = self._InternalImportModule(name, deferredImports, namespace = namespace) # if module not found, track that fact if module is None: if caller is None: raise ImportError("No module named %r" % name) self._RunHook("missing", name, caller) if returnError and name not in caller.ignoreNames: callers = self._badModules.setdefault(name, {}) callers[caller.name] = None return module def _InternalImportModule(self, name, deferredImports, namespace = False): """Internal method used for importing a module which assumes that the name given is an absolute name. None is returned if the module cannot be found.""" try: return self._modules[name], False except KeyError: pass if name in self._builtinModules: module = self._AddModule(name) self._RunHook("load", module.name, module) module.inImport = False return module, False pos = name.rfind(".") if pos < 0: path = self.path searchName = name parentModule = None else: parentName = name[:pos] parentModule, returnError = \ self._InternalImportModule(parentName, deferredImports, namespace = namespace) if parentModule is None: return None, returnError if namespace: parentModule.ExtendPath() path = parentModule.path searchName = name[pos + 1:] if name in self.aliases: actualName = self.aliases[name] module, returnError = \ self._InternalImportModule(actualName, deferredImports) self._modules[name] = module return module, returnError try: fp, path, info = self._FindModule(searchName, path, namespace) module = self._LoadModule(name, fp, path, info, deferredImports, parentModule, namespace) except ImportError: self._modules[name] = None return None, True return module, False def _LoadModule(self, name, fp, path, info, deferredImports, parent = None, namespace = False): """Load the module, given the information acquired by the finder.""" suffix, mode, type = info if type == imp.PKG_DIRECTORY: return self._LoadPackage(name, path, parent, deferredImports, namespace) module = self._AddModule(name) module.file = path module.parent = parent if type == imp.PY_SOURCE: if sys.version_info[0] >= 3: import tokenize fp = open(path, "rb") encoding, lines = tokenize.detect_encoding(fp.readline) fp = open(path, "U", encoding = encoding) codeString = fp.read() if codeString and codeString[-1] != "\n": codeString = codeString + "\n" module.code = compile(codeString, path, "exec") elif type == imp.PY_COMPILED: if isinstance(fp, str): magic = fp[:4] else: magic = fp.read(4) if magic != imp.get_magic(): raise ImportError("Bad magic number in %s" % path) if isinstance(fp, str): module.code = marshal.loads(fp[8:]) module.inZipFile = True else: fp.read(4) module.code = marshal.load(fp) self._RunHook("load", module.name, module) if module.code is not None: if self.replacePaths: topLevelModule = module while topLevelModule.parent is not None: topLevelModule = topLevelModule.parent module.code = self._ReplacePathsInCode(topLevelModule, module.code) self._ScanCode(module.code, module, deferredImports) module.inImport = False return module def _LoadPackage(self, name, path, parent, deferredImports, namespace): """Load the package, given its name and path.""" module = self._AddModule(name) module.path = [path] try: fp, path, info = imp.find_module("__init__", module.path) self._LoadModule(name, fp, path, info, deferredImports, parent) except ImportError: if not namespace: raise fileName = os.path.join(path, "__init__.py") module.code = compile("", fileName, "exec") return module def _ReplacePathsInCode(self, topLevelModule, co): """Replace paths in the code as directed, returning a new code object with the modified paths in place.""" origFileName = newFileName = os.path.normpath(co.co_filename) for searchValue, replaceValue in self.replacePaths: if searchValue == "*": searchValue = os.path.dirname(topLevelModule.file) if topLevelModule.path: searchValue = os.path.dirname(searchValue) if searchValue: searchValue = searchValue + os.pathsep elif not origFileName.startswith(searchValue): continue newFileName = replaceValue + origFileName[len(searchValue):] break constants = list(co.co_consts) for i, value in enumerate(constants): if isinstance(value, type(co)): constants[i] = self._ReplacePathsInCode(topLevelModule, value) if sys.version_info[0] < 3: return types.CodeType(co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, tuple(constants), co.co_names, co.co_varnames, newFileName, co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars, co.co_cellvars) return types.CodeType(co.co_argcount, co.co_kwonlyargcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, tuple(constants), co.co_names, co.co_varnames, newFileName, co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars, co.co_cellvars) def _RunHook(self, hookName, moduleName, *args): """Run hook for the given module if one is present.""" name = "%s_%s" % (hookName, moduleName.replace(".", "_")) method = getattr(cx_Freeze.hooks, name, None) if method is not None: method(self, *args) def _ScanCode(self, co, module, deferredImports, topLevel = True): """Scan code, looking for imported modules and keeping track of the constants that have been created in order to better tell which modules are truly missing.""" opIndex = 0 arguments = [] code = co.co_code numOps = len(code) is3 = sys.version_info[0] >= 3 while opIndex < numOps: if is3: op = code[opIndex] else: op = ord(code[opIndex]) opIndex += 1 if op >= dis.HAVE_ARGUMENT: if is3: opArg = code[opIndex] + code[opIndex + 1] * 256 else: opArg = ord(code[opIndex]) + ord(code[opIndex + 1]) * 256 opIndex += 2 if op == LOAD_CONST: arguments.append(co.co_consts[opArg]) elif op == IMPORT_NAME: name = co.co_names[opArg] if len(arguments) == 2: relativeImportIndex, fromList = arguments else: relativeImportIndex = -1 fromList, = arguments if name not in module.excludeNames: importedModule = self._ImportModule(name, deferredImports, module, relativeImportIndex) if importedModule is not None: if fromList and fromList != ("*",) \ and importedModule.path is not None: self._EnsureFromList(module, importedModule, fromList, deferredImports) elif op == IMPORT_FROM and topLevel: if is3: op = code[opIndex] opArg = code[opIndex + 1] + code[opIndex + 2] * 256 else: op = ord(code[opIndex]) opArg = ord(code[opIndex + 1]) + \ ord(code[opIndex + 2]) * 256 opIndex += 3 if op == STORE_FAST: name = co.co_varnames[opArg] else: name = co.co_names[opArg] storeName = True if deferredImports: deferredCaller, deferredPackage, deferredFromList = \ deferredImports[-1] storeName = deferredCaller is not module if storeName: module.globalNames[name] = None elif op == IMPORT_STAR and topLevel and importedModule is not None: module.globalNames.update(importedModule.globalNames) arguments = [] elif op not in (BUILD_LIST, INPLACE_ADD): if topLevel and op in STORE_OPS: name = co.co_names[opArg] module.globalNames[name] = None arguments = [] for constant in co.co_consts: if isinstance(constant, type(co)): self._ScanCode(constant, module, deferredImports, topLevel = False) def AddAlias(self, name, aliasFor): """Add an alias for a particular module; when an attempt is made to import a module using the alias name, import the actual name instead.""" self.aliases[name] = aliasFor def ExcludeModule(self, name): """Exclude the named module from the resulting frozen executable.""" self.excludes[name] = None self._modules[name] = None def IncludeFile(self, path, moduleName = None): """Include the named file as a module in the frozen executable.""" name, ext = os.path.splitext(os.path.basename(path)) if moduleName is None: moduleName = name info = (ext, "r", imp.PY_SOURCE) deferredImports = [] module = self._LoadModule(moduleName, open(path, "U"), path, info, deferredImports) self._ImportDeferredImports(deferredImports) return module def IncludeFiles(self, sourcePath, targetPath): """Include the files in the given directory in the target build.""" if self.copyDependentFiles: self.includeFiles.append((sourcePath, targetPath)) def IncludeModule(self, name, namespace = False): """Include the named module in the frozen executable.""" deferredImports = [] module = self._ImportModule(name, deferredImports, namespace = namespace) self._ImportDeferredImports(deferredImports, skipInImport = True) return module def IncludePackage(self, name): """Include the named package and any submodules in the frozen executable.""" deferredImports = [] module = self._ImportModule(name, deferredImports) if module.path: self._ImportAllSubModules(module, deferredImports) self._ImportDeferredImports(deferredImports, skipInImport = True) return module def ReportMissingModules(self): if self._badModules: sys.stdout.write("Missing modules:\n") names = list(self._badModules.keys()) names.sort() for name in names: callers = list(self._badModules[name].keys()) callers.sort() sys.stdout.write("? %s imported from %s\n" % \ (name, ", ".join(callers))) sys.stdout.write("\n") def WriteSourceFile(self, fileName): dirName = os.path.dirname(fileName) if not os.path.isdir(dirName): os.makedirs(dirName) outfp = open(fileName, "w") names = list(self._modules.keys()) names.sort() modulesWritten = [] for name in names: module = self._modules[name] if module is None or module.code is None: continue mangledName = "__".join(name.split(".")) sys.stdout.write("adding base module named %s\n" % name) code = marshal.dumps(module.code) size = len(code) if module.path: size = -size modulesWritten.append((name, mangledName, size)) outfp.write("unsigned char M_%s[] = {" % mangledName) for i in range(0, len(code), 16): outfp.write("\n\t") for op in code[i:i + 16]: if not isinstance(op, int): op = ord(op) outfp.write("%d," % op) outfp.write("\n};\n\n"); outfp.write("static struct _frozen gFrozenModules[] = {\n") for name, mangledName, size in modulesWritten: outfp.write(' {"%s", M_%s, %d},\n' % (name, mangledName, size)) outfp.write(" {0, 0, 0}\n};\n") class Module(object): def __init__(self, name): self.name = name self.file = None self.path = None self.code = None self.parent = None self.globalNames = {} self.excludeNames = {} self.ignoreNames = {} self.inZipFile = False self.inImport = True def __repr__(self): parts = ["name=%s" % repr(self.name)] if self.file is not None: parts.append("file=%s" % repr(self.file)) if self.path is not None: parts.append("path=%s" % repr(self.path)) return "" % ", ".join(parts) def AddGlobalName(self, name): self.globalNames[name] = None def ExcludeName(self, name): self.excludeNames[name] = None def ExtendPath(self): self.path = pkgutil.extend_path(self.path, self.name) if self.parent is not None: self.parent.ExtendPath() def IgnoreName(self, name): self.ignoreNames[name] = None cx_Freeze-4.3.1/cx_Freeze/macdist.py0000664000076600012760000001574412035172135014306 0ustar from distutils.core import Command import distutils.errors import distutils.util import os import stat import subprocess __all__ = [ "bdist_dmg", "bdist_mac" ] PLIST_TEMPLATE = \ """ CFBundleIconFile %(bundle_iconfile)s CFBundleDevelopmentRegion English CFBundleExecutable %(bundle_executable)s """ class bdist_dmg(Command): description = "create a Mac DMG disk image containing the Mac " \ "application bundle" user_options = [ ('volume-label=', None, 'Volume label of the DMG disk image'), ] def initialize_options(self): self.volume_label = self.distribution.get_fullname() def finalize_options(self): pass def buildDMG(self): # Remove DMG if it already exists if os.path.exists(self.dmgName): os.unlink(self.dmgName) # Create the dmg if os.spawnlp(os.P_WAIT,'hdiutil','hdiutil','create','-fs','HFSX', '-format','UDZO',self.dmgName, '-imagekey', 'zlib-level=9', '-srcfolder',self.bundleDir,'-volname',self.volume_label)!=0: raise OSError('creation of the dmg failed') def run(self): # Create the application bundle self.run_command('bdist_mac') # Find the location of the application bundle and the build dir self.bundleDir = self.get_finalized_command('bdist_mac').bundleDir self.buildDir = self.get_finalized_command('build').build_base # Set the file name of the DMG to be built self.dmgName = os.path.join(self.buildDir, self.distribution.get_fullname() + '.dmg') self.execute(self.buildDMG,()) class bdist_mac(Command): description = "create a Mac application bundle" user_options = [ ('bundle-iconfile=', None, 'Name of the application bundle icon ' \ 'file as stored in the Info.plist file'), ('qt-menu-nib=', None, 'Location of qt_menu.nib folder for Qt ' \ 'applications. Will be auto-detected by default.') ] def initialize_options(self): self.bundle_iconfile = 'icon.icns' self.qt_menu_nib = False def finalize_options(self): pass def create_plist(self): """Create the Contents/Info.plist file""" plist = open(os.path.join(self.contentsDir, 'Info.plist'),'w') plist.write(PLIST_TEMPLATE % self.__dict__) plist.close() def setRelativeReferencePaths(self): """ For all files in Contents/MacOS, check if they are binaries with references to other files in that dir. If so, make those references relative. The appropriate commands are applied to all files; they will just fail for files on which they do not apply.""" files = os.listdir(self.binDir) for fileName in files: # install_name_tool can't handle zip files or directories filePath = os.path.join(self.binDir, fileName) if fileName.endswith('.zip') or os.path.isdir(filePath): continue # ensure write permissions mode = os.stat(filePath).st_mode if not (mode & stat.S_IWUSR): os.chmod(filePath, mode | stat.S_IWUSR) # let the file itself know its place subprocess.call(('install_name_tool', '-id', '@executable_path/' + fileName, filePath)) # find the references: call otool -L on the file otool = subprocess.Popen(('otool', '-L', filePath), stdout = subprocess.PIPE) references = otool.stdout.readlines()[1:] for reference in references: # find the actual referenced file name referencedFile = reference.decode().strip().split()[0] if referencedFile.startswith('@'): # the referencedFile is already a relative path continue path, name = os.path.split(referencedFile) # see if we provide the referenced file; # if so, change the reference if name in files: newReference = '@executable_path/' + name subprocess.call(('install_name_tool', '-change', referencedFile, newReference, filePath)) def find_qt_menu_nib(self): """Returns a location of a qt_menu.nib folder, or None if this is not a Qt application.""" if self.qt_menu_nib: return self.qt_menu_nib elif any(n.startswith("PyQt4.QtCore") \ for n in os.listdir(self.binDir)): from PyQt4 import QtCore elif any(n.startswith("PySide.QtCore") \ for n in os.listdir(self.binDir)): from PySide import QtCore else: return None libpath = str(QtCore.QLibraryInfo.location( \ QtCore.QLibraryInfo.LibrariesPath)) for subpath in ['QtGui.framework/Resources/qt_menu.nib', 'Resources/qt_menu.nib']: path = os.path.join(libpath, subpath) if os.path.exists(path): return path raise IOError("Could not find qt_menu.nib") def prepare_qt_app(self): """Add resource files for a Qt application. Should do nothing if the application does not use QtCore.""" nib_locn = self.find_qt_menu_nib() if nib_locn is None: return # Copy qt_menu.nib self.copy_tree(nib_locn, os.path.join(self.resourcesDir, 'qt_menu.nib')) # qt.conf needs to exist, but needn't have any content f = open(os.path.join(self.resourcesDir, 'qt.conf'), "w") f.close() def run(self): self.run_command('build') build = self.get_finalized_command('build') # Define the paths within the application bundle self.bundleDir = os.path.join(build.build_base, self.distribution.get_fullname() + ".app") self.contentsDir = os.path.join(self.bundleDir, 'Contents') self.resourcesDir = os.path.join(self.contentsDir, 'Resources') self.binDir = os.path.join(self.contentsDir, 'MacOS') #Find the executable name executable = self.distribution.executables[0].targetName _, self.bundle_executable=os.path.split(executable) # Build the app directory structure self.mkpath(self.resourcesDir) self.mkpath(self.binDir) self.copy_tree(build.build_exe, self.binDir) # Create the Info.plist file self.execute(self.create_plist,()) # Make all references to libraries relative self.execute(self.setRelativeReferencePaths,()) # For a Qt application, run some tweaks self.execute(self.prepare_qt_app, ()) cx_Freeze-4.3.1/cx_Freeze/__init__.py0000664000076600012760000000053712051100647014410 0ustar version = "4.3.1" import sys from cx_Freeze.dist import * if sys.platform == "win32" and sys.version_info[:2] >= (2, 5): from cx_Freeze.windist import * elif sys.platform == "darwin": from cx_Freeze.macdist import * from cx_Freeze.finder import * from cx_Freeze.freezer import * from cx_Freeze.main import * del dist del finder del freezer cx_Freeze-4.3.1/cx_Freeze/setupwriter.py0000664000076600012760000000664412000121625015244 0ustar import os import sys import subprocess if sys.version_info[0] < 3: input = raw_input class SetupWriter(object): bases = { "C" : "Console", "G" : "Win32GUI", "S" : "Win32Service" } @property def base(self): return self.bases[self.baseCode] @property def defaultExecutableName(self): name, ext = os.path.splitext(self.script) return name def __init__(self): self.name = self.description = self.script = "" self.executableName = self.defaultExecutableName self.setupFileName = "setup.py" self.version = "1.0" self.baseCode = "C" def GetBooleanValue(self, label, default = False): defaultResponse = default and "y" or "n" while True: response = self.GetValue(label, defaultResponse, separator = "? ").lower() if response in ("y", "n", "yes", "no"): break return response in ("y", "yes") def GetValue(self, label, default = "", separator = ": "): if default: label += " [%s]" % default return input(label + separator).strip() or default def PopulateFromCommandLine(self): self.name = self.GetValue("Project name", self.name) self.version = self.GetValue("Version", self.version) self.description = self.GetValue("Description", self.description) self.script = self.GetValue("Python file to make executable from", self.script) self.executableName = self.GetValue("Executable file name", self.defaultExecutableName) basesPrompt = "(C)onsole application, (G)UI application, or (S)ervice" while True: self.baseCode = self.GetValue(basesPrompt, "C") if self.baseCode in self.bases: break while True: self.setupFileName = self.GetValue("Save setup script to", self.setupFileName) if not os.path.exists(self.setupFileName): break if self.GetBooleanValue("Overwrite %s" % self.setupFileName): break def Write(self): output = open(self.setupFileName, "w") w = lambda s: output.write(s + "\n") w("from cx_Freeze import setup, Executable") w("") w("# Dependencies are automatically detected, but it might need") w("# fine tuning.") w("buildOptions = dict(packages = [], excludes = [])") w("") w("executables = [") if self.executableName != self.defaultExecutableName: w(" Executable(%r, %r, targetName = %r)" % \ (self.script, self.base, self.executableName)) else: w(" Executable(%r, %r)" % (self.script, self.base)) w("]") w("") w(("setup(name=%r,\n" " version = %r,\n" " description = %r,\n" " options = dict(build_exe = buildOptions),\n" " executables = executables)") % \ (self.name, self.version, self.description)) def main(): writer = SetupWriter() writer.PopulateFromCommandLine() writer.Write() print("") print("Setup script written to %s; run it as:" % writer.setupFileName) print(" python %s build" % writer.setupFileName) if writer.GetBooleanValue("Run this now"): subprocess.call(["python", writer.setupFileName, "build"]) cx_Freeze-4.3.1/cx_Freeze/dist.py0000664000076600012760000003353012053100320013601 0ustar import distutils.command.bdist_rpm import distutils.command.build import distutils.command.install import distutils.core import distutils.dir_util import distutils.dist import distutils.errors import distutils.log import distutils.util import distutils.version import os import sys import cx_Freeze __all__ = [ "bdist_rpm", "build", "build_exe", "install", "install_exe", "setup" ] class Distribution(distutils.dist.Distribution): def __init__(self, attrs): self.executables = [] distutils.dist.Distribution.__init__(self, attrs) class bdist_rpm(distutils.command.bdist_rpm.bdist_rpm): def finalize_options(self): distutils.command.bdist_rpm.bdist_rpm.finalize_options(self) self.use_rpm_opt_flags = 1 def _make_spec_file(self): contents = distutils.command.bdist_rpm.bdist_rpm._make_spec_file(self) contents.append('%define __prelink_undo_cmd %{nil}') return [c for c in contents if c != 'BuildArch: noarch'] class build(distutils.command.build.build): user_options = distutils.command.build.build.user_options + [ ('build-exe=', None, 'build directory for executables') ] def get_sub_commands(self): subCommands = distutils.command.build.build.get_sub_commands(self) if self.distribution.executables: subCommands.append("build_exe") return subCommands def initialize_options(self): distutils.command.build.build.initialize_options(self) self.build_exe = None def finalize_options(self): distutils.command.build.build.finalize_options(self) if self.build_exe is None: dirName = "exe.%s-%s" % \ (distutils.util.get_platform(), sys.version[0:3]) self.build_exe = os.path.join(self.build_base, dirName) class build_exe(distutils.core.Command): description = "build executables from Python scripts" user_options = [ ('build-exe=', 'b', 'directory for built executables'), ('optimize=', 'O', 'optimization level: -O1 for "python -O", ' '-O2 for "python -OO" and -O0 to disable [default: -O0]'), ('excludes=', 'e', 'comma-separated list of modules to exclude'), ('includes=', 'i', 'comma-separated list of modules to include'), ('packages=', 'p', 'comma-separated list of packages to include'), ('namespace-packages=', None, 'comma-separated list of namespace packages to include'), ('replace-paths=', None, 'comma-separated list of paths to replace in included modules'), ('path=', None, 'comma-separated list of paths to search'), ('init-script=', 'i', 'name of script to use during initialization'), ('base=', None, 'name of base executable to use'), ('compressed', 'c', 'create a compressed zipfile'), ('copy-dependent-files', None, 'copy all dependent files'), ('create-shared-zip', None, 'create a shared zip file containing shared modules'), ('append-script-to-exe', None, 'append the script module to the exe'), ('include-in-shared-zip', None, 'include the script module in the shared zip file'), ('icon', None, 'include the icon along with the frozen executable(s)'), ('constants=', None, 'comma-separated list of constants to include'), ('include-files=', 'f', 'list of tuples of additional files to include in distribution'), ('include-msvcr=', None, 'include the Microsoft Visual C runtime files'), ('zip-includes=', None, 'list of tuples of additional files to include in zip file'), ('bin-includes', None, 'list of names of files to include when determining dependencies'), ('bin-excludes', None, 'list of names of files to exclude when determining dependencies'), ('bin-path-includes', None, 'list of paths from which to include files when determining ' 'dependencies'), ('bin-path-excludes', None, 'list of paths from which to exclude files when determining ' 'dependencies'), ('silent', 's', 'suppress all output except warnings') ] boolean_options = ["compressed", "copy_dependent_files", "create_shared_zip", "append_script_to_exe", "include_in_shared_zip", "include_msvcr", "silent"] def _normalize(self, attrName): value = getattr(self, attrName) if value is None: normalizedValue = [] elif isinstance(value, str): normalizedValue = value.split() else: normalizedValue = list(value) setattr(self, attrName, normalizedValue) def add_to_path(self, name): sourceDir = getattr(self, name.lower()) if sourceDir is not None: sys.path.insert(0, sourceDir) def build_extension(self, name, moduleName = None): if moduleName is None: moduleName = name sourceDir = getattr(self, name.lower()) if sourceDir is None: return origDir = os.getcwd() scriptArgs = ["build"] command = self.distribution.get_command_obj("build") if command.compiler is not None: scriptArgs.append("--compiler=%s" % command.compiler) os.chdir(sourceDir) distutils.log.info("building '%s' extension in '%s'", name, sourceDir) distribution = distutils.core.run_setup("setup.py", scriptArgs) modules = [m for m in distribution.ext_modules if m.name == moduleName] if not modules: messageFormat = "no module named '%s' in '%s'" raise distutils.errors.DistutilsSetupError(messageFormat % (moduleName, sourceDir)) command = distribution.get_command_obj("build_ext") command.ensure_finalized() if command.compiler is None: command.run() else: command.build_extensions() dirName = os.path.join(sourceDir, command.build_lib) os.chdir(origDir) if dirName not in sys.path: sys.path.insert(0, dirName) return os.path.join(sourceDir, command.build_lib, command.get_ext_filename(moduleName)) def initialize_options(self): self.optimize = 0 self.build_exe = None self.excludes = [] self.includes = [] self.packages = [] self.namespace_packages = [] self.replace_paths = [] self.compressed = None self.copy_dependent_files = None self.init_script = None self.base = None self.path = None self.create_shared_zip = None self.append_script_to_exe = None self.include_in_shared_zip = None self.include_msvcr = None self.icon = None self.constants = [] self.include_files = [] self.zip_includes = [] self.bin_excludes = [] self.bin_includes = [] self.bin_path_includes = [] self.bin_path_excludes = [] self.silent = None def finalize_options(self): self.set_undefined_options('build', ('build_exe', 'build_exe')) self.optimize = int(self.optimize) if self.silent is None: self.silent = False self._normalize("excludes") self._normalize("includes") self._normalize("packages") self._normalize("namespace_packages") self._normalize("constants") def run(self): metadata = self.distribution.metadata constantsModule = cx_Freeze.ConstantsModule(metadata.version) for constant in self.constants: parts = constant.split("=") if len(parts) == 1: name = constant value = None else: name, stringValue = parts value = eval(stringValue) constantsModule.values[name] = value freezer = cx_Freeze.Freezer(self.distribution.executables, [constantsModule], self.includes, self.excludes, self.packages, self.replace_paths, self.compressed, self.optimize, self.copy_dependent_files, self.init_script, self.base, self.path, self.create_shared_zip, self.append_script_to_exe, self.include_in_shared_zip, self.build_exe, icon = self.icon, includeMSVCR = self.include_msvcr, includeFiles = self.include_files, binIncludes = self.bin_includes, binExcludes = self.bin_excludes, zipIncludes = self.zip_includes, silent = self.silent, namespacePackages = self.namespace_packages, binPathIncludes = self.bin_path_includes, binPathExcludes = self.bin_path_excludes, metadata = metadata) freezer.Freeze() def set_source_location(self, name, *pathParts): envName = "%s_BASE" % name.upper() attrName = name.lower() sourceDir = getattr(self, attrName) if sourceDir is None: baseDir = os.environ.get(envName) if baseDir is None: return sourceDir = os.path.join(baseDir, *pathParts) if os.path.isdir(sourceDir): setattr(self, attrName, sourceDir) class install(distutils.command.install.install): user_options = distutils.command.install.install.user_options + [ ('install-exe=', None, 'installation directory for executables') ] def expand_dirs(self): distutils.command.install.install.expand_dirs(self) self._expand_attrs(['install_exe']) def get_sub_commands(self): subCommands = distutils.command.install.install.get_sub_commands(self) if self.distribution.executables: subCommands.append("install_exe") return [s for s in subCommands if s != "install_egg_info"] def initialize_options(self): distutils.command.install.install.initialize_options(self) self.install_exe = None def finalize_options(self): if self.prefix is None and sys.platform == "win32": try: import winreg except: import _winreg as winreg key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows\CurrentVersion") prefix = str(winreg.QueryValueEx(key, "ProgramFilesDir")[0]) metadata = self.distribution.metadata self.prefix = "%s/%s" % (prefix, metadata.name) distutils.command.install.install.finalize_options(self) self.convert_paths('exe') if self.root is not None: self.change_roots('exe') def select_scheme(self, name): distutils.command.install.install.select_scheme(self, name) if self.install_exe is None: if sys.platform == "win32": self.install_exe = '$base' else: metadata = self.distribution.metadata dirName = "%s-%s" % (metadata.name, metadata.version) self.install_exe = '$base/lib/%s' % dirName class install_exe(distutils.core.Command): description = "install executables built from Python scripts" user_options = [ ('install-dir=', 'd', 'directory to install executables to'), ('build-dir=', 'b', 'build directory (where to install from)'), ('force', 'f', 'force installation (overwrite existing files)'), ('skip-build', None, 'skip the build steps') ] def initialize_options(self): self.install_dir = None self.force = 0 self.build_dir = None self.skip_build = None def finalize_options(self): self.set_undefined_options('build', ('build_exe', 'build_dir')) self.set_undefined_options('install', ('install_exe', 'install_dir'), ('force', 'force'), ('skip_build', 'skip_build')) def run(self): if not self.skip_build: self.run_command('build_exe') self.outfiles = self.copy_tree(self.build_dir, self.install_dir) if sys.platform != "win32": baseDir = os.path.dirname(os.path.dirname(self.install_dir)) binDir = os.path.join(baseDir, "bin") if not os.path.exists(binDir): os.makedirs(binDir) sourceDir = os.path.join("..", self.install_dir[len(baseDir) + 1:]) for executable in self.distribution.executables: name = os.path.basename(executable.targetName) source = os.path.join(sourceDir, name) target = os.path.join(binDir, name) if os.path.exists(target): os.unlink(target) os.symlink(source, target) self.outfiles.append(target) def get_inputs(self): return self.distribution.executables or [] def get_outputs(self): return self.outfiles or [] def _AddCommandClass(commandClasses, name, cls): if name not in commandClasses: commandClasses[name] = cls def setup(**attrs): attrs.setdefault("distclass", Distribution) commandClasses = attrs.setdefault("cmdclass", {}) if sys.platform == "win32": if sys.version_info[:2] >= (2, 5): _AddCommandClass(commandClasses, "bdist_msi", cx_Freeze.bdist_msi) elif sys.platform == "darwin": _AddCommandClass(commandClasses, "bdist_dmg", cx_Freeze.bdist_dmg) _AddCommandClass(commandClasses, "bdist_mac", cx_Freeze.bdist_mac) else: _AddCommandClass(commandClasses, "bdist_rpm", cx_Freeze.bdist_rpm) _AddCommandClass(commandClasses, "build", build) _AddCommandClass(commandClasses, "build_exe", build_exe) _AddCommandClass(commandClasses, "install", install) _AddCommandClass(commandClasses, "install_exe", install_exe) distutils.core.setup(**attrs) cx_Freeze-4.3.1/cx_Freeze/hooks.py0000664000076600012760000006205112000121625013764 0ustar import os import sys def initialize(finder): """upon initialization of the finder, this routine is called to set up some automatic exclusions for various platforms.""" finder.ExcludeModule("FCNTL") finder.ExcludeModule("os.path") if os.name == "nt": finder.ExcludeModule("fcntl") finder.ExcludeModule("grp") finder.ExcludeModule("pwd") finder.ExcludeModule("termios") else: finder.ExcludeModule("_subprocess") finder.ExcludeModule("_winreg") finder.ExcludeModule("msilib") finder.ExcludeModule("msvcrt") finder.ExcludeModule("multiprocessing._multiprocessing") finder.ExcludeModule("nt") if os.name not in ("os2", "ce"): finder.ExcludeModule("ntpath") finder.ExcludeModule("nturl2path") finder.ExcludeModule("pyHook") finder.ExcludeModule("pythoncom") finder.ExcludeModule("pywintypes") finder.ExcludeModule("winerror") finder.ExcludeModule("winsound") finder.ExcludeModule("win32api") finder.ExcludeModule("win32con") finder.ExcludeModule("win32gui") finder.ExcludeModule("win32event") finder.ExcludeModule("win32evtlog") finder.ExcludeModule("win32evtlogutil") finder.ExcludeModule("win32file") finder.ExcludeModule("win32pdh") finder.ExcludeModule("win32pipe") finder.ExcludeModule("win32process") finder.ExcludeModule("win32security") finder.ExcludeModule("win32service") finder.ExcludeModule("wx.activex") if os.name != "posix": finder.ExcludeModule("posix") if sys.platform != "darwin": finder.ExcludeModule("Carbon") finder.ExcludeModule("gestalt") finder.ExcludeModule("ic") finder.ExcludeModule("mac") finder.ExcludeModule("MacOS") finder.ExcludeModule("macostools") finder.ExcludeModule("macpath") finder.ExcludeModule("macurl2path") finder.ExcludeModule("_scproxy") if os.name != "nt": finder.ExcludeModule("EasyDialogs") if os.name != "os2": finder.ExcludeModule("os2") finder.ExcludeModule("os2emxpath") finder.ExcludeModule("_emx_link") if os.name != "ce": finder.ExcludeModule("ce") if os.name != "riscos": finder.ExcludeModule("riscos") finder.ExcludeModule("riscosenviron") finder.ExcludeModule("riscospath") finder.ExcludeModule("rourl2path") if sys.platform[:4] != "java": finder.ExcludeModule("java.lang") finder.ExcludeModule("org.python.core") if sys.platform[:4] != "OpenVMS": finder.ExcludeModule("vms_lib") if sys.version_info[0] >= 3: finder.ExcludeModule("new") finder.ExcludeModule("Tkinter") else: finder.ExcludeModule("tkinter") def load_cElementTree(finder, module): """the cElementTree module implicitly loads the elementtree.ElementTree module; make sure this happens.""" finder.IncludeModule("elementtree.ElementTree") def load_ceODBC(finder, module): """the ceODBC module implicitly imports both datetime and decimal; make sure this happens.""" finder.IncludeModule("datetime") finder.IncludeModule("decimal") def load_cx_Oracle(finder, module): """the cx_Oracle module implicitly imports datetime; make sure this happens.""" finder.IncludeModule("datetime") try: finder.IncludeModule("decimal") except ImportError: pass def load_datetime(finder, module): """the datetime module implicitly imports time; make sure this happens.""" finder.IncludeModule("time") def load_docutils_frontend(finder, module): """The optik module is the old name for the optparse module; ignore the module if it cannot be found.""" module.IgnoreName("optik") def load_dummy_threading(finder, module): """the dummy_threading module plays games with the name of the threading module for its own purposes; ignore that here""" finder.ExcludeModule("_dummy_threading") def load_email(finder, module): """the email package has a bunch of aliases as the submodule names were all changed to lowercase in Python 2.5; mimic that here.""" if sys.version_info[:2] >= (2, 5): for name in ("Charset", "Encoders", "Errors", "FeedParser", "Generator", "Header", "Iterators", "Message", "Parser", "Utils", "base64MIME", "quopriMIME"): finder.AddAlias("email.%s" % name, "email.%s" % name.lower()) def load_ftplib(finder, module): """the ftplib module attempts to import the SOCKS module; ignore this module if it cannot be found""" module.IgnoreName("SOCKS") def load_GifImagePlugin(finder, module): """The GifImagePlugin module optionally imports the _imaging_gif module""" module.IgnoreName("_imaging_gif") def load_glib(finder, module): """Ignore globals that are imported.""" module.AddGlobalName("GError") module.AddGlobalName("IOChannel") module.AddGlobalName("IO_ERR") module.AddGlobalName("IO_FLAG_APPEND") module.AddGlobalName("IO_FLAG_GET_MASK") module.AddGlobalName("IO_FLAG_IS_READABLE") module.AddGlobalName("IO_FLAG_IS_SEEKABLE") module.AddGlobalName("IO_FLAG_IS_WRITEABLE") module.AddGlobalName("IO_FLAG_MASK") module.AddGlobalName("IO_FLAG_NONBLOCK") module.AddGlobalName("IO_FLAG_SET_MASK") module.AddGlobalName("IO_HUP") module.AddGlobalName("IO_IN") module.AddGlobalName("IO_NVAL") module.AddGlobalName("IO_OUT") module.AddGlobalName("IO_PRI") module.AddGlobalName("IO_STATUS_AGAIN") module.AddGlobalName("IO_STATUS_EOF") module.AddGlobalName("IO_STATUS_ERROR") module.AddGlobalName("IO_STATUS_NORMAL") module.AddGlobalName("Idle") module.AddGlobalName("MainContext") module.AddGlobalName("MainLoop") module.AddGlobalName("OPTION_ERROR") module.AddGlobalName("OPTION_ERROR_BAD_VALUE") module.AddGlobalName("OPTION_ERROR_FAILED") module.AddGlobalName("OPTION_ERROR_UNKNOWN_OPTION") module.AddGlobalName("OPTION_FLAG_FILENAME") module.AddGlobalName("OPTION_FLAG_HIDDEN") module.AddGlobalName("OPTION_FLAG_IN_MAIN") module.AddGlobalName("OPTION_FLAG_NOALIAS") module.AddGlobalName("OPTION_FLAG_NO_ARG") module.AddGlobalName("OPTION_FLAG_OPTIONAL_ARG") module.AddGlobalName("OPTION_FLAG_REVERSE") module.AddGlobalName("OPTION_REMAINING") module.AddGlobalName("OptionContext") module.AddGlobalName("OptionGroup") module.AddGlobalName("PRIORITY_DEFAULT") module.AddGlobalName("PRIORITY_DEFAULT_IDLE") module.AddGlobalName("PRIORITY_HIGH") module.AddGlobalName("PRIORITY_HIGH_IDLE") module.AddGlobalName("PRIORITY_LOW") module.AddGlobalName("Pid") module.AddGlobalName("PollFD") module.AddGlobalName("SPAWN_CHILD_INHERITS_STDIN") module.AddGlobalName("SPAWN_DO_NOT_REAP_CHILD") module.AddGlobalName("SPAWN_FILE_AND_ARGV_ZERO") module.AddGlobalName("SPAWN_LEAVE_DESCRIPTORS_OPEN") module.AddGlobalName("SPAWN_SEARCH_PATH") module.AddGlobalName("SPAWN_STDERR_TO_DEV_NULL") module.AddGlobalName("SPAWN_STDOUT_TO_DEV_NULL") module.AddGlobalName("Source") module.AddGlobalName("Timeout") module.AddGlobalName("child_watch_add") module.AddGlobalName("filename_display_basename") module.AddGlobalName("filename_display_name") module.AddGlobalName("filename_from_utf8") module.AddGlobalName("get_application_name") module.AddGlobalName("get_current_time") module.AddGlobalName("get_prgname") module.AddGlobalName("glib_version") module.AddGlobalName("idle_add") module.AddGlobalName("io_add_watch") module.AddGlobalName("main_context_default") module.AddGlobalName("main_depth") module.AddGlobalName("markup_escape_text") module.AddGlobalName("set_application_name") module.AddGlobalName("set_prgname") module.AddGlobalName("source_remove") module.AddGlobalName("spawn_async") module.AddGlobalName("timeout_add") module.AddGlobalName("timeout_add_seconds") def load_gtk__gtk(finder, module): """the gtk._gtk module has a number of implicit imports""" finder.IncludeModule("atk") finder.IncludeModule("cairo") finder.IncludeModule("gio") finder.IncludeModule("pango") finder.IncludeModule("pangocairo") def load_matplotlib(finder, module): """the matplotlib module requires data to be found in mpl-data in the same directory as the frozen executable so oblige it""" dir = os.path.join(module.path[0], "mpl-data") finder.IncludeFiles(dir, "mpl-data") def load_matplotlib_numerix(finder, module): """the numpy.numerix module loads a number of modules dynamically""" for name in ("ma", "fft", "linear_algebra", "random_array", "mlab"): finder.IncludeModule("%s.%s" % (module.name, name)) def load_Numeric(finder, module): """the Numeric module optionally loads the dotblas module; ignore the error if this modules does not exist.""" module.IgnoreName("dotblas") def load_numpy_core_multiarray(finder, module): """the numpy.core.multiarray module is an extension module and the numpy module imports * from this module; define the list of global names available to this module in order to avoid spurious errors about missing modules""" module.AddGlobalName("arange") def load_numpy_core_numerictypes(finder, module): """the numpy.core.numerictypes module adds a number of items to itself dynamically; define these to avoid spurious errors about missing modules""" module.AddGlobalName("bool_") module.AddGlobalName("cdouble") module.AddGlobalName("complexfloating") module.AddGlobalName("csingle") module.AddGlobalName("double") module.AddGlobalName("float64") module.AddGlobalName("float_") module.AddGlobalName("inexact") module.AddGlobalName("intc") module.AddGlobalName("int32") module.AddGlobalName("number") module.AddGlobalName("single") def load_numpy_core_umath(finder, module): """the numpy.core.umath module is an extension module and the numpy module imports * from this module; define the list of global names available to this module in order to avoid spurious errors about missing modules""" module.AddGlobalName("add") module.AddGlobalName("absolute") module.AddGlobalName("arccos") module.AddGlobalName("arccosh") module.AddGlobalName("arcsin") module.AddGlobalName("arcsinh") module.AddGlobalName("arctan") module.AddGlobalName("arctanh") module.AddGlobalName("bitwise_and") module.AddGlobalName("bitwise_or") module.AddGlobalName("bitwise_xor") module.AddGlobalName("ceil") module.AddGlobalName("conj") module.AddGlobalName("conjugate") module.AddGlobalName("cosh") module.AddGlobalName("divide") module.AddGlobalName("fabs") module.AddGlobalName("floor") module.AddGlobalName("floor_divide") module.AddGlobalName("fmod") module.AddGlobalName("greater") module.AddGlobalName("hypot") module.AddGlobalName("invert") module.AddGlobalName("isfinite") module.AddGlobalName("isinf") module.AddGlobalName("isnan") module.AddGlobalName("less") module.AddGlobalName("left_shift") module.AddGlobalName("log") module.AddGlobalName("logical_and") module.AddGlobalName("logical_not") module.AddGlobalName("logical_or") module.AddGlobalName("logical_xor") module.AddGlobalName("maximum") module.AddGlobalName("minimum") module.AddGlobalName("multiply") module.AddGlobalName("negative") module.AddGlobalName("not_equal") module.AddGlobalName("power") module.AddGlobalName("remainder") module.AddGlobalName("right_shift") module.AddGlobalName("sign") module.AddGlobalName("sinh") module.AddGlobalName("sqrt") module.AddGlobalName("tan") module.AddGlobalName("tanh") module.AddGlobalName("true_divide") def load_numpy_distutils_command_scons(finder, module): """the numpy.distutils.command.scons module optionally imports the numscons module; ignore the error if the module cannot be found.""" module.IgnoreName("numscons") def load_numpy_distutils_misc_util(finder, module): """the numpy.distutils.misc_util module optionally imports the numscons module; ignore the error if the module cannot be found.""" module.IgnoreName("numscons") def load_numpy_distutils_system_info(finder, module): """the numpy.distutils.system_info module optionally imports the Numeric module; ignore the error if the module cannot be found.""" module.IgnoreName("Numeric") def load_numpy_f2py___version__(finder, module): """the numpy.f2py.__version__ module optionally imports the __svn_version__ module; ignore the error if the module cannot be found.""" module.IgnoreName("__svn_version__") def load_numpy_linalg(finder, module): """the numpy.linalg module implicitly loads the lapack_lite module; make sure this happens""" finder.IncludeModule("numpy.linalg.lapack_lite") def load_numpy_random_mtrand(finder, module): """the numpy.random.mtrand module is an extension module and the numpy module imports * from this module; define the list of global names available to this module in order to avoid spurious errors about missing modules""" module.AddGlobalName("rand") module.AddGlobalName("randn") def load_postgresql_lib(finder, module): """the postgresql.lib module requires the libsys.sql file to be included so make sure that file is included""" fileName = os.path.join(module.path[0], "libsys.sql") finder.IncludeFiles(fileName, os.path.basename(fileName)) def load_pty(finder, module): """The sgi module is not needed for this module to function.""" module.IgnoreName("sgi") def load_pydoc(finder, module): """The pydoc module will work without the Tkinter module so ignore the error if that module cannot be found.""" module.IgnoreName("Tkinter") def load_pythoncom(finder, module): """the pythoncom module is actually contained in a DLL but since those cannot be loaded directly in Python 2.5 and higher a special module is used to perform that task; simply use that technique directly to determine the name of the DLL and ensure it is included as a normal extension; also load the pywintypes module which is implicitly loaded.""" import pythoncom module.file = pythoncom.__file__ module.code = None finder.IncludeModule("pywintypes") def load_pywintypes(finder, module): """the pywintypes module is actually contained in a DLL but since those cannot be loaded directly in Python 2.5 and higher a special module is used to perform that task; simply use that technique directly to determine the name of the DLL and ensure it is included as a normal extension.""" import pywintypes module.file = pywintypes.__file__ module.code = None def load_PyQt4_phonon(finder, module): """In Windows, phonon4.dll requires an additional dll phonon_ds94.dll to be present in the build directory inside a folder phonon_backend.""" if sys.platform == "win32": dir = os.path.join(module.parent.path[0], "plugins", "phonon_backend") finder.IncludeFiles(dir, "phonon_backend") def load_PyQt4_QtCore(finder, module): """the PyQt4.QtCore module implicitly imports the sip module and, depending on configuration, the PyQt4._qt module.""" finder.IncludeModule("sip") try: finder.IncludeModule("PyQt4._qt") except ImportError: pass def load_PyQt4_Qt(finder, module): """the PyQt4.Qt module is an extension module which imports a number of other modules and injects their namespace into its own. It seems a foolish way of doing things but perhaps there is some hidden advantage to this technique over pure Python; ignore the absence of some of the modules since not every installation includes all of them.""" finder.IncludeModule("PyQt4.QtCore") finder.IncludeModule("PyQt4.QtGui") for name in ("PyQt4._qt", "PyQt4.QtSvg", "PyQt4.Qsci", "PyQt4.QtAssistant", "PyQt4.QtNetwork", "PyQt4.QtOpenGL", "PyQt4.QtScript", "PyQt4.QtSql", "PyQt4.QtSvg", "PyQt4.QtTest", "PyQt4.QtXml"): try: finder.IncludeModule(name) except ImportError: pass def load_PyQt4_uic(finder, module): """The uic module makes use of "plugins" that need to be read directly and cannot be frozen; the PyQt4.QtWebKit and PyQt4.QtNetwork modules are also implicity loaded.""" dir = os.path.join(module.path[0], "widget-plugins") finder.IncludeFiles(dir, "PyQt4.uic.widget-plugins") finder.IncludeModule("PyQt4.QtNetwork") finder.IncludeModule("PyQt4.QtWebKit") def load_scipy(finder, module): """the scipy module loads items within itself in a way that causes problems without the entire package and a number of other subpackages being present.""" finder.IncludePackage("scipy.lib") finder.IncludePackage("scipy.misc") def load_scipy_linalg(finder, module): """the scipy.linalg module loads items within itself in a way that causes problems without the entire package being present.""" module.AddGlobalName("norm") finder.IncludePackage("scipy.linalg") def load_scipy_linalg_interface_gen(finder, module): """the scipy.linalg.interface_gen module optionally imports the pre module; ignore the error if this module cannot be found""" module.IgnoreName("pre") def load_scipy_sparse_linalg_dsolve_linsolve(finder, module): """the scipy.linalg.dsolve.linsolve optionally loads scikits.umfpack""" module.IgnoreName("scikits.umfpack") def load_scipy_special__cephes(finder, module): """the scipy.special._cephes is an extension module and the scipy module imports * from it in places; advertise the global names that are used in order to avoid spurious errors about missing modules.""" module.AddGlobalName("gammaln") def load_setuptools_extension(finder, module): """the setuptools.extension module optionally loads Pyrex.Distutils.build_ext but its absence is not considered an error.""" module.IgnoreName("Pyrex.Distutils.build_ext") def load_site(finder, module): """the site module optionally loads the sitecustomize and usercustomize modules; ignore the error if these modules do not exist.""" module.IgnoreName("sitecustomize") module.IgnoreName("usercustomize") def load_tkinter(finder, module): """the tkinter module has data files that are required to be loaded so ensure that they are copied into the directory that is expected at runtime.""" if sys.platform == "win32": import tkinter import _tkinter tclSourceDir = os.environ["TCL_LIBRARY"] tkSourceDir = os.environ["TK_LIBRARY"] finder.IncludeFiles(tclSourceDir, "tcl") finder.IncludeFiles(tkSourceDir, "tk") def load_Tkinter(finder, module): """the Tkinter module has data files that are required to be loaded so ensure that they are copied into the directory that is expected at runtime.""" import Tkinter import _tkinter tk = _tkinter.create() tclDir = os.path.dirname(tk.call("info", "library")) # on OS X, Tcl and Tk are organized in frameworks, different layout if sys.platform == 'darwin' and tk.call('tk', 'windowingsystem') == 'aqua': tclSourceDir=os.path.join(os.path.split(tclDir)[0], 'Tcl') tkSourceDir = tclSourceDir.replace('Tcl', 'Tk') else: tclSourceDir = os.path.join(tclDir, "tcl%s" % _tkinter.TCL_VERSION) tkSourceDir = os.path.join(tclDir, "tk%s" % _tkinter.TK_VERSION) finder.IncludeFiles(tclSourceDir, "tcl") finder.IncludeFiles(tkSourceDir, "tk") def load_tempfile(finder, module): """the tempfile module attempts to load the fcntl and thread modules but continues if these modules cannot be found; ignore these modules if they cannot be found.""" module.IgnoreName("fcntl") module.IgnoreName("thread") def load_time(finder, module): """the time module implicitly loads _strptime; make sure this happens.""" finder.IncludeModule("_strptime") def load_twisted_conch_ssh_transport(finder, module): """the twisted.conch.ssh.transport module uses __import__ builtin to dynamically load different ciphers at runtime.""" finder.IncludePackage("Crypto.Cipher") def load_twitter(finder, module): """the twitter module tries to load the simplejson, json and django.utils module in an attempt to locate any module that will implement the necessary protocol; ignore these modules if they cannot be found.""" module.IgnoreName("json") module.IgnoreName("simplejson") module.IgnoreName("django.utils") def load_win32api(finder, module): """the win32api module implicitly loads the pywintypes module; make sure this happens.""" finder.IncludeModule("pywintypes") def load_win32com(finder, module): """the win32com package manipulates its search path at runtime to include the sibling directory called win32comext; simulate that by changing the search path in a similar fashion here.""" baseDir = os.path.dirname(os.path.dirname(module.file)) module.path.append(os.path.join(baseDir, "win32comext")) def load_win32file(finder, module): """the win32api module implicitly loads the pywintypes module; make sure this happens.""" finder.IncludeModule("pywintypes") def load_Xlib_display(finder, module): """the Xlib.display module implicitly loads a number of extension modules; make sure this happens.""" finder.IncludeModule("Xlib.ext.xtest") finder.IncludeModule("Xlib.ext.shape") finder.IncludeModule("Xlib.ext.xinerama") finder.IncludeModule("Xlib.ext.record") finder.IncludeModule("Xlib.ext.composite") finder.IncludeModule("Xlib.ext.randr") def load_Xlib_support_connect(finder, module): """the Xlib.support.connect module implicitly loads a platform specific module; make sure this happens.""" if sys.platform.split("-")[0] == "OpenVMS": moduleName = "vms_connect" else: moduleName = "unix_connect" finder.IncludeModule("Xlib.support.%s" % moduleName) def load_Xlib_XK(finder, module): """the Xlib.XK module implicitly loads some keysymdef modules; make sure this happens.""" finder.IncludeModule("Xlib.keysymdef.miscellany") finder.IncludeModule("Xlib.keysymdef.latin1") def load_xml(finder, module): """the builtin xml package attempts to load the _xmlplus module to see if that module should take its role instead; ignore the failure to find this module, though.""" module.IgnoreName("_xmlplus") def load_xml_etree_cElementTree(finder, module): """the xml.etree.cElementTree module implicitly loads the xml.etree.ElementTree module; make sure this happens.""" finder.IncludeModule("xml.etree.ElementTree") def load_xmlrpclib(finder, module): """the xmlrpclib optionally imports the _xmlrpclib and sgmlop modules; ignore the error if these modules cannot be found.""" module.IgnoreName("_xmlrpclib") module.IgnoreName("sgmlop") def load_zope(finder, module): """the zope package is distributed in multiple packages and they need to be stitched back together again.""" module.ExtendPath() def load_zope_component(finder, module): """the zope.component package requires the presence of the pkg_resources module but it uses a dynamic, not static import to do its work.""" finder.IncludeModule("pkg_resources") def missing_cElementTree(finder, caller): """the cElementTree has been incorporated into the standard library in Python 2.5 so ignore its absence if it cannot found.""" if sys.version_info[:2] >= (2, 5): caller.IgnoreName("cElementTree") def missing_EasyDialogs(finder, caller): """the EasyDialogs module is not normally present on Windows but it also may be so instead of excluding it completely, ignore it if it can't be found""" if sys.platform == "win32": caller.IgnoreName("EasyDialogs") def missing_gdk(finder, caller): """the gdk module is buried inside gtk so there is no need to concern ourselves with an error saying that it cannot be found""" caller.IgnoreName("gdk") def missing_ltihooks(finder, caller): """this module is not necessairly present so ignore it when it cannot be found""" caller.IgnoreName("ltihooks") def missing_readline(finder, caller): """the readline module is not normally present on Windows but it also may be so instead of excluding it completely, ignore it if it can't be found""" if sys.platform == "win32": caller.IgnoreName("readline") def missing_xml_etree(finder, caller): """the xml.etree package is new for Python 2.5 but it is common practice to use a try..except.. block in order to support versions earlier than Python 2.5 transparently; ignore the absence of the package in this situation.""" if sys.version_info[:2] < (2, 5): caller.IgnoreName("xml.etree") cx_Freeze-4.3.1/cx_Freeze/main.py0000664000076600012760000001732312053612113013574 0ustar import optparse import os import shutil import stat import sys import cx_Freeze __all__ = ["main"] USAGE = \ """ %prog [options] [SCRIPT] Freeze a Python script and all of its referenced modules to a base executable which can then be distributed without requiring a Python installation.""" VERSION = \ """ %%prog %s Copyright (c) 2007-2012 Anthony Tuininga. All rights reserved. Copyright (c) 2001-2006 Computronix Corporation. All rights reserved.""" % \ cx_Freeze.version def ParseCommandLine(): parser = optparse.OptionParser(version = VERSION.strip(), usage = USAGE.strip()) parser.add_option("-O", action = "count", default = 0, dest = "optimized", help = "optimize generated bytecode as per PYTHONOPTIMIZE; " "use -OO in order to remove doc strings") parser.add_option("-c", "--compress", action = "store_true", dest = "compress", help = "compress byte code in zip files") parser.add_option("-s", "--silent", action = "store_true", dest = "silent", help = "suppress all output except warnings and errors") parser.add_option("--base-name", dest = "baseName", metavar = "NAME", help = "file on which to base the target file; if the name of the " "file is not an absolute file name, the subdirectory bases " "(rooted in the directory in which the freezer is found) " "will be searched for a file matching the name") parser.add_option("--init-script", dest = "initScript", metavar = "NAME", help = "script which will be executed upon startup; if the name " "of the file is not an absolute file name, the " "subdirectory initscripts (rooted in the directory in " "which the cx_Freeze package is found) will be searched " "for a file matching the name") parser.add_option("--target-dir", "--install-dir", dest = "targetDir", metavar = "DIR", help = "the directory in which to place the target file and " "any dependent files") parser.add_option("--target-name", dest = "targetName", metavar = "NAME", help = "the name of the file to create instead of the base name " "of the script and the extension of the base binary") parser.add_option("--no-copy-deps", dest = "copyDeps", default = True, action = "store_false", help = "do not copy the dependent files (extensions, shared " "libraries, etc.) to the target directory; this also " "modifies the default init script to ConsoleKeepPath.py " "and means that the target executable requires a Python " "installation to execute properly") parser.add_option("--default-path", action = "append", dest = "defaultPath", metavar = "DIRS", help = "list of paths separated by the standard path separator " "for the platform which will be used to initialize " "sys.path prior to running the module finder") parser.add_option("--include-path", action = "append", dest = "includePath", metavar = "DIRS", help = "list of paths separated by the standard path separator " "for the platform which will be used to modify sys.path " "prior to running the module finder") parser.add_option("--replace-paths", dest = "replacePaths", metavar = "DIRECTIVES", help = "replace all the paths in modules found in the given paths " "with the given replacement string; multiple values are " "separated by the standard path separator and each value " "is of the form path=replacement_string; path can be * " "which means all paths not already specified") parser.add_option("--include-modules", dest = "includeModules", metavar = "NAMES", help = "comma separated list of modules to include") parser.add_option("--exclude-modules", dest = "excludeModules", metavar = "NAMES", help = "comma separated list of modules to exclude") parser.add_option("--ext-list-file", dest = "extListFile", metavar = "NAME", help = "name of file in which to place the list of dependent files " "which were copied into the target directory") parser.add_option("-z", "--zip-include", dest = "zipIncludes", action = "append", default = [], metavar = "SPEC", help = "name of file to add to the zip file or a specification of " "the form name=arcname which will specify the archive name " "to use; multiple --zip-include arguments can be used") parser.add_option("--icon", dest = "icon", help = "name of the icon file for the application") options, args = parser.parse_args() if len(args) == 0: options.script = None elif len(args) == 1: options.script, = args else: parser.error("only one script can be specified") if not args and options.includeModules is None and options.copyDeps: parser.error("script or a list of modules must be specified") if not args and options.targetName is None: parser.error("script or a target name must be specified") if options.excludeModules: options.excludeModules = options.excludeModules.split(",") else: options.excludeModules = [] if options.includeModules: options.includeModules = options.includeModules.split(",") else: options.includeModules = [] replacePaths = [] if options.replacePaths: for directive in options.replacePaths.split(os.pathsep): fromPath, replacement = directive.split("=") replacePaths.append((fromPath, replacement)) options.replacePaths = replacePaths if options.defaultPath is not None: sys.path = [p for mp in options.defaultPath \ for p in mp.split(os.pathsep)] if options.includePath is not None: paths = [p for mp in options.includePath for p in mp.split(os.pathsep)] sys.path = paths + sys.path if options.script is not None: sys.path.insert(0, os.path.dirname(options.script)) zipIncludes = [] if options.zipIncludes: for spec in options.zipIncludes: if '=' in spec: zipIncludes.append(spec.split('=', 1)) else: zipIncludes.append(spec) options.zipIncludes = zipIncludes return options def main(): options = ParseCommandLine() executables = [cx_Freeze.Executable(options.script, targetName = options.targetName)] freezer = cx_Freeze.Freezer(executables, includes = options.includeModules, excludes = options.excludeModules, replacePaths = options.replacePaths, compress = options.compress, optimizeFlag = options.optimized, copyDependentFiles = options.copyDeps, initScript = options.initScript, base = options.baseName, path = None, createLibraryZip = False, appendScriptToExe = True, targetDir = options.targetDir, zipIncludes = options.zipIncludes, icon = options.icon, silent = options.silent) freezer.Freeze() cx_Freeze-4.3.1/cx_Freeze/windist.py0000664000076600012760000004474711776175117014366 0ustar import distutils.command.bdist_msi import distutils.errors import distutils.util import msilib import os __all__ = [ "bdist_msi" ] # force the remove existing products action to happen first since Windows # installer appears to be braindead and doesn't handle files shared between # different "products" very well sequence = msilib.sequence.InstallExecuteSequence for index, info in enumerate(sequence): if info[0] == 'RemoveExistingProducts': sequence[index] = (info[0], info[1], 1450) class bdist_msi(distutils.command.bdist_msi.bdist_msi): user_options = distutils.command.bdist_msi.bdist_msi.user_options + [ ('add-to-path=', None, 'add target dir to PATH environment variable'), ('upgrade-code=', None, 'upgrade code to use'), ('initial-target-dir=', None, 'initial target directory'), ('target-name=', None, 'name of the file to create'), ('directories=', None, 'list of 3-tuples of directories to create'), ('data=', None, 'dictionary of data indexed by table name') ] x = y = 50 width = 370 height = 300 title = "[ProductName] Setup" modeless = 1 modal = 3 def add_config(self, fullname): if self.add_to_path: msilib.add_data(self.db, 'Environment', [("E_PATH", "Path", r"[~];[TARGETDIR]", "TARGETDIR")]) if self.directories: msilib.add_data(self.db, "Directory", self.directories) msilib.add_data(self.db, 'CustomAction', [("A_SET_TARGET_DIR", 256 + 51, "TARGETDIR", self.initial_target_dir)]) msilib.add_data(self.db, 'InstallExecuteSequence', [("A_SET_TARGET_DIR", 'TARGETDIR=""', 401)]) msilib.add_data(self.db, 'InstallUISequence', [("PrepareDlg", None, 140), ("A_SET_TARGET_DIR", 'TARGETDIR=""', 401), ("SelectDirectoryDlg", "not Installed", 1230), ("MaintenanceTypeDlg", "Installed and not Resume and not Preselected", 1250), ("ProgressDlg", None, 1280) ]) for index, executable in enumerate(self.distribution.executables): if executable.shortcutName is not None \ and executable.shortcutDir is not None: baseName = os.path.basename(executable.targetName) msilib.add_data(self.db, "Shortcut", [("S_APP_%s" % index, executable.shortcutDir, executable.shortcutName, "TARGETDIR", "[TARGETDIR]%s" % baseName, None, None, None, None, None, None, None)]) for tableName, data in self.data.items(): msilib.add_data(self.db, tableName, data) def add_cancel_dialog(self): dialog = msilib.Dialog(self.db, "CancelDlg", 50, 10, 260, 85, 3, self.title, "No", "No", "No") dialog.text("Text", 48, 15, 194, 30, 3, "Are you sure you want to cancel [ProductName] installation?") button = dialog.pushbutton("Yes", 72, 57, 56, 17, 3, "Yes", "No") button.event("EndDialog", "Exit") button = dialog.pushbutton("No", 132, 57, 56, 17, 3, "No", "Yes") button.event("EndDialog", "Return") def add_error_dialog(self): dialog = msilib.Dialog(self.db, "ErrorDlg", 50, 10, 330, 101, 65543, self.title, "ErrorText", None, None) dialog.text("ErrorText", 50, 9, 280, 48, 3, "") for text, x in [("No", 120), ("Yes", 240), ("Abort", 0), ("Cancel", 42), ("Ignore", 81), ("Ok", 159), ("Retry", 198)]: button = dialog.pushbutton(text[0], x, 72, 81, 21, 3, text, None) button.event("EndDialog", "Error%s" % text) def add_exit_dialog(self): dialog = distutils.command.bdist_msi.PyDialog(self.db, "ExitDialog", self.x, self.y, self.width, self.height, self.modal, self.title, "Finish", "Finish", "Finish") dialog.title("Completing the [ProductName] installer") dialog.back("< Back", "Finish", active = False) dialog.cancel("Cancel", "Back", active = False) dialog.text("Description", 15, 235, 320, 20, 0x30003, "Click the Finish button to exit the installer.") button = dialog.next("Finish", "Cancel", name = "Finish") button.event("EndDialog", "Return") def add_fatal_error_dialog(self): dialog = distutils.command.bdist_msi.PyDialog(self.db, "FatalError", self.x, self.y, self.width, self.height, self.modal, self.title, "Finish", "Finish", "Finish") dialog.title("[ProductName] installer ended prematurely") dialog.back("< Back", "Finish", active = False) dialog.cancel("Cancel", "Back", active = False) dialog.text("Description1", 15, 70, 320, 80, 0x30003, "[ProductName] setup ended prematurely because of an error. " "Your system has not been modified. To install this program " "at a later time, please run the installation again.") dialog.text("Description2", 15, 155, 320, 20, 0x30003, "Click the Finish button to exit the installer.") button = dialog.next("Finish", "Cancel", name = "Finish") button.event("EndDialog", "Exit") def add_files(self): db = self.db cab = msilib.CAB("distfiles") f = msilib.Feature(db, "default", "Default Feature", "Everything", 1, directory="TARGETDIR") f.set_current() rootdir = os.path.abspath(self.bdist_dir) root = msilib.Directory(db, cab, None, rootdir, "TARGETDIR", "SourceDir") db.Commit() todo = [root] while todo: dir = todo.pop() for file in os.listdir(dir.absolute): if os.path.isdir(os.path.join(dir.absolute, file)): newDir = msilib.Directory(db, cab, dir, file, file, "%s|%s" % (dir.make_short(file), file)) todo.append(newDir) else: dir.add_file(file) cab.commit(db) def add_files_in_use_dialog(self): dialog = distutils.command.bdist_msi.PyDialog(self.db, "FilesInUse", self.x, self.y, self.width, self.height, 19, self.title, "Retry", "Retry", "Retry", bitmap = False) dialog.text("Title", 15, 6, 200, 15, 0x30003, r"{\DlgFontBold8}Files in Use") dialog.text("Description", 20, 23, 280, 20, 0x30003, "Some files that need to be updated are currently in use.") dialog.text("Text", 20, 55, 330, 50, 3, "The following applications are using files that need to be " "updated by this setup. Close these applications and then " "click Retry to continue the installation or Cancel to exit " "it.") dialog.control("List", "ListBox", 20, 107, 330, 130, 7, "FileInUseProcess", None, None, None) button = dialog.back("Exit", "Ignore", name = "Exit") button.event("EndDialog", "Exit") button = dialog.next("Ignore", "Retry", name = "Ignore") button.event("EndDialog", "Ignore") button = dialog.cancel("Retry", "Exit", name = "Retry") button.event("EndDialog", "Retry") def add_maintenance_type_dialog(self): dialog = distutils.command.bdist_msi.PyDialog(self.db, "MaintenanceTypeDlg", self.x, self.y, self.width, self.height, self.modal, self.title, "Next", "Next", "Cancel") dialog.title("Welcome to the [ProductName] Setup Wizard") dialog.text("BodyText", 15, 63, 330, 42, 3, "Select whether you want to repair or remove [ProductName].") group = dialog.radiogroup("RepairRadioGroup", 15, 108, 330, 60, 3, "MaintenanceForm_Action", "", "Next") group.add("Repair", 0, 18, 300, 17, "&Repair [ProductName]") group.add("Remove", 0, 36, 300, 17, "Re&move [ProductName]") dialog.back("< Back", None, active = False) button = dialog.next("Finish", "Cancel") button.event("[REINSTALL]", "ALL", 'MaintenanceForm_Action="Repair"', 5) button.event("[Progress1]", "Repairing", 'MaintenanceForm_Action="Repair"', 6) button.event("[Progress2]", "repairs", 'MaintenanceForm_Action="Repair"', 7) button.event("Reinstall", "ALL", 'MaintenanceForm_Action="Repair"', 8) button.event("[REMOVE]", "ALL", 'MaintenanceForm_Action="Remove"', 11) button.event("[Progress1]", "Removing", 'MaintenanceForm_Action="Remove"', 12) button.event("[Progress2]", "removes", 'MaintenanceForm_Action="Remove"', 13) button.event("Remove", "ALL", 'MaintenanceForm_Action="Remove"', 14) button.event("EndDialog", "Return", 'MaintenanceForm_Action<>"Change"', 20) button = dialog.cancel("Cancel", "RepairRadioGroup") button.event("SpawnDialog", "CancelDlg") def add_prepare_dialog(self): dialog = distutils.command.bdist_msi.PyDialog(self.db, "PrepareDlg", self.x, self.y, self.width, self.height, self.modeless, self.title, "Cancel", "Cancel", "Cancel") dialog.text("Description", 15, 70, 320, 40, 0x30003, "Please wait while the installer prepares to guide you through" "the installation.") dialog.title("Welcome to the [ProductName] installer") text = dialog.text("ActionText", 15, 110, 320, 20, 0x30003, "Pondering...") text.mapping("ActionText", "Text") text = dialog.text("ActionData", 15, 135, 320, 30, 0x30003, None) text.mapping("ActionData", "Text") dialog.back("Back", None, active = False) dialog.next("Next", None, active = False) button = dialog.cancel("Cancel", None) button.event("SpawnDialog", "CancelDlg") def add_progress_dialog(self): dialog = distutils.command.bdist_msi.PyDialog(self.db, "ProgressDlg", self.x, self.y, self.width, self.height, self.modeless, self.title, "Cancel", "Cancel", "Cancel", bitmap = False) dialog.text("Title", 20, 15, 200, 15, 0x30003, r"{\DlgFontBold8}[Progress1] [ProductName]") dialog.text("Text", 35, 65, 300, 30, 3, "Please wait while the installer [Progress2] [ProductName].") dialog.text("StatusLabel", 35, 100 ,35, 20, 3, "Status:") text = dialog.text("ActionText", 70, 100, self.width - 70, 20, 3, "Pondering...") text.mapping("ActionText", "Text") control = dialog.control("ProgressBar", "ProgressBar", 35, 120, 300, 10, 65537, None, "Progress done", None, None) control.mapping("SetProgress", "Progress") dialog.back("< Back", "Next", active = False) dialog.next("Next >", "Cancel", active = False) button = dialog.cancel("Cancel", "Back") button.event("SpawnDialog", "CancelDlg") def add_properties(self): metadata = self.distribution.metadata props = [ ('DistVersion', metadata.get_version()), ('DefaultUIFont', 'DlgFont8'), ('ErrorDialog', 'ErrorDlg'), ('Progress1', 'Install'), ('Progress2', 'installs'), ('MaintenanceForm_Action', 'Repair'), ('ALLUSERS', '1') ] email = metadata.author_email or metadata.maintainer_email if email: props.append(("ARPCONTACT", email)) if metadata.url: props.append(("ARPURLINFOABOUT", metadata.url)) if self.upgrade_code is not None: props.append(("UpgradeCode", self.upgrade_code)) msilib.add_data(self.db, 'Property', props) def add_select_directory_dialog(self): dialog = distutils.command.bdist_msi.PyDialog(self.db, "SelectDirectoryDlg", self.x, self.y, self.width, self.height, self.modal, self.title, "Next", "Next", "Cancel") dialog.title("Select destination directory") dialog.back("< Back", None, active = False) button = dialog.next("Next >", "Cancel") button.event("SetTargetPath", "TARGETDIR", ordering = 1) button.event("SpawnWaitDialog", "WaitForCostingDlg", ordering = 2) button.event("EndDialog", "Return", ordering = 3) button = dialog.cancel("Cancel", "DirectoryCombo") button.event("SpawnDialog", "CancelDlg") dialog.control("DirectoryCombo", "DirectoryCombo", 15, 70, 272, 80, 393219, "TARGETDIR", None, "DirectoryList", None) dialog.control("DirectoryList", "DirectoryList", 15, 90, 308, 136, 3, "TARGETDIR", None, "PathEdit", None) dialog.control("PathEdit", "PathEdit", 15, 230, 306, 16, 3, "TARGETDIR", None, "Next", None) button = dialog.pushbutton("Up", 306, 70, 18, 18, 3, "Up", None) button.event("DirectoryListUp", "0") button = dialog.pushbutton("NewDir", 324, 70, 30, 18, 3, "New", None) button.event("DirectoryListNew", "0") def add_text_styles(self): msilib.add_data(self.db, 'TextStyle', [("DlgFont8", "Tahoma", 9, None, 0), ("DlgFontBold8", "Tahoma", 8, None, 1), ("VerdanaBold10", "Verdana", 10, None, 1), ("VerdanaRed9", "Verdana", 9, 255, 0) ]) def add_ui(self): self.add_text_styles() self.add_error_dialog() self.add_fatal_error_dialog() self.add_cancel_dialog() self.add_exit_dialog() self.add_user_exit_dialog() self.add_files_in_use_dialog() self.add_wait_for_costing_dialog() self.add_prepare_dialog() self.add_select_directory_dialog() self.add_progress_dialog() self.add_maintenance_type_dialog() def add_upgrade_config(self, sversion): if self.upgrade_code is not None: msilib.add_data(self.db, 'Upgrade', [(self.upgrade_code, None, sversion, None, 513, None, "REMOVEOLDVERSION"), (self.upgrade_code, sversion, None, None, 257, None, "REMOVENEWVERSION") ]) def add_user_exit_dialog(self): dialog = distutils.command.bdist_msi.PyDialog(self.db, "UserExit", self.x, self.y, self.width, self.height, self.modal, self.title, "Finish", "Finish", "Finish") dialog.title("[ProductName] installer was interrupted") dialog.back("< Back", "Finish", active = False) dialog.cancel("Cancel", "Back", active = False) dialog.text("Description1", 15, 70, 320, 80, 0x30003, "[ProductName] setup was interrupted. Your system has not " "been modified. To install this program at a later time, " "please run the installation again.") dialog.text("Description2", 15, 155, 320, 20, 0x30003, "Click the Finish button to exit the installer.") button = dialog.next("Finish", "Cancel", name = "Finish") button.event("EndDialog", "Exit") def add_wait_for_costing_dialog(self): dialog = msilib.Dialog(self.db, "WaitForCostingDlg", 50, 10, 260, 85, self.modal, self.title, "Return", "Return", "Return") dialog.text("Text", 48, 15, 194, 30, 3, "Please wait while the installer finishes determining your " "disk space requirements.") button = dialog.pushbutton("Return", 102, 57, 56, 17, 3, "Return", None) button.event("EndDialog", "Exit") def finalize_options(self): distutils.command.bdist_msi.bdist_msi.finalize_options(self) name = self.distribution.get_name() fullname = self.distribution.get_fullname() if self.initial_target_dir is None: if distutils.util.get_platform() == "win-amd64": programFilesFolder = "ProgramFiles64Folder" else: programFilesFolder = "ProgramFilesFolder" self.initial_target_dir = r"[%s]\%s" % (programFilesFolder, name) if self.add_to_path is None: self.add_to_path = False if self.target_name is None: self.target_name = fullname if not self.target_name.lower().endswith(".msi"): platform = distutils.util.get_platform().replace("win-", "") self.target_name = "%s-%s.msi" % (self.target_name, platform) if not os.path.isabs(self.target_name): self.target_name = os.path.join(self.dist_dir, self.target_name) if self.directories is None: self.directories = [] if self.data is None: self.data = {} def initialize_options(self): distutils.command.bdist_msi.bdist_msi.initialize_options(self) self.upgrade_code = None self.add_to_path = None self.initial_target_dir = None self.target_name = None self.directories = None self.data = None def run(self): if not self.skip_build: self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands = 1) install.prefix = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 distutils.log.info("installing to %s", self.bdist_dir) install.ensure_finalized() install.run() self.mkpath(self.dist_dir) fullname = self.distribution.get_fullname() if os.path.exists(self.target_name): os.unlink(self.target_name) metadata = self.distribution.metadata author = metadata.author or metadata.maintainer or "UNKNOWN" version = metadata.get_version() sversion = "%d.%d.%d" % \ distutils.version.StrictVersion(version).version self.db = msilib.init_database(self.target_name, msilib.schema, self.distribution.metadata.name, msilib.gen_uuid(), sversion, author) msilib.add_tables(self.db, msilib.sequence) self.add_properties() self.add_config(fullname) self.add_upgrade_config(sversion) self.add_ui() self.add_files() self.db.Commit() if not self.keep_temp: distutils.dir_util.remove_tree(self.bdist_dir, dry_run = self.dry_run) cx_Freeze-4.3.1/cx_Freeze/freezer.py0000664000076600012760000007377612053610362014334 0ustar """ Base class for freezing scripts into executables. """ import datetime import distutils.sysconfig import imp import marshal import os import shutil import socket import stat import struct import sys import time import zipfile import cx_Freeze __all__ = [ "ConfigError", "ConstantsModule", "Executable", "Freezer" ] EXTENSION_LOADER_SOURCE = \ """ import imp, os, sys found = False for p in sys.path: if not os.path.isdir(p): continue f = os.path.join(p, "%s") if not os.path.exists(f): continue m = imp.load_dynamic(__name__, f) import sys sys.modules[__name__] = m found = True break if not found: del sys.modules[__name__] raise ImportError("No module named %%s" %% __name__) """ MSVCR_MANIFEST_TEMPLATE = """ """ class Freezer(object): def __init__(self, executables, constantsModules = [], includes = [], excludes = [], packages = [], replacePaths = [], compress = None, optimizeFlag = 0, copyDependentFiles = None, initScript = None, base = None, path = None, createLibraryZip = None, appendScriptToExe = None, appendScriptToLibrary = None, targetDir = None, binIncludes = [], binExcludes = [], binPathIncludes = [], binPathExcludes = [], icon = None, includeFiles = [], zipIncludes = [], silent = False, namespacePackages = [], metadata = None, includeMSVCR = False): self.executables = list(executables) self.constantsModules = list(constantsModules) self.includes = list(includes) self.excludes = list(excludes) self.packages = list(packages) self.namespacePackages = list(namespacePackages) self.replacePaths = list(replacePaths) self.compress = compress self.optimizeFlag = optimizeFlag self.copyDependentFiles = copyDependentFiles self.initScript = initScript self.base = base self.path = path self.createLibraryZip = createLibraryZip self.includeMSVCR = includeMSVCR self.appendScriptToExe = appendScriptToExe self.appendScriptToLibrary = appendScriptToLibrary self.targetDir = targetDir self.binIncludes = [os.path.normcase(n) \ for n in self._GetDefaultBinIncludes() + binIncludes] self.binExcludes = [os.path.normcase(n) \ for n in self._GetDefaultBinExcludes() + binExcludes] self.binPathIncludes = [os.path.normcase(n) for n in binPathIncludes] self.binPathExcludes = [os.path.normcase(n) \ for n in self._GetDefaultBinPathExcludes() + binPathExcludes] self.icon = icon self.includeFiles = list(includeFiles) self.includeFiles = self._ProcessPathSpecs(includeFiles) self.zipIncludes = self._ProcessPathSpecs(zipIncludes) self.silent = silent self.metadata = metadata self._VerifyConfiguration() def _AddVersionResource(self, fileName): try: from win32verstamp import stamp except: print("*** WARNING *** unable to create version resource") print("install pywin32 extensions first") return versionInfo = VersionInfo(self.metadata.version, comments = self.metadata.long_description, description = self.metadata.description, company = self.metadata.author, product = self.metadata.name) stamp(fileName, versionInfo) def _CopyFile(self, source, target, copyDependentFiles = False, includeMode = False): normalizedSource = os.path.normcase(os.path.normpath(source)) normalizedTarget = os.path.normcase(os.path.normpath(target)) if normalizedTarget in self.filesCopied: return if normalizedSource == normalizedTarget: return self._RemoveFile(target) targetDir = os.path.dirname(target) self._CreateDirectory(targetDir) if not self.silent: sys.stdout.write("copying %s -> %s\n" % (source, target)) shutil.copyfile(source, target) shutil.copystat(source, target) if includeMode: shutil.copymode(source, target) self.filesCopied[normalizedTarget] = None if copyDependentFiles: for source in self._GetDependentFiles(source): target = os.path.join(targetDir, os.path.basename(source)) self._CopyFile(source, target, copyDependentFiles) def _CreateDirectory(self, path): if not os.path.isdir(path): if not self.silent: sys.stdout.write("creating directory %s\n" % path) os.makedirs(path) def _FreezeExecutable(self, exe): if self.createLibraryZip: finder = self.finder else: finder = self._GetModuleFinder(exe) if exe.script is None: scriptModule = None else: scriptModule = finder.IncludeFile(exe.script, exe.moduleName) self._CopyFile(exe.base, exe.targetName, exe.copyDependentFiles, includeMode = True) if self.includeMSVCR: self._IncludeMSVCR(exe) if exe.icon is not None: if sys.platform == "win32": import cx_Freeze.util cx_Freeze.util.AddIcon(exe.targetName, exe.icon) else: targetName = os.path.join(os.path.dirname(exe.targetName), os.path.basename(exe.icon)) self._CopyFile(exe.icon, targetName, copyDependentFiles = False) if not os.access(exe.targetName, os.W_OK): mode = os.stat(exe.targetName).st_mode os.chmod(exe.targetName, mode | stat.S_IWUSR) if self.metadata is not None and sys.platform == "win32": self._AddVersionResource(exe.targetName) if not exe.appendScriptToLibrary: if exe.appendScriptToExe: fileName = exe.targetName else: baseFileName, ext = os.path.splitext(exe.targetName) fileName = baseFileName + ".zip" self._RemoveFile(fileName) if not self.createLibraryZip and exe.copyDependentFiles: scriptModule = None self._WriteModules(fileName, exe.initScript, finder, exe.compress, exe.copyDependentFiles, scriptModule) def _GetBaseFileName(self, argsSource = None): if argsSource is None: argsSource = self name = argsSource.base if name is None: if argsSource.copyDependentFiles: name = "Console" else: name = "ConsoleKeepPath" argsSource.base = self._GetFileName("bases", name) if argsSource.base is None: raise ConfigError("no base named %s", name) def _GetDefaultBinExcludes(self): """Return the file names of libraries that need not be included because they would normally be expected to be found on the target system or because they are part of a package which requires independent installation anyway.""" if sys.platform == "win32": return ["comctl32.dll", "oci.dll", "cx_Logging.pyd"] else: return ["libclntsh.so", "libwtc9.so"] def _GetDefaultBinIncludes(self): """Return the file names of libraries which must be included for the frozen executable to work.""" if sys.platform == "win32": pythonDll = "python%s%s.dll" % sys.version_info[:2] return [pythonDll, "gdiplus.dll", "mfc71.dll", "msvcp71.dll", "msvcr71.dll"] else: soName = distutils.sysconfig.get_config_var("INSTSONAME") if soName is None: return [] pythonSharedLib = self._RemoveVersionNumbers(soName) return [pythonSharedLib] def _GetDefaultBinPathExcludes(self): """Return the paths of directories which contain files that should not be included, generally because they contain standard system libraries.""" if sys.platform == "win32": import cx_Freeze.util systemDir = cx_Freeze.util.GetSystemDir() windowsDir = cx_Freeze.util.GetWindowsDir() return [windowsDir, systemDir, os.path.join(windowsDir, "WinSxS")] elif sys.platform == "darwin": return ["/lib", "/usr/lib", "/System/Library/Frameworks"] else: return ["/lib", "/lib32", "/lib64", "/usr/lib", "/usr/lib32", "/usr/lib64"] def _GetDependentFiles(self, path): """Return the file's dependencies using platform-specific tools (the imagehlp library on Windows, otool on Mac OS X and ldd on Linux); limit this list by the exclusion lists as needed""" dependentFiles = self.dependentFiles.get(path) if dependentFiles is None: if sys.platform == "win32": origPath = os.environ["PATH"] os.environ["PATH"] = origPath + os.pathsep + \ os.pathsep.join(sys.path) import cx_Freeze.util dependentFiles = cx_Freeze.util.GetDependentFiles(path) os.environ["PATH"] = origPath else: dependentFiles = [] if sys.platform == "darwin": command = 'otool -L "%s"' % path splitString = " (compatibility" dependentFileIndex = 0 else: command = 'ldd "%s"' % path splitString = " => " dependentFileIndex = 1 for line in os.popen(command): parts = line.expandtabs().strip().split(splitString) if len(parts) != 2: continue dependentFile = parts[dependentFileIndex].strip() if dependentFile in ("not found", "(file not found)"): fileName = parts[0] if fileName not in self.linkerWarnings: self.linkerWarnings[fileName] = None message = "WARNING: cannot find %s\n" % fileName sys.stdout.write(message) continue if dependentFile.startswith("("): continue pos = dependentFile.find(" (") if pos >= 0: dependentFile = dependentFile[:pos].strip() if dependentFile: dependentFiles.append(dependentFile) dependentFiles = self.dependentFiles[path] = \ [f for f in dependentFiles if self._ShouldCopyFile(f)] return dependentFiles def _GetFileName(self, dir, name, ext = None): if os.path.isabs(name): return name name = os.path.normcase(name) fullDir = os.path.join(os.path.dirname(cx_Freeze.__file__), dir) if os.path.isdir(fullDir): for fileName in os.listdir(fullDir): checkName, checkExt = \ os.path.splitext(os.path.normcase(fileName)) if name == checkName and (ext is None or ext == checkExt): return os.path.join(fullDir, fileName) def _GetInitScriptFileName(self, argsSource = None): if argsSource is None: argsSource = self name = argsSource.initScript if name is None: if argsSource.copyDependentFiles: name = "Console" else: name = "ConsoleKeepPath" if sys.version_info[0] >= 3: name += "3" argsSource.initScript = self._GetFileName("initscripts", name, ".py") if argsSource.initScript is None: raise ConfigError("no initscript named %s", name) def _GetModuleFinder(self, argsSource = None): if argsSource is None: argsSource = self finder = cx_Freeze.ModuleFinder(self.includeFiles, argsSource.excludes, argsSource.path, argsSource.replacePaths, argsSource.copyDependentFiles, compress = argsSource.compress) for name in argsSource.namespacePackages: package = finder.IncludeModule(name, namespace = True) package.ExtendPath() for name in argsSource.includes: finder.IncludeModule(name) for name in argsSource.packages: finder.IncludePackage(name) return finder def _IncludeMSVCR(self, exe): msvcRuntimeDll = None targetDir = os.path.dirname(exe.targetName) for fullName in self.filesCopied: path, name = os.path.split(os.path.normcase(fullName)) if name.startswith("msvcr") and name.endswith(".dll"): msvcRuntimeDll = name for otherName in [name.replace("r", c) for c in "mp"]: sourceName = os.path.join(self.msvcRuntimeDir, otherName) if not os.path.exists(sourceName): continue targetName = os.path.join(targetDir, otherName) self._CopyFile(sourceName, targetName) break if msvcRuntimeDll is not None and msvcRuntimeDll == "msvcr90.dll": if struct.calcsize("P") == 4: arch = "x86" else: arch = "amd64" manifest = MSVCR_MANIFEST_TEMPLATE.strip().replace("{PROC_ARCH}", arch) fileName = os.path.join(targetDir, "Microsoft.VC90.CRT.manifest") sys.stdout.write("creating %s\n" % fileName) open(fileName, "w").write(manifest) def _PrintReport(self, fileName, modules): sys.stdout.write("writing zip file %s\n\n" % fileName) sys.stdout.write(" %-25s %s\n" % ("Name", "File")) sys.stdout.write(" %-25s %s\n" % ("----", "----")) for module in modules: if module.path: sys.stdout.write("P") else: sys.stdout.write("m") sys.stdout.write(" %-25s %s\n" % (module.name, module.file or "")) sys.stdout.write("\n") def _ProcessPathSpecs(self, specs): processedSpecs = [] for spec in specs: if not isinstance(spec, (list, tuple)): source = target = spec elif len(spec) != 2: raise ConfigError("path spec must be a list or tuple of " "length two") else: source, target = spec source = os.path.normpath(source) if not target: dirName, target = os.path.split(source) elif os.path.isabs(target): raise ConfigError("target path for include file may not be " "an absolute path") processedSpecs.append((source, target)) return processedSpecs def _RemoveFile(self, path): if os.path.exists(path): os.chmod(path, stat.S_IWRITE) os.remove(path) def _RemoveVersionNumbers(self, libName): tweaked = False parts = libName.split(".") while parts: if not parts[-1].isdigit(): break parts.pop(-1) tweaked = True if tweaked: libName = ".".join(parts) return libName def _ShouldCopyFile(self, path): """Return true if the file should be copied to the target machine. This is done by checking the binPathIncludes, binPathExcludes, binIncludes and binExcludes configuration variables using first the full file name, then just the base file name, then the file name without any version numbers. Files are included unless specifically excluded but inclusions take precedence over exclusions.""" # check for C runtime, if desired path = os.path.normcase(path) dirName, fileName = os.path.split(path) if fileName.startswith("msvcr") and fileName.endswith(".dll"): self.msvcRuntimeDir = dirName return self.includeMSVCR # check the full path if path in self.binIncludes: return True if path in self.binExcludes: return False # check the file name by itself (with any included version numbers) if fileName in self.binIncludes: return True if fileName in self.binExcludes: return False # check the file name by itself (version numbers removed) name = self._RemoveVersionNumbers(fileName) if name in self.binIncludes: return True if name in self.binExcludes: return False # check the path for inclusion/exclusion for path in self.binPathIncludes: if dirName.startswith(path): return True for path in self.binPathExcludes: if dirName.startswith(path): return False return True def _VerifyCanAppendToLibrary(self): if not self.createLibraryZip: raise ConfigError("script cannot be appended to library zip if " "one is not being created") def _VerifyConfiguration(self): if self.compress is None: self.compress = True if self.copyDependentFiles is None: self.copyDependentFiles = True if self.createLibraryZip is None: self.createLibraryZip = True if self.appendScriptToExe is None: self.appendScriptToExe = False if self.appendScriptToLibrary is None: self.appendScriptToLibrary = \ self.createLibraryZip and not self.appendScriptToExe if self.targetDir is None: self.targetDir = os.path.abspath("dist") self._GetInitScriptFileName() self._GetBaseFileName() if self.path is None: self.path = sys.path if self.appendScriptToLibrary: self._VerifyCanAppendToLibrary() for sourceFileName, targetFileName in \ self.includeFiles + self.zipIncludes: if not os.path.exists(sourceFileName): raise ConfigError("cannot find file/directory named %s", sourceFileName) if os.path.isabs(targetFileName): raise ConfigError("target file/directory cannot be absolute") for executable in self.executables: executable._VerifyConfiguration(self) def _WriteModules(self, fileName, initScript, finder, compress, copyDependentFiles, scriptModule = None): initModule = finder.IncludeFile(initScript, "cx_Freeze__init__") if scriptModule is None: for module in self.constantsModules: module.Create(finder) modules = [m for m in finder.modules \ if m.name not in self.excludeModules] else: modules = [initModule, scriptModule] self.excludeModules[initModule.name] = None self.excludeModules[scriptModule.name] = None itemsToSort = [(m.name, m) for m in modules] itemsToSort.sort() modules = [m for n, m in itemsToSort] if not self.silent: self._PrintReport(fileName, modules) if scriptModule is None: finder.ReportMissingModules() targetDir = os.path.dirname(fileName) self._CreateDirectory(targetDir) filesToCopy = [] if os.path.exists(fileName): mode = "a" else: mode = "w" outFile = zipfile.PyZipFile(fileName, mode, zipfile.ZIP_DEFLATED) for module in modules: if module.code is None and module.file is not None: fileName = os.path.basename(module.file) baseFileName, ext = os.path.splitext(fileName) if baseFileName != module.name and module.name != "zlib": if "." in module.name: fileName = module.name + ext generatedFileName = "ExtensionLoader_%s.py" % \ module.name.replace(".", "_") module.code = compile(EXTENSION_LOADER_SOURCE % fileName, generatedFileName, "exec") target = os.path.join(targetDir, fileName) filesToCopy.append((module, target)) if module.code is None: continue fileName = "/".join(module.name.split(".")) if module.path: fileName += "/__init__" if module.file is not None and os.path.exists(module.file): mtime = os.stat(module.file).st_mtime else: mtime = time.time() zipTime = time.localtime(mtime)[:6] # starting with Python 3.3 the pyc file format contains the source # size; it is not actually used for anything except determining if # the file is up to date so we can safely set this value to zero if sys.version_info[:2] < (3, 3): header = imp.get_magic() + struct.pack("" % self.script def _VerifyConfiguration(self, freezer): if self.path is None: self.path = freezer.path if self.targetDir is None: self.targetDir = freezer.targetDir if self.includes is None: self.includes = freezer.includes if self.excludes is None: self.excludes = freezer.excludes if self.packages is None: self.packages = freezer.packages if self.namespacePackages is None: self.namespacePackages = freezer.namespacePackages if self.replacePaths is None: self.replacePaths = freezer.replacePaths if self.compress is None: self.compress = freezer.compress if self.copyDependentFiles is None: self.copyDependentFiles = freezer.copyDependentFiles if self.appendScriptToExe is None: self.appendScriptToExe = freezer.appendScriptToExe if self.appendScriptToLibrary is None: self.appendScriptToLibrary = freezer.appendScriptToLibrary if self.initScript is None: self.initScript = freezer.initScript else: freezer._GetInitScriptFileName(self) if self.base is None: self.base = freezer.base else: freezer._GetBaseFileName(self) if self.appendScriptToLibrary: freezer._VerifyCanAppendToLibrary() if self.icon is None: self.icon = freezer.icon if self.targetName is None: name, ext = os.path.splitext(os.path.basename(self.script)) baseName, ext = os.path.splitext(self.base) self.targetName = name + ext if self.appendScriptToLibrary: name, ext = os.path.splitext(self.targetName) self.moduleName = "%s__main__" % os.path.normcase(name) else: self.moduleName = "__main__" self.targetName = os.path.join(self.targetDir, self.targetName) class ConstantsModule(object): def __init__(self, releaseString = None, copyright = None, moduleName = "BUILD_CONSTANTS", timeFormat = "%B %d, %Y %H:%M:%S"): self.moduleName = moduleName self.timeFormat = timeFormat self.values = {} self.values["BUILD_RELEASE_STRING"] = releaseString self.values["BUILD_COPYRIGHT"] = copyright def Create(self, finder): """Create the module which consists of declaration statements for each of the values.""" today = datetime.datetime.today() sourceTimestamp = 0 for module in finder.modules: if module.file is None: continue if module.inZipFile: continue if not os.path.exists(module.file): raise ConfigError("no file named %s (for module %s)", module.file, module.name) timestamp = os.stat(module.file).st_mtime sourceTimestamp = max(sourceTimestamp, timestamp) sourceTimestamp = datetime.datetime.fromtimestamp(sourceTimestamp) self.values["BUILD_TIMESTAMP"] = today.strftime(self.timeFormat) self.values["BUILD_HOST"] = socket.gethostname().split(".")[0] self.values["SOURCE_TIMESTAMP"] = \ sourceTimestamp.strftime(self.timeFormat) module = finder._AddModule(self.moduleName) sourceParts = [] names = list(self.values.keys()) names.sort() for name in names: value = self.values[name] sourceParts.append("%s = %r" % (name, value)) source = "\n".join(sourceParts) module.code = compile(source, "%s.py" % self.moduleName, "exec") return module class VersionInfo(object): def __init__(self, version, internalName = None, originalFileName = None, comments = None, company = None, description = None, copyright = None, trademarks = None, product = None, dll = False, debug = False, verbose = True): parts = version.split(".") while len(parts) < 4: parts.append("0") self.version = ".".join(parts) self.internal_name = internalName self.original_filename = originalFileName self.comments = comments self.company = company self.description = description self.copyright = copyright self.trademarks = trademarks self.product = product self.dll = dll self.debug = debug self.verbose = verbose cx_Freeze-4.3.1/samples/0000755000000000000000000000000012053761025013574 5ustar rootrootcx_Freeze-4.3.1/samples/service/0000755000000000000000000000000012053761026015235 5ustar rootrootcx_Freeze-4.3.1/samples/service/setup.py0000664000076600012760000000167211776175122015221 0ustar # A simple setup script for creating a Windows service. See the comments in the # Config.py and ServiceHandler.py files for more information on how to set this # up. # # Installing the service is done with the option --install and # uninstalling the service is done with the option --uninstall . The # value for is intended to differentiate between different invocations # of the same service code -- for example for accessing different databases or # using different configuration files. from cx_Freeze import setup, Executable buildOptions = dict(includes = ["ServiceHandler"]) executable = Executable("Config.py", base = "Win32Service", targetName = "cx_FreezeSampleService.exe") setup( name = "cx_FreezeSampleService", version = "0.1", description = "Sample cx_Freeze Windows serice", executables = [executable], options = dict(build_exe = buildOptions)) cx_Freeze-4.3.1/samples/service/Config.py0000664000076600012760000000360612000121626015242 0ustar #------------------------------------------------------------------------------ # Config.py # This file defines information about the service. The first four # attributes are expected to be defined and if they are not an exception will # be thrown when attempting to create the service: # # NAME # the name to call the service with one %s place holder that will be used # to identify the service further. # # DISPLAY_NAME # the value to use as the display name for the service with one %s place # holder that will be used to identify the service further. # # MODULE_NAME # the name of the module implementing the service. # # CLASS_NAME # the name of the class within the module implementing the service. This # class should accept no parameters in the constructor. It should have a # method called "Initialize" which will accept the configuration file # name. It should also have a method called "Run" which will be called # with no parameters when the service is started. It should also have a # method called "Stop" which will be called with no parameters when the # service is stopped using the service control GUI. # # DESCRIPTION # the description of the service (optional) # # AUTO_START # whether the service should be started automatically (optional) # # SESSION_CHANGES # whether the service should monitor session changes (optional). If # True, session changes will call the method "SessionChanged" with the # parameters sessionId and eventTypeId. #------------------------------------------------------------------------------ NAME = "cx_FreezeSampleService%s" DISPLAY_NAME = "cx_Freeze Sample Service - %s" MODULE_NAME = "ServiceHandler" CLASS_NAME = "Handler" DESCRIPTION = "Sample service description" AUTO_START = False SESSION_CHANGES = False cx_Freeze-4.3.1/samples/service/ServiceHandler.py0000664000076600012760000000246511776175122016760 0ustar """ Implements a simple service using cx_Freeze. This sample makes use of cx_PyGenLib (http://cx-pygenlib.sourceforge.net) and cx_Logging (http://cx-logging.sourceforge.net). See below for more information on what methods must be implemented and how they are called. """ import cx_Logging import cx_Threads import sys class Handler(object): # no parameters are permitted; all configuration should be placed in the # configuration file and handled in the Initialize() method def __init__(self): cx_Logging.Info("creating handler instance") self.stopEvent = cx_Threads.Event() # called when the service is starting def Initialize(self, configFileName): cx_Logging.Info("initializing: config file name is %r", configFileName) # called when the service is starting immediately after Initialize() # use this to perform the work of the service; don't forget to set or check # for the stop event or the service GUI will not respond to requests to # stop the service def Run(self): cx_Logging.Info("running service....") self.stopEvent.Wait() # called when the service is being stopped by the service manager GUI def Stop(self): cx_Logging.Info("stopping service...") self.stopEvent.Set() cx_Freeze-4.3.1/samples/relimport/0000755000000000000000000000000012053761026015612 5ustar rootrootcx_Freeze-4.3.1/samples/relimport/relimport.py0000664000076600012760000000001411776175122016440 0ustar import pkg1 cx_Freeze-4.3.1/samples/relimport/pkg1/0000755000000000000000000000000012053761026016454 5ustar rootrootcx_Freeze-4.3.1/samples/relimport/pkg1/__init__.py0000664000076600012760000000013011776175121017022 0ustar import sys sys.stdout.write("importing pkg1\n") from . import sub1 from . import pkg2 cx_Freeze-4.3.1/samples/relimport/pkg1/sub6.py0000664000076600012760000000006711776175122016154 0ustar import sys sys.stdout.write("importing pkg1.sub6\n") cx_Freeze-4.3.1/samples/relimport/pkg1/sub2.py0000664000076600012760000000006711776175122016150 0ustar import sys sys.stdout.write("importing pkg1.sub2\n") cx_Freeze-4.3.1/samples/relimport/pkg1/sub1.py0000664000076600012760000000011211776175122016136 0ustar import sys sys.stdout.write("importing pkg1.sub1\n") from . import sub2 cx_Freeze-4.3.1/samples/relimport/pkg1/pkg2/0000755000000000000000000000000012053761026017317 5ustar rootrootcx_Freeze-4.3.1/samples/relimport/pkg1/pkg2/sub5.py0000664000076600012760000000007411776175122017014 0ustar import sys sys.stdout.write("importing pkg1.pkg2.sub5\n") cx_Freeze-4.3.1/samples/relimport/pkg1/pkg2/__init__.py0000664000076600012760000000013611776175121017673 0ustar import sys sys.stdout.write("importing pkg1.pkg2\n") from . import sub3 from .. import sub4 cx_Freeze-4.3.1/samples/relimport/pkg1/pkg2/sub3.py0000664000076600012760000000014311776175121017006 0ustar import sys sys.stdout.write("importing pkg1.pkg2.sub3\n") from . import sub5 from .. import sub6 cx_Freeze-4.3.1/samples/relimport/pkg1/sub4.py0000664000076600012760000000006711776175122016152 0ustar import sys sys.stdout.write("importing pkg1.sub4\n") cx_Freeze-4.3.1/samples/relimport/setup.py0000664000076600012760000000107011776175122015566 0ustar # relimport.py is a very simple script that tests importing using relative # imports (available in Python 2.5 and up) # # Run the build process by running the command 'python setup.py build' # # If everything works well you should find a subdirectory in the build # subdirectory that contains the files needed to run the script without Python from cx_Freeze import setup, Executable setup( name = "relimport", version = "0.1", description = "Sample cx_Freeze script for relative imports", executables = [Executable("relimport.py")]) cx_Freeze-4.3.1/samples/zope/0000755000000000000000000000000012053761027014553 5ustar rootrootcx_Freeze-4.3.1/samples/zope/qotd.py0000664000076600012760000000100111776175122014327 0ustar #!/usr/bin/env /usr/bin/python """A simple Quote of the Day server""" from twisted.internet.protocol import Protocol, Factory from twisted.internet import reactor class QOTD(Protocol): def connectionMade(self): self.transport.write("An apple a day keeps the doctor away\r\n") self.transport.loseConnection() # Next lines are magic: factory = Factory() factory.protocol = QOTD # 8007 is the port you want to run under. Choose something >1024 reactor.listenTCP(8007, factory) reactor.run() cx_Freeze-4.3.1/samples/zope/setup.py0000664000076600012760000000134011776175123014527 0ustar # A simple setup script to create an executable using Zope which demonstrates # the use of namespace packages. # # qotd.py is a very simple type of Zope application # # Run the build process by running the command 'python setup.py build' # # If everything works well you should find a subdirectory in the build # subdirectory that contains the files needed to run the application import sys from cx_Freeze import setup, Executable buildOptions = dict( namespace_packages = ['zope']) setup( name = "QOTD sample", version = "1.0", description = "QOTD sample for demonstrating use of namespace packages", options = dict(build_exe = buildOptions), executables = [Executable("qotd.py")]) cx_Freeze-4.3.1/samples/simple/0000755000000000000000000000000012053761027015067 5ustar rootrootcx_Freeze-4.3.1/samples/simple/setup.py0000664000076600012760000000113012053100321015011 0ustar # A very simple setup script to create a single executable # # hello.py is a very simple "Hello, world" type script which also displays the # environment in which the script runs # # Run the build process by running the command 'python setup.py build' # # If everything works well you should find a subdirectory in the build # subdirectory that contains the files needed to run the script without Python from cx_Freeze import setup, Executable setup( name = "hello", version = "0.1", description = "Sample cx_Freeze script", executables = [Executable("hello.py")]) cx_Freeze-4.3.1/samples/simple/hello.py0000664000076600012760000000110511776175122015004 0ustar import datetime import sys sys.stdout.write("Hello from cx_Freeze\n") sys.stdout.write("The current date is %s\n\n" % \ datetime.datetime.today().strftime("%B %d, %Y %H:%M:%S")) sys.stdout.write("Executable: %r\n" % sys.executable) sys.stdout.write("Prefix: %r\n" % sys.prefix) sys.stdout.write("File system encoding: %r\n\n" % sys.getfilesystemencoding()) sys.stdout.write("ARGUMENTS:\n") for a in sys.argv: sys.stdout.write("%s\n" % a) sys.stdout.write("\n") sys.stdout.write("PATH:\n") for p in sys.path: sys.stdout.write("%s\n" % p) sys.stdout.write("\n") cx_Freeze-4.3.1/samples/advanced/0000755000000000000000000000000012053761026015342 5ustar rootrootcx_Freeze-4.3.1/samples/advanced/advanced_2.py0000664000076600012760000000016111776175121016143 0ustar import sys sys.stdout.write("Hello from cx_Freeze Advanced #2\n\n") module = __import__("testfreeze_2") cx_Freeze-4.3.1/samples/advanced/advanced_1.py0000664000076600012760000000016111776175121016142 0ustar import sys sys.stdout.write("Hello from cx_Freeze Advanced #1\n\n") module = __import__("testfreeze_1") cx_Freeze-4.3.1/samples/advanced/setup.py0000664000076600012760000000175711776175121015331 0ustar # An advanced setup script to create multiple executables and demonstrate a few # of the features available to setup scripts # # hello.py is a very simple "Hello, world" type script which also displays the # environment in which the script runs # # Run the build process by running the command 'python setup.py build' # # If everything works well you should find a subdirectory in the build # subdirectory that contains the files needed to run the script without Python import sys from cx_Freeze import setup, Executable executables = [ Executable("advanced_1.py"), Executable("advanced_2.py") ] buildOptions = dict( compressed = True, includes = ["testfreeze_1", "testfreeze_2"], path = sys.path + ["modules"]) setup( name = "advanced_cx_Freeze_sample", version = "0.1", description = "Advanced sample cx_Freeze script", options = dict(build_exe = buildOptions), executables = executables) cx_Freeze-4.3.1/samples/advanced/modules/0000755000000000000000000000000012053761026017012 5ustar rootrootcx_Freeze-4.3.1/samples/advanced/modules/testfreeze_2.py0000664000076600012760000000007511776175121020232 0ustar import sys sys.stdout.write("Test freeze module #2\n") cx_Freeze-4.3.1/samples/advanced/modules/testfreeze_1.py0000664000076600012760000000007511776175121020231 0ustar import sys sys.stdout.write("Test freeze module #1\n") cx_Freeze-4.3.1/samples/PyQt4/0000755000000000000000000000000012053761026014556 5ustar rootrootcx_Freeze-4.3.1/samples/PyQt4/PyQt4app.py0000664000076600012760000000021011776175121015046 0ustar import sys from PyQt4.QtCore import * from PyQt4.QtGui import * app = QApplication(sys.argv) form = QDialog() form.show() app.exec_() cx_Freeze-4.3.1/samples/PyQt4/setup.py0000664000076600012760000000145112000121626014512 0ustar # A simple setup script to create an executable using PyQt4. This also # demonstrates the method for creating a Windows executable that does not have # an associated console. # # PyQt4app.py is a very simple type of PyQt4 application # # Run the build process by running the command 'python setup.py build' # # If everything works well you should find a subdirectory in the build # subdirectory that contains the files needed to run the application import sys from cx_Freeze import setup, Executable base = None if sys.platform == "win32": base = "Win32GUI" setup( name = "simple_PyQt4", version = "0.1", description = "Sample cx_Freeze PyQt4 script", options = {"build_exe" : {"includes" : "atexit" }}, executables = [Executable("PyQt4app.py", base = base)]) cx_Freeze-4.3.1/samples/wx/0000755000000000000000000000000012053761027014234 5ustar rootrootcx_Freeze-4.3.1/samples/wx/wxapp.py0000664000076600012760000000222311776175122014207 0ustar import wx class Frame(wx.Frame): def __init__(self): wx.Frame.__init__(self, parent = None, title = "Hello from cx_Freeze") panel = wx.Panel(self) closeMeButton = wx.Button(panel, -1, "Close Me") wx.EVT_BUTTON(self, closeMeButton.GetId(), self.OnCloseMe) wx.EVT_CLOSE(self, self.OnCloseWindow) pushMeButton = wx.Button(panel, -1, "Push Me") wx.EVT_BUTTON(self, pushMeButton.GetId(), self.OnPushMe) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(closeMeButton, flag = wx.ALL, border = 20) sizer.Add(pushMeButton, flag = wx.ALL, border = 20) panel.SetSizer(sizer) topSizer = wx.BoxSizer(wx.VERTICAL) topSizer.Add(panel, flag = wx.ALL | wx.EXPAND) topSizer.Fit(self) def OnCloseMe(self, event): self.Close(True) def OnPushMe(self, event): wx.MessageBox("I was pushed!", "Informational message") def OnCloseWindow(self, event): self.Destroy() class App(wx.App): def OnInit(self): frame = Frame() frame.Show(True) self.SetTopWindow(frame) return True app = App(1) app.MainLoop() cx_Freeze-4.3.1/samples/wx/setup.py0000664000076600012760000000136711776175122014220 0ustar # A simple setup script to create an executable running wxPython. This also # demonstrates the method for creating a Windows executable that does not have # an associated console. # # wxapp.py is a very simple "Hello, world" type wxPython application # # Run the build process by running the command 'python setup.py build' # # If everything works well you should find a subdirectory in the build # subdirectory that contains the files needed to run the application import sys from cx_Freeze import setup, Executable base = None if sys.platform == "win32": base = "Win32GUI" setup( name = "hello", version = "0.1", description = "Sample cx_Freeze wxPython script", executables = [Executable("wxapp.py", base = base)]) cx_Freeze-4.3.1/samples/matplotlib/0000755000000000000000000000000012053761026015744 5ustar rootrootcx_Freeze-4.3.1/samples/matplotlib/test_matplotlib.py0000664000076600012760000000300311776175121017763 0ustar from numpy import arange, sin, pi import matplotlib matplotlib.use('WXAgg') from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.backends.backend_wx import NavigationToolbar2Wx from matplotlib.figure import Figure import wx class CanvasFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self,None,-1, 'CanvasFrame',size=(550,350)) self.SetBackgroundColour(wx.NamedColor("WHITE")) self.figure = Figure() self.axes = self.figure.add_subplot(111) t = arange(0.0,3.0,0.01) s = sin(2*pi*t) self.axes.plot(t,s) self.canvas = FigureCanvas(self, -1, self.figure) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizerAndFit(self.sizer) self.add_toolbar() def add_toolbar(self): self.toolbar = NavigationToolbar2Wx(self.canvas) self.toolbar.Realize() if wx.Platform == '__WXMAC__': self.SetToolBar(self.toolbar) else: tw, th = self.toolbar.GetSizeTuple() fw, fh = self.canvas.GetSizeTuple() self.toolbar.SetSize(wx.Size(fw, th)) self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) self.toolbar.update() def OnPaint(self, event): self.canvas.draw() class App(wx.App): def OnInit(self): 'Create the main window and insert the custom frame' frame = CanvasFrame() frame.Show(True) return True app = App(0) app.MainLoop() cx_Freeze-4.3.1/samples/matplotlib/setup.py0000664000076600012760000000145711776175121015730 0ustar # A simple setup script to create an executable using matplotlib. # # test_matplotlib.py is a very simple matplotlib application that demonstrates # its use. # # Run the build process by running the command 'python setup.py build' # # If everything works well you should find a subdirectory in the build # subdirectory that contains the files needed to run the application import cx_Freeze import sys base = None if sys.platform == "win32": base = "Win32GUI" buildOptions = dict( excludes = ["Tkinter"]) executables = [ cx_Freeze.Executable("test_matplotlib.py", base = base) ] cx_Freeze.setup( name = "test_matplotlib", version = "0.1", description = "Sample matplotlib script", executables = executables, options = dict(build_exe = buildOptions)) cx_Freeze-4.3.1/samples/Tkinter/0000755000000000000000000000000012053761026015215 5ustar rootrootcx_Freeze-4.3.1/samples/Tkinter/SimpleTkApp.py0000664000076600012760000000032411776175121016222 0ustar try: from tkinter import * except ImportError: from Tkinter import * root = Tk() root.title('Button') Label(text='I am a button').pack(pady=15) Button( text='Button') .pack(side=BOTTOM) root.mainloop() cx_Freeze-4.3.1/samples/Tkinter/setup.py0000664000076600012760000000137311776175121015176 0ustar # A simple setup script to create an executable using Tkinter. This also # demonstrates the method for creating a Windows executable that does not have # an associated console. # # SimpleTkApp.py is a very simple type of Tkinter application # # Run the build process by running the command 'python setup.py build' # # If everything works well you should find a subdirectory in the build # subdirectory that contains the files needed to run the application import sys from cx_Freeze import setup, Executable base = None if sys.platform == "win32": base = "Win32GUI" setup( name = "simple_Tkinter", version = "0.1", description = "Sample cx_Freeze Tkinter script", executables = [Executable("SimpleTkApp.py", base = base)]) cx_Freeze-4.3.1/cxfreeze-quickstart0000775000076600012760000000010212000121625014273 0ustar #!/usr/bin/python from cx_Freeze.setupwriter import main main() cx_Freeze-4.3.1/initscripts/0000755000000000000000000000000012053761025014503 5ustar rootrootcx_Freeze-4.3.1/initscripts/SharedLib.py0000775000076600012760000000132611776175120015162 0ustar #------------------------------------------------------------------------------ # SharedLib.py # Initialization script for cx_Freeze which behaves similarly to the one for # console based applications but must handle the case where Python has already # been initialized and another DLL of this kind has been loaded. As such it # does not block the path unless sys.frozen is not already set. #------------------------------------------------------------------------------ import encodings import os import sys import warnings if not hasattr(sys, "frozen"): sys.frozen = True sys.path = sys.path[:4] os.environ["TCL_LIBRARY"] = os.path.join(DIR_NAME, "tcl") os.environ["TK_LIBRARY"] = os.path.join(DIR_NAME, "tk") cx_Freeze-4.3.1/initscripts/Console.py0000775000076600012760000000224711776175120014732 0ustar #------------------------------------------------------------------------------ # Console.py # Initialization script for cx_Freeze which manipulates the path so that the # directory in which the executable is found is searched for extensions but # no other directory is searched. It also sets the attribute sys.frozen so that # the Win32 extensions behave as expected. #------------------------------------------------------------------------------ import os import sys import zipimport sys.frozen = True sys.path = sys.path[:4] os.environ["TCL_LIBRARY"] = os.path.join(DIR_NAME, "tcl") os.environ["TK_LIBRARY"] = os.path.join(DIR_NAME, "tk") m = __import__("__main__") importer = zipimport.zipimporter(INITSCRIPT_ZIP_FILE_NAME) if INITSCRIPT_ZIP_FILE_NAME != SHARED_ZIP_FILE_NAME: moduleName = m.__name__ else: name, ext = os.path.splitext(os.path.basename(os.path.normcase(FILE_NAME))) moduleName = "%s__main__" % name code = importer.get_code(moduleName) exec code in m.__dict__ versionInfo = sys.version_info[:3] if versionInfo >= (2, 5, 0) and versionInfo <= (2, 6, 4): module = sys.modules.get("threading") if module is not None: module._shutdown() cx_Freeze-4.3.1/initscripts/SharedLibSource.py0000775000076600012760000000171111776175120016341 0ustar #------------------------------------------------------------------------------ # SharedLibSource.py # Initialization script for cx_Freeze which imports the site module (as per # normal processing of a Python script) and then searches for a file with the # same name as the shared library but with the extension .pth. The entries in # this file are used to modify the path to use for subsequent imports. #------------------------------------------------------------------------------ import os import sys import warnings # the site module must be imported for normal behavior to take place; it is # done dynamically so that cx_Freeze will not add all modules referenced by # the site module to the frozen executable __import__("site") # now locate the pth file to modify the path appropriately baseName, ext = os.path.splitext(FILE_NAME) pathFileName = baseName + ".pth" sys.path = [s.strip() for s in file(pathFileName).read().splitlines()] + \ sys.path cx_Freeze-4.3.1/initscripts/Console3.py0000775000076600012760000000175111776175120015014 0ustar #------------------------------------------------------------------------------ # Console3.py # Initialization script for cx_Freeze which manipulates the path so that the # directory in which the executable is found is searched for extensions but # no other directory is searched. It also sets the attribute sys.frozen so that # the Win32 extensions behave as expected. #------------------------------------------------------------------------------ import os import sys import zipimport sys.frozen = True sys.path = sys.path[:4] os.environ["TCL_LIBRARY"] = os.path.join(DIR_NAME, "tcl") os.environ["TK_LIBRARY"] = os.path.join(DIR_NAME, "tk") m = __import__("__main__") importer = zipimport.zipimporter(INITSCRIPT_ZIP_FILE_NAME) if INITSCRIPT_ZIP_FILE_NAME != SHARED_ZIP_FILE_NAME: moduleName = m.__name__ else: name, ext = os.path.splitext(os.path.basename(os.path.normcase(FILE_NAME))) moduleName = "%s__main__" % name code = importer.get_code(moduleName) exec(code, m.__dict__) cx_Freeze-4.3.1/initscripts/ConsoleSetLibPath.py0000775000076600012760000000262611776175120016653 0ustar #------------------------------------------------------------------------------ # ConsoleSetLibPath.py # Initialization script for cx_Freeze which manipulates the path so that the # directory in which the executable is found is searched for extensions but # no other directory is searched. The environment variable LD_LIBRARY_PATH is # manipulated first, however, to ensure that shared libraries found in the # target directory are found. This requires a restart of the executable because # the environment variable LD_LIBRARY_PATH is only checked at startup. #------------------------------------------------------------------------------ import encodings import os import sys import warnings import zipimport paths = os.environ.get("LD_LIBRARY_PATH", "").split(os.pathsep) if DIR_NAME not in paths: paths.insert(0, DIR_NAME) os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(paths) os.execv(sys.executable, sys.argv) sys.frozen = True sys.path = sys.path[:4] os.environ["TCL_LIBRARY"] = os.path.join(DIR_NAME, "tcl") os.environ["TK_LIBRARY"] = os.path.join(DIR_NAME, "tk") m = __import__("__main__") importer = zipimport.zipimporter(INITSCRIPT_ZIP_FILE_NAME) code = importer.get_code(m.__name__) exec code in m.__dict__ versionInfo = sys.version_info[:3] if versionInfo >= (2, 5, 0) and versionInfo <= (2, 6, 4): module = sys.modules.get("threading") if module is not None: module._shutdown() cx_Freeze-4.3.1/initscripts/ConsoleKeepPath.py0000775000076600012760000000122611776175120016350 0ustar #------------------------------------------------------------------------------ # ConsoleKeepPath.py # Initialization script for cx_Freeze which leaves the path alone and does # not set the sys.frozen attribute. #------------------------------------------------------------------------------ import sys import zipimport m = __import__("__main__") importer = zipimport.zipimporter(INITSCRIPT_ZIP_FILE_NAME) code = importer.get_code(m.__name__) exec code in m.__dict__ versionInfo = sys.version_info[:3] if versionInfo >= (2, 5, 0) and versionInfo <= (2, 6, 4): module = sys.modules.get("threading") if module is not None: module._shutdown() cx_Freeze-4.3.1/initscripts/ConsoleKeepPath3.py0000775000076600012760000000073011776175120016432 0ustar #------------------------------------------------------------------------------ # ConsoleKeepPath3.py # Initialization script for cx_Freeze which leaves the path alone and does # not set the sys.frozen attribute. #------------------------------------------------------------------------------ import sys import zipimport m = __import__("__main__") importer = zipimport.zipimporter(INITSCRIPT_ZIP_FILE_NAME) code = importer.get_code(m.__name__) exec(code, m.__dict__) cx_Freeze-4.3.1/setup.py0000775000076600012760000002264312053100321012073 0ustar """ Distutils script for cx_Freeze. """ import cx_Freeze import distutils.command.bdist_rpm import distutils.command.build_ext import distutils.command.install import distutils.command.install_data import distutils.sysconfig import os import sys from distutils.core import setup from distutils.extension import Extension if sys.platform == "win32": import msilib import distutils.command.bdist_msi class bdist_msi(distutils.command.bdist_msi.bdist_msi): def add_scripts(self): distutils.command.bdist_msi.bdist_msi.add_scripts(self) msilib.add_data(self.db, "RemoveFile", [("cxFreezeBatch", "cx_Freeze", "cxfreeze*.bat", "Scripts", 2)]) class bdist_rpm(distutils.command.bdist_rpm.bdist_rpm): # rpm automatically byte compiles all Python files in a package but we # don't want that to happen for initscripts and samples so we tell it to # ignore those files def _make_spec_file(self): specFile = distutils.command.bdist_rpm.bdist_rpm._make_spec_file(self) specFile.insert(0, "%define _unpackaged_files_terminate_build 0%{nil}") return specFile def run(self): distutils.command.bdist_rpm.bdist_rpm.run(self) specFile = os.path.join(self.rpm_base, "SPECS", "%s.spec" % self.distribution.get_name()) queryFormat = "%{name}-%{version}-%{release}.%{arch}.rpm" command = "rpm -q --qf '%s' --specfile %s" % (queryFormat, specFile) origFileName = os.popen(command).read() parts = origFileName.split("-") parts.insert(2, "py%s%s" % sys.version_info[:2]) newFileName = "-".join(parts) self.move_file(os.path.join("dist", origFileName), os.path.join("dist", newFileName)) class build_ext(distutils.command.build_ext.build_ext): def build_extension(self, ext): if ext.name.find("bases") < 0: distutils.command.build_ext.build_ext.build_extension(self, ext) return if sys.platform == "win32": if sys.version_info[:2] < (2, 6): ext.sources.append("source/bases/dummy.rc") elif self.compiler.compiler_type == "mingw32": ext.sources.append("source/bases/manifest.rc") os.environ["LD_RUN_PATH"] = "${ORIGIN}:${ORIGIN}/../lib" objects = self.compiler.compile(ext.sources, output_dir = self.build_temp, include_dirs = ext.include_dirs, debug = self.debug, depends = ext.depends) fileName = os.path.splitext(self.get_ext_filename(ext.name))[0] fullName = os.path.join(self.build_lib, fileName) libraryDirs = ext.library_dirs or [] libraries = self.get_libraries(ext) extraArgs = ext.extra_link_args or [] if sys.platform != "win32": vars = distutils.sysconfig.get_config_vars() if not vars.get("Py_ENABLE_SHARED", 0): libraryDirs.append(vars["LIBPL"]) libraries.append("python%s.%s" % sys.version_info[:2]) if vars["LINKFORSHARED"] and sys.platform != "darwin": extraArgs.extend(vars["LINKFORSHARED"].split()) if vars["LIBS"]: extraArgs.extend(vars["LIBS"].split()) if vars["LIBM"]: extraArgs.append(vars["LIBM"]) if vars["BASEMODLIBS"]: extraArgs.extend(vars["BASEMODLIBS"].split()) if vars["LOCALMODLIBS"]: extraArgs.extend(vars["LOCALMODLIBS"].split()) extraArgs.append("-s") elif ext.name.find("Win32GUI") > 0 \ and self.compiler.compiler_type == "mingw32": extraArgs.append("-mwindows") self.compiler.link_executable(objects, fullName, libraries = libraries, library_dirs = libraryDirs, runtime_library_dirs = ext.runtime_library_dirs, extra_postargs = extraArgs, debug = self.debug) def get_ext_filename(self, name): fileName = distutils.command.build_ext.build_ext.get_ext_filename(self, name) if name.endswith("util"): return fileName vars = distutils.sysconfig.get_config_vars() soExt = vars["SO"] ext = self.compiler.exe_extension or "" return fileName[:-len(soExt)] + ext class install(distutils.command.install.install): def get_sub_commands(self): subCommands = distutils.command.install.install.get_sub_commands(self) subCommands.append("install_packagedata") return subCommands class install_packagedata(distutils.command.install_data.install_data): def run(self): installCommand = self.get_finalized_command("install") installDir = getattr(installCommand, "install_lib") sourceDirs = ["samples", "initscripts"] while sourceDirs: sourceDir = sourceDirs.pop(0) targetDir = os.path.join(installDir, "cx_Freeze", sourceDir) self.mkpath(targetDir) for name in os.listdir(sourceDir): if name in ("build", "CVS") or name.startswith("."): continue fullSourceName = os.path.join(sourceDir, name) if os.path.isdir(fullSourceName): sourceDirs.append(fullSourceName) else: fullTargetName = os.path.join(targetDir, name) self.copy_file(fullSourceName, fullTargetName) self.outfiles.append(fullTargetName) def find_cx_Logging(): dirName = os.path.dirname(os.getcwd()) loggingDir = os.path.join(dirName, "cx_Logging") if not os.path.exists(loggingDir): return subDir = "implib.%s-%s" % (distutils.util.get_platform(), sys.version[:3]) importLibraryDir = os.path.join(loggingDir, "build", subDir) if not os.path.exists(importLibraryDir): return return loggingDir, importLibraryDir commandClasses = dict( build_ext = build_ext, bdist_rpm = bdist_rpm, install = install, install_packagedata = install_packagedata) if sys.platform == "win32": commandClasses["bdist_msi"] = bdist_msi # generate C source for base frozen modules subDir = "temp.%s-%s" % (distutils.util.get_platform(), sys.version[:3]) baseModulesDir = os.path.join("build", subDir) baseModulesFileName = os.path.join(baseModulesDir, "BaseModules.c") finder = cx_Freeze.ModuleFinder(bootstrap = True) finder.WriteSourceFile(baseModulesFileName) # build utility module if sys.platform == "win32": libraries = ["imagehlp", "Shlwapi"] else: libraries = [] utilModule = Extension("cx_Freeze.util", ["source/util.c"], libraries = libraries) # build base executables docFiles = "README.txt" scripts = ["cxfreeze", "cxfreeze-quickstart"] options = dict(bdist_rpm = dict(doc_files = docFiles), install = dict(optimize = 1)) depends = ["source/bases/Common.c"] fullDepends = depends + [baseModulesFileName] includeDirs = [baseModulesDir] console = Extension("cx_Freeze.bases.Console", ["source/bases/Console.c"], depends = fullDepends, include_dirs = includeDirs) consoleKeepPath = Extension("cx_Freeze.bases.ConsoleKeepPath", ["source/bases/ConsoleKeepPath.c"], depends = depends) extensions = [utilModule, console, consoleKeepPath] if sys.platform == "win32": scripts.append("cxfreeze-postinstall") options["bdist_msi"] = dict(install_script = "cxfreeze-postinstall") gui = Extension("cx_Freeze.bases.Win32GUI", ["source/bases/Win32GUI.c"], include_dirs = includeDirs, depends = fullDepends, libraries = ["user32"]) extensions.append(gui) moduleInfo = find_cx_Logging() if moduleInfo is not None and sys.version_info[:2] < (3, 0): includeDir, libraryDir = moduleInfo includeDirs.append(includeDir) service = Extension("cx_Freeze.bases.Win32Service", ["source/bases/Win32Service.c"], depends = fullDepends, library_dirs = [libraryDir], libraries = ["advapi32", "cx_Logging"], include_dirs = includeDirs) extensions.append(service) classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: Python Software Foundation License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: C", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development :: Build Tools", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: System :: Software Distribution", "Topic :: Utilities" ] setup(name = "cx_Freeze", description = "create standalone executables from Python scripts", long_description = "create standalone executables from Python scripts", version = "4.3.1", cmdclass = commandClasses, options = options, ext_modules = extensions, packages = ['cx_Freeze'], maintainer="Anthony Tuininga", maintainer_email="anthony.tuininga@gmail.com", url = "http://cx-freeze.sourceforge.net", scripts = scripts, classifiers = classifiers, keywords = "freeze", license = "Python Software Foundation License") cx_Freeze-4.3.1/PKG-INFO0000644000000000000000000000177012053761027013234 0ustar rootrootMetadata-Version: 1.0 Name: cx_Freeze Version: 4.3.1 Summary: create standalone executables from Python scripts Home-page: http://cx-freeze.sourceforge.net Author: Anthony Tuininga Author-email: anthony.tuininga@gmail.com License: Python Software Foundation License Description: create standalone executables from Python scripts Keywords: freeze Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Python Software Foundation License Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Programming Language :: C Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Software Development :: Build Tools Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: System :: Software Distribution Classifier: Topic :: Utilities cx_Freeze-4.3.1/MANIFEST.in0000664000076600012760000000025112000121267012107 0ustar include MANIFEST.in include *.txt recursive-include doc *.html recursive-include initscripts *.py recursive-include samples *.py recursive-include source *.c *.rc *.txt cx_Freeze-4.3.1/README.txt0000664000076600012760000000022412050622533012056 0ustar Please see http://cx_freeze.readthedocs.org for documentation on how to use cx_Freeze. To build: python setup.py build python setup.py install cx_Freeze-4.3.1/cxfreeze0000775000076600012760000000006711776175117012145 0ustar #!/usr/bin/python from cx_Freeze import main main()