Home >Backend Development >Python Tutorial >How Can I Convert My Python Script (.py) to an Executable (.exe)?

How Can I Convert My Python Script (.py) to an Executable (.exe)?

Barbara Streisand
Barbara StreisandOriginal
2024-12-30 15:32:09730browse

How Can I Convert My Python Script (.py) to an Executable (.exe)?

Converting Python Scripts (.py) to Executables (.exe)

Problem: Converting a Python program to an executable for wider usage.

Answer:

Using cx_Freeze:

  1. Install cx_Freeze using pip install cx_Freeze.
  2. Install idna using pip install idna.
  3. Create a setup.py script in the script's directory.
  4. Copy the following code into setup.py and save it:

    from cx_Freeze import setup, Executable
    
    base = None
    
    executables = [Executable("myfirstprog.py", base=base)]
    
    packages = ["idna"]
    options = {
     'build_exe': {
         'packages': packages,
     },
    }
    
    setup(
     name="<any name>",
     options=options,
     version="<any number>",
     description='<any description>',
     executables=executables
    )

    Note: Replace "myfirstprog.py" with the actual script name.

  5. Open a command prompt in the script's directory and execute python setup.py build.
  6. A new folder named "build" will be created, containing the compiled .exe file.

Additional Notes:

  • Ensure that imported packages are included in the "packages" list in setup.py.
  • Customize the name, version, and description fields in setup.py according to your program.
  • Installed packages (e.g., idna) must be available before compiling.

The above is the detailed content of How Can I Convert My Python Script (.py) to an Executable (.exe)?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn