Hi, I'm very new to Python and programing in general and wanted to learn how to use the py2exe module. I think I've done the setup alright but I get an error message. Everything runs along smoothly until it start to make the dist folder. When it begins to make it i get and error message in Windows that says that py2exe_util.pyd is not a valid Windows image. Then I get an error message in the command prompt saying that DLL load failed with error code 193. I think the problem has something to do with py2exe_util but I don't know how to fix it. Does anyone know why this happens and how to fix it? By the way I'm using Windows XP.

I'm including my setup code just in case:

from distutils.core import setup
import py2exe


I know the code is very simple but this was just something to test if the module worked

Thanks in advance

10 Years
Discussion Span
Last Post by patratacus

I've tried your advice the program is certainly easier to use, but I still get an error message. I run the program and it creates the setup file, but when the file runs I get an error it says the file can't be found. Then if I run the setup file created in IDLE, when it runs it just asks me if I want to exit altoghether. Also, I've tried adding the patch that is recommended to be added to build_exe.py and I get an error when I run it. I fixed the indentation but the is an invalid sintax error in the patch. I sent the built_exe module with the patch included to see if maybe I made a mistake inserting it but I dont think I did. I think the main problem is with the py2exe module, do I have to write the programs I want to convert in the py2exe folder or something?
This is the error message in case it helps: Execution of command 'python-u "PATH TO PROGRAM CREATED BY THE GUI" py2exe' failed (error 2: the system cannot find the file specified)
If I save the python document the GUI creates but cannot run and run it seperatly, I get the following error:

Traceback (most recent call last):
  File "PATH", line 120, in <module>
    windows = [test_wx]
  File "C:\Python25\lib\distutils\core.py", line 139, in setup
    raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg
SystemExit: usage: tmpnwys32.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: tmpnwys32.py --help [cmd1 cmd2 ...]
   or: tmpnwys32.py --help-commands
   or: tmpnwys32.py cmd --help

error: no commands supplied


# Changes:
#    can now specify 'zipfile = None', in this case the Python module
#    library archive is appended to the exe.

# Todo:
# Make 'unbuffered' a per-target option

from distutils.core import Command
from distutils.spawn import spawn
from distutils.errors import *
import sys, os, imp, types, stat
import marshal
import zipfile
import sets
import tempfile
import struct

is_win64 = struct.calcsize("P") == 8

def _is_debug_build():
    for ext, _, _ in imp.get_suffixes():
        if ext == "_d.pyd":
            return True
    return False

is_debug_build = _is_debug_build()

if is_debug_build:
    python_dll = "python%d%d_d.dll" % sys.version_info[:2]
    python_dll = "python%d%d.dll" % sys.version_info[:2]

# resource constants

# note: we cannot use the list from imp.get_suffixes() because we want
# .pyc and .pyo, independent of the optimize flag.
_py_suffixes = ['.py', '.pyo', '.pyc', '.pyw']
_c_suffixes = [_triple[0] for _triple in imp.get_suffixes()
               if _triple[2] == imp.C_EXTENSION]

def imp_find_module(name):
    # same as imp.find_module, but handles dotted names
    names = name.split('.')
    path = None
    for name in names:
        result = imp.find_module(name, path)
        path = [result[1]]
    return result

def fancy_split(str, sep=","):
    # a split which also strips whitespace from the items
    # passing a list or tuple will return it unchanged
    if str is None:
        return []
    if hasattr(str, "split"):
        return [item.strip() for item in str.split(sep)]
    return str

# This loader locates extension modules relative to the library.zip
# file when an archive is used (i.e., skip_archive is not used), otherwise
# it locates extension modules relative to sys.prefix.
LOADER = """
def __load():
    import imp, os, sys
        dirname = os.path.dirname(__loader__.archive)
    except NameError:
        dirname = sys.prefix
    path = os.path.join(dirname, '%s')
    #print "py2exe extension module", __name__, "->", path
    mod = imp.load_dynamic(__name__, path)
##    mod.frozen = 1
del __load

# A very loosely defined "target".  We assume either a "script" or "modules"
# attribute.  Some attributes will be target specific.
class Target:
    def __init__(self, **kw):
        # If modules is a simple string, assume they meant list
        m = self.__dict__.get("modules")
        if m and type(m) in types.StringTypes:
            self.modules = [m]
    def get_dest_base(self):
        dest_base = getattr(self, "dest_base", None)
        if dest_base: return dest_base
        script = getattr(self, "script", None)
        if script:
            return os.path.basename(os.path.splitext(script)[0])
        modules = getattr(self, "modules", None)
        assert modules, "no script, modules or dest_base specified"
        return modules[0].split(".")[-1]

    def validate(self):
        resources = getattr(self, "bitmap_resources", []) + \
                    getattr(self, "icon_resources", [])
        for r_id, r_filename in resources:
            if type(r_id) != type(0):
                raise DistutilsOptionError, "Resource ID must be an integer"
            if not os.path.isfile(r_filename):
                raise DistutilsOptionError, "Resource filename '%s' does not exist" % r_filename

def FixupTargets(targets, default_attribute):
    if not targets:
        return targets
    ret = []
    for target_def in targets:
        if type(target_def) in types.StringTypes :
            # Create a default target object, with the string as the attribute
            target = Target(**{default_attribute: target_def})
            d = getattr(target_def, "__dict__", target_def)
            if not d.has_key(default_attribute):
                raise DistutilsOptionError, \
                      "This target class requires an attribute '%s'" % default_attribute
            target = Target(**d)
    return ret

class py2exe(Command):
    description = ""
    # List of option tuples: long name, short name (None if no short
    # name), and help string.
    user_options = [
        ('optimize=', 'O',
         "optimization level: -O1 for \"python -O\", "
         "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
        ('dist-dir=', 'd',
         "directory to put final built distributions in (default is dist)"),

        ("excludes=", 'e',
         "comma-separated list of modules to exclude"),
        ("dll-excludes=", None,
         "comma-separated list of DLLs to exclude"),
        ("ignores=", None,
         "comma-separated list of modules to ignore if they are not found"),
        ("includes=", 'i',
         "comma-separated list of modules to include"),
        ("packages=", 'p',
         "comma-separated list of packages to include"),

        ("compressed", 'c',
         "create a compressed zipfile"),

        ("xref", 'x',
         "create and show a module cross reference"),

        ("bundle-files=", 'b',
         "bundle dlls in the zipfile or the exe. Valid levels are 1, 2, or 3 (default)"),

        ("skip-archive", None,
         "do not place Python bytecode files in an archive, put them directly in the file system"),

        ("ascii", 'a',
         "do not automatically include encodings and codecs"),

        ('custom-boot-script=', None,
         "Python file that will be run when setting up the runtime environment"),

    boolean_options = ["compressed", "xref", "ascii", "skip-archive"]

    def initialize_options (self):
        self.xref =0
        self.compressed = 0
        self.unbuffered = 0
        self.optimize = 0
        self.includes = None
        self.excludes = None
        self.ignores = None
        self.packages = None
        self.dist_dir = None
        self.dll_excludes = None
        self.typelibs = None
        self.bundle_files = 3
        self.skip_archive = 0
        self.ascii = 0
        self.custom_boot_script = None

    def finalize_options (self):
        self.optimize = int(self.optimize)
        self.excludes = fancy_split(self.excludes)
        self.includes = fancy_split(self.includes)
        self.ignores = fancy_split(self.ignores)
        self.bundle_files = int(self.bundle_files)
        if self.bundle_files < 1 or self.bundle_files > 3:
            raise DistutilsOptionError, \
                  "bundle-files must be 1, 2, or 3, not %s" % self.bundle_files
        if is_win64 and self.bundle_files < 3:
            raise DistutilsOptionError, \
                  "bundle-files %d not yet supported on win64" % self.bundle_files
        if self.skip_archive:
            if self.compressed:
                raise DistutilsOptionError, \
                      "can't compress when skipping archive"
            if self.distribution.zipfile is None:
                raise DistutilsOptionError, \
                      "zipfile cannot be None when skipping archive"
        # includes is stronger than excludes
        for m in self.includes:
            if m in self.excludes:
        self.packages = fancy_split(self.packages)
                                   ('dist_dir', 'dist_dir'))
        self.dll_excludes = [x.lower() for x in fancy_split(self.dll_excludes)]

    def run(self):
        build = self.reinitialize_command('build')
        sys_old_path = sys.path[:]
        if build.build_platlib is not None:
            sys.path.insert(0, build.build_platlib)
        if build.build_lib is not None:
            sys.path.insert(0, build.build_lib)
            sys.path = sys_old_path

    def _run(self):

        dist = self.distribution

        # all of these contain module names
        required_modules = []
        for target in dist.com_server + dist.service + dist.ctypes_com_server:
        # and these contains file names
        required_files = [target.script
                          for target in dist.windows + dist.console]

        mf = self.create_modulefinder()

        # These are the name of a script, but used as a module!
        for f in dist.isapi:

        if self.typelibs:
            print "*** generate typelib stubs ***"
            from distutils.dir_util import mkpath
            genpy_temp = os.path.join(self.temp_dir, "win32com", "gen_py")
            num_stubs = collect_win32com_genpy(genpy_temp,
            print "collected %d stubs from %d type libraries" \
                  % (num_stubs, len(self.typelibs))
            mf.load_package("win32com.gen_py", genpy_temp)

        # monkey patching the compile builtin.
        # The idea is to include the filename in the error message
        orig_compile = compile
        import __builtin__
        def my_compile(source, filename, *args):
                result = orig_compile(source, filename, *args)
            except Exception, details:
                raise DistutilsError, "compiling '%s' failed\n    %s: %s" % \
                      (filename, details.__class__.__name__, details)
            return result
        __builtin__.compile = my_compile

        print "*** searching for required modules ***"
        self.find_needed_modules(mf, required_files, required_modules)

        print "*** parsing results ***"
        py_files, extensions, builtins = self.parse_mf_results(mf)

        if self.xref:

        print "*** finding

This might be really old, but maybe you are still looking for an answer. I had the same problem, but I then found out that I had the wrong version of py2exe. I downloaded the 64-bit window version instead of the 32-bit version. Check to make sure that you have the right version or py2exe will not work.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.