Auto py to exe error

After helping many of people fix issues with auto-py-to-exe and PyInstaller, this post contains what I think you should understand and ways to fix issues you are having with auto-py-to-exe.

After helping many of people fix issues with auto-py-to-exe and PyInstaller, this post contains what I think you should understand and ways to fix issues you are having with auto-py-to-exe.

  • Introduction
    • A Small Disclaimer
  • What is auto-py-to-exe?
  • Installation
    • Possible Gevent Issue
  • The Layout of the Interface and What Things Do
  • General Steps
  • Debugging
    • How to Fix Specific Issues
      • Fatal Error: failed to execute
      • PermissionError: [Errno 13] Permission denied: …
      • FileNotFoundError: [Errno 2] No such file or directory
      • RecursionError
      • AttributeError: module ‘enum’ has no attribute ‘IntFlag’
      • ModuleNotFoundError: No module named x / ImportError: No module named x
      • ERR_CONNECTION_REFUSED
      • Command «python setup.py egg_info» failed with error code 1
      • FileNotFoundError
      • struct.error: unpack requires a buffer of 16 bytes
  • General Questions Constantly Asked
    • How do I Convert All My Python Files?
    • The Terminal Just Opens and Closes But There Are No Errors
    • ‘python’/’pip’/’auto-py-to-exe’ is not recognised as an internal or external command, operable program or batch file.
    • The exe Doesn’t Work on Another Computer
    • Can I Create an Executable on One Operating System and Run it on Another?
    • What is the __pycache__ folder?
    • My Antivirus Detected the exe as a Virus
    • Lots of Warnings Appear in the Output
    • The Output Executable is Huge
    • «VCRUNTIME140.dll» is either not designed to run on Windows or it contains an error
    • LoadLibraryEx / The file cannot be accessed by the system
    • The exe Runs But Does Some Unexpected Things
  • Additional Information and Explanations
    • Using concurrent.futures
    • The Difference Between One Directory and One File
      • Demonstration of Files References After Packaging
        • Running this un-packaged (.py)
        • Running this when packaged using one directory
        • Running this when packaged using one file
    • The one-file Resource Wrapper

Introduction

A while ago I wrote an article on common issues when using auto-py-to-exe. In this post, I aim to replace that post and explain more in greater depth.

Please do not feel offended if I have referred you to this page, it’s just the case that many other people have asked the same question you are asking and you haven’t been able to find the answers I or others have provided.

A Small Disclaimer

I cannot guarantee this post or any advice I give will fix all your issues with auto-py-to-exe and PyInstaller. This tool allows you to select options and give data to be fed into PyInstaller, that means that a lot of the errors that occur will be raised by PyInstaller, meaning I can’t go and change how it works. Typically though, errors brought up in PyInstaller are due to incorrect configuration, thus this post aims to help you fix anything set up incorrectly.

If you have an issue that isn’t mentioned in this post, chuck it in the comments below and I will look into adding it if we can find a solution.

What is auto-py-to-exe?

auto-py-to-exe is a project I made in my free time to make packaging Python scripts to an executable/bundle easier. The interface uses Chromes app mode and a small Python server in the backend.

When the user presses «Convert .py to .exe», all the data in the interface is sent to PyInstaller and then the output from PyInstaller is sent back to the interface. auto-py-to-exe then cleans things up in the background when done (files/folders generated by PyInstaller) and allows you to find your project in the output folder in your current working directory.

Installation

To install auto-py-to-exe, make sure you have Python 3.4 or above installed. Ideally, you will also want Chrome installed but this is not a must; it will open in your default browser if Chrome is not found and the only thing different will be the interface size. Execute the following in the command prompt / terminal to install auto-py-to-exe:

python -m pip install auto-py-to-exe

Wait for this to finish and make sure that the last line contains «Successfully installed auto-py-to-exe» dash some version. You might get a message about your version of pip but you can ignore it. Now to run the project, execute the following in the terminal:

This will open auto-py-to-exe and the output will be saved in output/ in where your current working directory is.

Possible Gevent Issue

There could be a situation when installing auto-py-to-exe that you are told you require Microsoft Visual C++ Build Tools. This occurs because the file that was downloaded from PyPI to be installed needs to be built and these tools will build it.

Generally, the way to fix this would be to install the tools and run it again, but instead, you can get a pre-built version. To do this, go to gevents PyPI page and click «Download files» on the right to bring you to the files that are on PyPI for this project. You will want to find the file that matches your setup and is a .whl file, for example, I am using Python 3.7 on Windows so I would look for cp37 in the «Python version» column, Wheel in the «File type» column and then in the files that match these two criteria, match my OS — Windows. This means the file I will want is gevent-1.3.7-cp37-cp37m-win_amd64.whl (currently gevent is at 1.3.7).

The Layout of the Interface and What Things Do

auto-py-to-exe empty interface

At the top of the interface, you are asked for the script location. This is the script you call to run your project, so if your project is one script, put that here, if your project is more than one script, put the script that starts it here. The inputs outline will become blue if the file exists, otherwise it will be red.

Next, you need to choose between one-file and one-directory. These are relatively similar but when using one-file with extra files like images or data files you may need to modify your script to account for path changes. The difference between these methods and people ignoring the extra step required generally result in the bulk of complaints I get.

Under that is a selection of whether you want a console window to appear or not. Simply if you are developing a GUI application or something that doesn’t need the console to appear, use «Window Based». If you do want the console to appear, keep «Console Based Selected» but keep in mind that the script needs to block somewhere otherwise execution will end and the terminal will disappear immediately; a workaround for this is to put input() at the end of the script to hold execution until input is provided.

After this, you can select an icon for your executable. Make sure that the files are .ico and don’t just rename a file to be a .ico — that is not how file types work.

Next, there is a section to add files to your executable that are not Python files. Since PyInstaller doesn’t find extra files like images you need to add them manually. When adding an entry, the file path/folder path needs to the in the box on the left and the destination on the right; the destination is the folder in the executable.

  • If you put a folder on the left, all files will be placed in the folder (and sub-directories keeping structure) specified on the right.
  • If you put a file on the left, this file will be put in the folder specified with the filename the same as the original.

If you’re using one-file mode, you’ll be provided a link to stackoverflow which tells you how to implement a small wrapper to find the files you added. I explain why you have to do this towards the bottom of this post including an example; if you do not follow this step errors will occur.

Under this is the advanced tab which holds all PyInstallers extra flags as well as where to save the project and setting the maximum recursion depth. Here are a few flags/options that can help with things:

  • —name: The name of the output folder/executable
  • —hidden-import: If the executable says a module is missing, make sure you have it installed and add it here; you can separate multiple modules by a comma.
  • —debug: Set this to all to help make debugging a lot easier

The last tab is for auto-py-to-exe specific settings:

  • Output Directory: The directory that the output of the application is put into.
  • Increase Recursion Limit: If a RecursionError occurs, make sure this is enabled to set the depth to 5000.
  • Manual Argument Input: A simple input to manually add to the current command.

The «Current Command» section tells you what would be called if you wanted to execute this in a terminal and the convert button is under this. After the conversion, you can clear the output or open the output folder where the executable/package was saved.

General Steps

The process of packaging a Python project to an executable is simple in most cases.

  1. Start auto-py-to-exe by executing auto-py-to-exe in the terminal
  2. Search for your script
  3. Decide on whether you want the output to be a single executable or a directory (a directory has many benefits discussed later)
  4. Decide if you want a console window or not
  5. Add an icon if you desire
  6. Add any extra files your project requires that aren’t Python files (e.g. images, csv, databases, …)
  7. Click the big blue button at the bottom to package the project
  8. Open the location of the executable/package and run it

If you have any issues with running your script, it may be due to incorrect configuration. This means you will now have to go through a debugging process to find what is occurring.

Debugging

To debug, make sure you have set up the fields in auto-py-to-exe like you had previously — all your extra files and other settings. Now go to the «Advanced» section and under the title «How to generate» put all in the box beside —debug. This will print out messages to the console to help you debug.

When debugging, make sure you select the «Console Based» button and using «One Directory» will help remove basic problems; you can switch back to «One File» when there are no more bugs and then fix the ones associated with «One File» mode. When all bugs are removed, you can go back to «Window Based» if you wish.

Re-package your project and open up the command prompt / terminal and cd to the directory where the executable / package was output to. If you are using one-directory cd into that directory. Now execute ./my_project.exe (substitute the names). This will run the executable file and any errors you were missing before will be output to the console and preserved.

Look at what these errors are saying and fix them. Now repackage like you just did and keep fixing bugs and repackaging until there are no more left and your project is working properly. After this, you can then move to one-file if you were using one-directory and want one-file, and repeat the process by still staring it with cmd and debugging on.

When everything is done and there are no more bugs in the modes you want, you can enable «Window Based» if you want and remove all from —debug.

Not every project can be converted to one-file. This is due to files being used by the application being lost every time the application starts/stops. To understand this more go down to «Demonstration of Files References After Packaging».

How to Fix Specific Issues

These are some of the issues I have come across or others have asked me about and ways to fix them.

Fatal Error: failed to execute

This means something has gone wrong as it’s giving you a visual warning about it; this is not an error, it’s a warning; the real error has been printed to stdout/stderr. If you open the executable using the terminal or something else that will preserve the console output, you will most likely see a Python error telling you what went wrong. Fixing this and repackaging is the solution to this issue.

PermissionError: [Errno 13] Permission denied: …

This occurs because you are trying to modify files in a directory you do not have access to. A way to fix this is to run the script with admin privileges by opening cmd as admin and then running auto-py-to-exe one you have cd’ed to the directory you want the output to be in.

One reason this could occur is that you have opened cmd and am in System32. Make sure you do not accidentally modify files in this directory so make sure you are in a directory where you want to write files to when running auto-py-to-exe.

FileNotFoundError: [Errno 2] No such file or directory

This error is saying that a file you referenced does not exist. This can mean one of two things:

  • You have not included the file (you may have not realised you needed to as it is part of a library)
  • You have included the file but are not referencing it correctly

For situations where you have not included the file, you need to use the «Additional Files» section in the UI to add the required file or folder. You can identify the required file by looking at the error and then also work out the destination based on where it was being looked for.

When adding a file or folder in auto-py-to-exe, there are two boxes to fill out: the source location and the destination.

  • The source location is where the file currently is on your disk. Using «Add Files» or «Add Folder» will auto-populate this field for you.
  • The destination is where the file/folder will be put inside the final executable/folder. For example, if you have a file called icon.png and your code expects it to be in the folder «assets/images/» relative to your script, then you should put in «assets/images/».

For files that have been included but this error is still showing, package to one-directory instead of one-file to make sure things are working. Check out «The one-file Resource Wrapper» for a function that will help identify the root your application is currently running in.

RecursionError

This error is now prevented by the application by default by setting the recursion limit to 5000. If you want to disable this, there is an option in the Settings tab to.

AttributeError: module ‘enum’ has no attribute ‘IntFlag’

Try executing python -m pip uninstall enum34 to stop enum conflicts. This is also a fix for the similar issue «Fatal Python error: Py_Initialize: unable to load the file system codec».

ModuleNotFoundError: No module named x / ImportError: No module named x

This means a particular module (‘x’ in this case) was not added to the package. I have seen this occur with packages in the pandas library and win32api; as long as you can identify the package (e.g. ‘x’), then it is very easy to fix.

To fix this in the UI, open the advanced tab and find the --hidden-import input. Simply paste the module name into this input and then repackage. If the original error is still appearing, you have done this incorrectly.

For example, if you are missing pandas._libs.tslib, add ‘pandas._libs.tslib’ into the input by —hidden-import. Additionally, you can add more than one module, for example, pandas._libs.tslib, win32api. (See the question mark by the input for more information).

Alternatively, you may have installed auto-py-to-exe in one Python environment (a single installation or venv) and installed your dependent package in a different Python environment. Take a look at «How to Manage Multiple Python Distributions» for help on how to identify if you’ve done this.

ERR_CONNECTION_REFUSED

You need to be connected to the internet. This error appears when you cannot reach the servers.

Command «python setup.py egg_info» failed with error code 1

Update setuptools using pip install --upgrade setuptools.

FileNotFoundError

Make sure the file you are referencing actually exists, this error says that the file you are referencing doesn’t exist. If you are using one-file mode, make sure you have followed the necessary steps.

struct.error: unpack requires a buffer of 16 bytes

This typically occurs when you have supplied --icon / -i with a file that is not a .ico file. Please note that simply changing the extension of a file to .ico does not make it a .ico file; you will need to use a converter of some sort to convert your file (e.g. png, jpg) into a .ico.

General Questions Constantly Asked

How do I Convert All My Python Files?

Add the entry point in the script location. PyInstaller searches for imports to get the rest of the Python files required to run, so as long as you use the import keyword, your files will be added.

For example, if you have a layout like:

📂root
 ┣ 📂my_package
 ┃ ┣ 📜__init__.py
 ┃ ┣ 📜__main__.py
 ┃ ┗ 📜utils.py
 ┗ 📜start.py

Then package start.py — PyInstaller will find the rest as long as you are using the import keyword.

If you don’t have something like start.py and use your application like a module (python -m [module_name]) then create a file like start.py which imports the package and runs it as you would expect. For example, this is what I do with auto-py-to-exe:

from my_package import __main__

__main__.__name__ = '__main__' # Make it look like `my_package.__main__` is the main script
__main__.run()  # Call your main function if required

The Terminal Just Opens and Closes But There Are No Errors

If you double click to run your Python script, what happens? Does it open and close also? That means this tool has done its job correctly and the script is finishing just like it should.

You most likely think the output should stay visible because you are always using IDLE or an IDE and that’s what those tools do. Add a statement like input() at the end of your script to block execution and wait for you to press enter before closing.

Alternatively, there may be an error occurring which means you need to follow the debugging steps above.

‘python’/’pip’/’auto-py-to-exe’ is not recognised as an internal or external command, operable program or batch file.

This occurs because the path that these executables are located in is not on your path; thus cmd doesn’t know where to look for them. You need to add these paths to the PATH environment variable so cmd knows where to look for the executable you are trying to execute.

I created a script that can help set up these paths automatically, which can be found in my «Fix: ‘python’ is not recognized as an internal or external command» post.

If you want a more manual approach to understand what is occurring, watch my video on how to setup Pythons PIP. This will show you how to add the Scripts folder, but I also recommend you add the root Python directory (same path without ‘Scripts’) so the python command will work. The paths you will need to add can be found using the commands below:

import os, sys

# If 'python' is not recognised
print (os.path.dirname(sys.executable))

# If 'pip'/'auto-py-to-exe'/... is not recognised
print (os.path.dirname(sys.executable) + "\Scripts")

If you are using something older than Windows 10, setting the PATH environment variable will be a bit different than what is demonstrated in the video. If it is just one line, add a «;» to the end and then paste the path after the «;«.

The exe Doesn’t Work on Another Computer

This may be an architecture issue. PyInstaller will build an executable using the architecture of the machine it was built with. This means if you are using a 32bit machine, it will create a 64bit executable. As with any other programs, you cannot run 64bit on 32bit but you can run 32bit on 64bit. Thus I recommend using 32bit python or compiling on a 32bit machine so it will work on both architectures.

Can I Create an Executable on One Operating System and Run it on Another?

PyInstaller’s documentation states:

PyInstaller is tested against Windows, MacOS X, and Linux. However, it is not a cross-compiler; to make a Windows app you run PyInstaller on Windows, and to make a Linux app you run it on Linux, etc.

PyInstaller is cross-platform, meaning the tool itself works on many operating systems, however it is not a cross-compiler, meaning the output from the tool cannot run across multiple operating systems.

There are ways to use things like «wine» on Linux to create an executable on Linux that can run on Windows, but this is out of the scope of PyInstaller.

What is the __pycache__ folder?

This is Python bytecode generated by Python. You can delete this if you wish.

My Antivirus Detected the exe as a Virus

This is your anti-virus vendors fault. Check out this. There is nothing I or PyInstaller can do to stop this. After seeing this pop up a lot more recently I stated in brentvollebregt/auto-py-to-exe#122 that you have a few options:

  • Tell your antivirus that these files are fine
  • Switch to a different and more accurate anti-virus
  • Notify your antivirus vendor about the false positive

Typically files are quarantined during the build process which is done within a temporary directory by default.
This directory can be overridden using the --build-directory-override [FOLDER_PATH] argument.
From here, if you whitelist your custom build directory and the output directory, you could potentially stop your antivirus from quarantining the files.

Lots of Warnings Appear in the Output

These warnings can be ignored in most cases. I have not currently found a situation where these are an issue, after all, they are only warnings. These warnings typically match the format WARNING: lib not found: api-ms-win-crt-<specific dll> dependency of <file>.

A YouTube user comment on the video related to this project that if you add C:WindowsSystem32downlevel to your PATH variable, these DLLS that were previously not being found can now be found. This is because the files missing are commonly found in this folder. Adding this folder to your path to now successfully locate these files can also speed up packaging times.

The Output Executable is Huge

Sometimes pyinstaller tries to be smart and will add packages it sees in your environment even if you are not using them in the project being packaged. This can lead to output executables being tens to hundreds of megabytes in size.

To get around this, the easiest way would be to:

  1. Create a new/clean virtual environment
  2. Install auto-py-to-exe into it
  3. Install the required modules for your project
  4. Use the auto-py-to-exe in this virtual environment to package your script

Doing this will mean pyinstaller doesn’t see the packages you don’t need bundled which can lead to smaller packages.

«VCRUNTIME140.dll» is either not designed to run on Windows or it contains an error

Try selecting the --noupx button in the advanced tab.

LoadLibraryEx / The file cannot be accessed by the system

I have seen quite a few people get tracebacks containing the following error messages:

  • win32ctypes.pywin32.pywintypes.error: (1920, 'LoadLibraryEx', 'The file cannot be accessed by the system'
  • OSError: [WinError 1920] The file cannot be accessed by the system

Looking at the traceback for these situations, it is very common that I see a path like C:Users<USER>AppDataLocalPackagesPythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0LocalCache... which tells me they’re using Python from the Windows Store. As stated in pyinstaller/pyinstaller#4941, we have been told by a maintainer that:

We don’t support using python from the windows store when not using a virtual environment. Please use a virtual environment; that should fix this.

So to fix this issue, download a distribution of Python from python.org or use a virtual environment. This solution is also noted in brentvollebregt/auto-py-to-exe#141.

Supporting Stack Overflow questions here, here and here.

If you install Python from python.org to fix this issue, you will need to install auto-py-to-exe in this new distribution. You will then also need to make sure you execute auto-py-to-exe from the newly installed distribution and not the old python from the windows store distribution. Executing where auto-py-to-exe can tell you where it will be execute from (the top result).

The exe Runs But Does Some Unexpected Things

A lot of people say their python script runs fine in IDLE, PyCharm, Conda or something similar but after packaging, the executable functions differently.

Examples of executables functioning differently include but are not limited to:

  • A console window appearing
  • Console windows appearing and closing

This difference is most likely because the script is now running in a different environment or started in a different way.

If you double-click your exe to run it, you can test how your script will run before packaging by doing the following:

  1. Set the default application for .py files on your machine to the python.exe binary you are using to run your .py file
  2. Double-click on your .py script to run it
  3. Witness how your application runs

If you are packaging to a single .exe file (onefile), set pythonw.exe as the default application for .py files rather than python.exe.

If your script doesn’t run as expected when following this, it shows there is something wrong with the implementation of your script.

Additional Information and Explanations

Some things that are clear to people that use Python a lot are not always clear to new people. Here are some discussions about why and how things occur.

Using concurrent.futures

It was brought to my attention by William Lake in this GitHub issue that when using concurrent.futures for any multi-threading/processing, it is recommended to add the following import:

from multiprocessing import freeze_support

and this line to your main:

William had stated that before adding these lines, he kept getting errors regarding concurrent.futures even though it worked fine before packaging.

A related issue on bugs.python.org recommending the fix

The Difference Between One Directory and One File

One directory puts all your files in one folder. You can easily add and remove files like you normally would in a folder. When your script modifies a file in its folder, the file will still be modified when you run the script again.

One file mode is a bit different, instead of putting all the files in a folder, it puts them in something like a zip file which is contained in the end executable. When you run the executable, the files contained internally are unpacked to a new temporary directory. Due to one file unpacking on startup, it is a lot slower to start.

Also due to the files being unpacked to a new temporary directory on execution, the files that you modified added that were in the same directory as the executable will not be there on the next run because they are now in a different unknown folder. This means when creating files, you will want to use an absolute path that is not where the project files are (could use something like APPDATA on Windows).

Demonstration of Files References After Packaging

I made a small Python file that finds where it is located and then tries to print the contents of a file if it exists otherwise will create a new one.

import sys, os
if getattr(sys, 'frozen', False): # we are running in a bundle
    bundle_dir = sys._MEIPASS # This is where the files are unpacked to
else: # normal Python environment
    bundle_dir = os.path.dirname(os.path.abspath(__file__))

print ('Location : ' + bundle_dir) # Where the base file exists

file = bundle_dir + '\test.txt'
print ('File is at: ' + os.path.abspath(file)) # Absolute path of target file
if os.path.isfile(file):
    with open(file, "r") as f:
        print ('Contents:n' + f.read()) # Print contents of file if it exists
else:
    print ('Created a new file') # Create a file if it doesn't exist

with open(file, "a") as f:
    f.write('New Linen') # Add a new line to see if is there next time

input() # Block to keep terminal alive
Running this un-packaged (.py)

The first time it will create a file beside the script. Every time it is run, the new line will be added and this will be shown in the output. This means When you modify a file, it will stay modified.

Running this when packaged using one directory

The first time it will create a file in the directory (which will be beside the .exe). Every time it is run, the new line will be added and this will be shown in the output. This means When you modify a file, it will stay modified.

Running this when packaged using one file

Every time this is run, it will create a new file in the temporary directory. This occurs because the .exe unpacks to a new directory every time it is run, so instead of finding old files (which can disappear any time because they are in the temp folder) you may as well use an absolute reference to somewhere else.

The one-file Resource Wrapper

As described in the section above, non-python files that are bundled into an executable when using one-file mode need care when being referenced due to how they are un-packaged.

In the interface, when one-file mode is selected and the additional files section is expanded, a note can be found that references a StackOverflow question regarding «Bundling data files with PyInstaller (—onefile)». The first answer provides a nice snippet of code:

import sys, os
def resource_path(relative_path):
    """ Get the absolute path to the resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

When referencing files using relative references, instead of using open('folder/my-file.jpg'), you will want to use open(resource_path('folder/my-file.jpg')). This appends the relative path you provided to the current / extracted location to make an absolute file reference which is safe to use.

The reason you need to use this extra bit of code is because a one-file exe will unpack all of it’s contents to a new folder in the operating systems temporary directory. This means the current working directory initially set in the application will not be where the files have been unpacked to unlike one-directory. This is why using relative references will work in one-directory but not in one-file — you need to adjust for the fact that the root of the project is now somewhere different.

python v3.6.8
PyInstaller v3.6
auto-py-to-exe v2.7.5
os: windows 7

Command:

pyinstaller —noconfirm —onedir —console —name «MyMainapp» —key «qXx53d02m2PrswB1» —debug «all» «<Script Location>»


When I want to convert a python file to exe (using auto-py-to-exe), these errors are shown to me:

An error occurred while packaging
Traceback (most recent call last):
  File "c:usersnimaappdatalocalprogramspythonpython36libsite-packagesauto_py_to_exepackaging.py", line 131, in package
    run_pyinstaller()
  File "c:usersnimaappdatalocalprogramspythonpython36libsite-packagesPyInstaller__main__.py", line 114, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "c:usersnimaappdatalocalprogramspythonpython36libsite-packagesPyInstaller__main__.py", line 65, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "c:usersnimaappdatalocalprogramspythonpython36libsite-packagesPyInstallerbuildingbuild_main.py", line 734, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "c:usersnimaappdatalocalprogramspythonpython36libsite-packagesPyInstallerbuildingbuild_main.py", line 681, in build
    exec(code, spec_namespace)
  File "C:UsersNimaAppDataLocalTemptmp8t9th72tMyMainapp.spec", line 17, in <module>
    noarchive=True)
  File "c:usersnimaappdatalocalprogramspythonpython36libsite-packagesPyInstallerbuildingbuild_main.py", line 244, in __init__
    self.__postinit__()
  File "c:usersnimaappdatalocalprogramspythonpython36libsite-packagesPyInstallerbuildingdatastruct.py", line 160, in __postinit__
    self.assemble()
  File "c:usersnimaappdatalocalprogramspythonpython36libsite-packagesPyInstallerbuildingbuild_main.py", line 500, in assemble
    for name, path, typecode in compile_py_files(new_toc, CONF['workpath']):
  File "c:usersnimaappdatalocalprogramspythonpython36libsite-packagesPyInstallerutilsmisc.py", line 152, in compile_py_files


      with open(obj_fnm, 'rb') as fh:
    FileNotFoundError: [Errno 2] No such file or directory: '-'



Project output will not be moved to output folder

Complete.

if someone knows something, please help me! thank you.

I have python 3.9 I used the command ‘pip install auto-py-to-exe’ and it downloaded but when I tried to using the command ‘auto-py-to-exe’ the program just said » ‘auto-py-to-exe’ is not recognized as an internal or external command, operable program or batch file.». I have the latest version of PIP and I also have PATH. What can I do to fix this?

Dmitri Chubarov's user avatar

asked Jun 5, 2021 at 17:01

Vyom Bhandari's user avatar

2

This works on VSCode:

python -m auto_py_to_exe

Tomerikoo's user avatar

Tomerikoo

17.6k16 gold badges40 silver badges59 bronze badges

answered Nov 13, 2021 at 8:46

Sear D's user avatar

Sear DSear D

611 silver badge6 bronze badges

If I install «auto-py-to-exe» using following command, as described in this link as well as from the comment from Justin Ezequiel (above):

python -m pip install auto-py-to-exe

I am able to run it (in Windows 10) using following command:

python -m auto_py_to_exe

answered Jan 16, 2022 at 16:08

Aananth C N's user avatar

Aananth C NAananth C N

3986 silver badges14 bronze badges

This gave me quite a bit of trouble, as none of the above solutions worked for me. Spent lots of time trying to figure out what I should be adding to PATH with no success.

My issue stemmed from (I think) the fact that I have been using python downloaded from the windows store, which uses a different location to store python in.

With the manual install of python (https://www.python.org) you can specify where python is downloaded and automatically add that location to path.

Steps I took to solve the problem:

  1. Uninstall all versions of python downloaded from the windows store via settings (settings > apps > python > uninstall)

  2. Uninstall all version of python via the control panel (control panel > add or remove programs > python x.x.x > uninstall)

  3. Uninstall auto-py-to-exe (pip uninstall auto-py-to-exe) in case it didnt do that automatically

  4. Install python from python.org. (auto-py-to-exe is not supported in versions greater than 3.10 as of 1/23/2023). So I installed Python 3.10

  5. The settings which were successful for me were:
    Custom installation,
    check install python for all users,
    check add to path,
    input ‘C:Python310’ (with the respective version number) for install location,
    install

  6. Check new python version has been installed python --version

  7. Check pip is installed pip --version

  8. Install auto-py-to-exe pip install auto-py-to-exe

When auto-py-to-exe finishes installing, scroll up through the install info and make sure there are no warnings that state there is a location not found in PATH. If there are, you’ll have to do some other research on adding those locations to PATH appropriately (since I don’t think I was doing that right).

Assuming no PATH warnings,
9. Run auto-py-to-exe

answered Jan 23 at 23:11

Asher Creech's user avatar

First you need to type in the terminal (not Python):

auto-py-to-exe 

If you are currently in python use exit() to exit then try the above code.

Shivam Roy's user avatar

Shivam Roy

1,9043 gold badges8 silver badges22 bronze badges

answered Jun 5, 2021 at 17:11

AaronJ97's user avatar

It Depends on in which environment you have installed

Make sure to replace {User} with your user

In Conda Enviournment go to below location Manually

C:Users{User}anaconda3Scriptsauto-py-to-exe.exe

In Pip, Environment go to the location below

C:Users{User}AppDataLocalProgramsPythonPython37-32Scriptsauto-py-to-exe.exe

or you can add this path to your environment variable as well for accessing these from anywhere

answered Jun 5, 2021 at 19:11

SHYAM SHEEL's user avatar

First check you installed it

pip install auto-py-to-exe

then restart your vscode and check another time.
If still an error, check it in CMD.

answered Nov 13, 2021 at 12:20

Ali FGT's user avatar

1

As suggested above use:

pip show —files auto-py-to-exe to find out in what directory pip has
installed the scripts. Double check the directory is in %PATH%

This will show you where the installer has placed the binary files. I then changed to that directory which circumvents any path issue. I tried to run the files and found :

OSError: [WinError 1920] The file cannot be accessed by the system: 'C:\Users\aaaa\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\python.exe'
PS C:usersaaaaappdatalocalpackagespythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0localcachelocal-packagespython37Scripts>

In my case, although I haven’t worked out how to fix it yet… It would seem to be trying to refer to an incorrect Python executable, the files in that directory are all 0 length. Unfortunately the «python -m» suggestion didn’t work for me, so it’s back to the drawing board. Hope that helps you confirm if it’s the right solution to chase down.

answered Nov 22, 2021 at 16:50

Rob's user avatar

You need to make sure you have typed cd C:Usersyour_user_nameAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39Scripts as a separate command, and then auto-py-to-exe with python 3. Check in file explorer to make sure your path is correct if the cd fails.

answered Aug 16, 2022 at 1:32

user19771984's user avatar

1

Уведомления

  • Начало
  • » Python для новичков
  • » Auto-py-to-exe проблема при запуске

#1 Сен. 6, 2020 19:55:01

Auto-py-to-exe проблема при запуске

C помощью pip установил auto-py-to-exe

 pip install auto-py-to-exe

После чего в командной строке запуска: auto-py-to-exe
В результате чего выходит окно с ошибкой соединения (скрин1)

И ошибка в командной строке UnicodeDecodeError (скрин 2)

Как можно исправить?

Отредактировано bang (Сен. 6, 2020 19:56:42)

Офлайн

  • Пожаловаться

#2 Сен. 6, 2020 20:10:18

Auto-py-to-exe проблема при запуске

Для версии питона 3.8, не поддерживается, установите 3.7
p/s> Об этом указано на гит хабе разработчика.

https://github.com/pyinstaller/pyinstaller/issues/4311

Хотя, сейчас посмотрел вроде как 7 дней назад добавили что то) хз в общем, у меня те же ошибки при установки.

Отредактировано oDoDo (Сен. 6, 2020 20:17:18)

Офлайн

  • Пожаловаться

#3 Сен. 7, 2020 10:30:39

Auto-py-to-exe проблема при запуске

oDoDo
Для версии питона 3.8, не поддерживается, установите 3.7p/s> Об этом указано на гит хабе разработчика. https://github.com/pyinstaller/pyinstaller/issues/4311Хотя, сейчас посмотрел вроде как 7 дней назад добавили что то) хз в общем, у меня те же ошибки при установки.

На 3.6.5 та же самая проблема.

Офлайн

  • Пожаловаться

#4 Сен. 7, 2020 11:22:21

Auto-py-to-exe проблема при запуске

Пайинсталер устанавливали?

Офлайн

  • Пожаловаться

#5 Сен. 7, 2020 19:30:53

Auto-py-to-exe проблема при запуске

Поскольку большинство придерживается мнения что exe делать не нужно, расчитывать на активную помощь не приходится.

Офлайн

  • Пожаловаться

#6 Сен. 7, 2020 19:33:05

Auto-py-to-exe проблема при запуске

oDoDo
Пайинсталер устанавливали?

Да, вроде даже нормально работает.

doza_and
Поскольку большинство придерживается мнения что exe делать не нужно, расчитывать на активную помощь не приходится.

Ну у меня выбора нет, есть необходимость в запуске приложений на других машинах.

Офлайн

  • Пожаловаться

#7 Сен. 8, 2020 00:17:22

Auto-py-to-exe проблема при запуске

bang
Да, вроде даже нормально работает.

Тогда, зачем велосипед изобретать)

Офлайн

  • Пожаловаться

#8 Сен. 8, 2020 04:49:19

Auto-py-to-exe проблема при запуске

bang
Ну у меня выбора нет

Вы глубоко заблуждаетесь.
Это всегда делается в два действия. Установка питона на целевую машину, установка вашего приложения.
Есть гораздо более простые и понятные пути это сделать чем делать неподдерживаемыми средствами контейнер с расширением exe. Наверное это самый плохой из всех вариантов.

А вам чтобы получить разумный ответ и спрашивать надо “как распространять программу на питоне” а не “как делать *.exe *.com *.bat *.sh” ….

Офлайн

  • Пожаловаться

  • Начало
  • » Python для новичков
  • » Auto-py-to-exe проблема при запуске

If you are installing auto-py-to-exe package on Python 3.8 or below, you will get an error stating ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

In this tutorial, we will look into what exactly is ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output and how to fix it.

The auto-py-to-exe library is mainly used to convert the python file(.py) into an executable file (.exe) and run it on windows.

As shown below, we can install the package directly through the pip command in Python 3.8.

$ pip install auto-py-to-exe

The package has an additional dependency on bottle-websocket, which in turn has a dependency on the gevent.

gevent did not release a stable version that offers prebuilt wheels for Python 3.8 during the time of release. Hence, the pip will pick the prebuilt wheels and try to build the gevent==1.4 version from the source dist, resulting in the below error.

ERROR: Command errored out with exit status 1:
    raise distutils.errors.DistutilsPlatformError(err)
    distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Later they had released the new version, which works without any issue. Let us look at the fix for this issue.

Solution

Currently, there are many versions of gevent released, including prebuilt wheels for Python 3.8 on Windows. You can just execute the below command to install the auto-py-to-exe package.

pip install auto-py-to-exe

If this is not working for you, you can try an alternate solution listed below.

pip3 install --upgrade pip setuptools wheel

If you are not able to install setuptools through pip you can also download Microsoft Visual C++ Build Tools and install it manually.

OR

pip install --no-use-wheel --upgrade distribute
pip install --upgrade setuptools

Once you perform this operation, you can install the auto-py-to-exe package. The same solution applies to other libraries, too, which have a dependency on gevent.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Collecting auto-py-to-exe
Using cached auto_py_to_exe-2.6.6-py2.py3-none-any.whl (65 kB)
Collecting pyinstaller>=3.4
Using cached PyInstaller-3.6.tar.gz (3.5 MB)
Installing build dependencies … done
Getting requirements to build wheel … done
Preparing wheel metadata … done
Collecting Eel==0.11.0
Using cached Eel-0.11.0.tar.gz (13 kB)
Collecting pywin32-ctypes>=0.2.0
Using cached pywin32_ctypes-0.2.0-py2.py3-none-any.whl (28 kB)
Collecting pefile>=2017.8.1
Using cached pefile-2019.4.18.tar.gz (62 kB)
Requirement already satisfied: setuptools in c:usersкомпappdatalocalprogramspythonpython 38-32libsite-packages (from pyinstaller>=3.4->auto-py-to-exe) (41.2.0)
Collecting altgraph
Using cached altgraph-0.17-py2.py3-none-any.whl (21 kB)
Collecting bottle
Using cached bottle-0.12.18-py3-none-any.whl (89 kB)
Collecting bottle-websocket
Using cached bottle-websocket-0.2.9.tar.gz (2.0 kB)
Collecting future
Using cached future-0.18.2.tar.gz (829 kB)
Collecting whichcraft
Using cached whichcraft-0.6.1-py2.py3-none-any.whl (5.2 kB)
Collecting gevent-websocket
Using cached gevent_websocket-0.10.1-py3-none-any.whl (22 kB)
Collecting gevent
Using cached gevent-1.4.0.tar.gz (5.2 MB)
ERROR: Command errored out with exit status 1:
command: ‘c:usersкомпappdatalocalprogramspythonpytho n38-32python.exe’ -c ‘import sys, setuptools, tokenize; sys.argv[0] = ‘»‘»‘C:\Users\Комп\AppData\Local\Temp\pip-install-qnlnmqgs\gevent\setup.py'»‘»‘; __file__='»
‘»‘C:\Users\Комп\AppData\Local\Temp\pip-install-qnlnmqgs\gevent\setup.py'»‘»‘;f=getattr(tokenize , ‘»‘»‘open'»‘»‘, open)(__file__);code=f.read().replace(‘»‘»‘rn'»‘ «‘, ‘»‘»‘n'»‘»‘);f.close();exec(compile(code, __file__, ‘»‘»‘e
xec'»‘»‘))’ egg_info —egg-base ‘C:UsersКомпAppDataLocalTemppip-install-qnlnmqgsgeventpip-egg-info’
cwd: C:UsersКомпAppDataLocalTemppip-install-qnlnmqgsgevent
Complete output (112 lines):
Traceback (most recent call last):
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolssandbox.py», line 154, in save_modules
yield saved
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolssandbox.py», line 195, in setup_context
yield
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolssandbox.py», line 250, in run_setup
_execfile(setup_script, ns)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolssandbox.py», line 45, in _execfile
exec(code, globals, locals)
File «C:Users2824~1AppDataLocalTempeasy_insta ll-5v4ut0p8cffi-1.14.0setup.py», line 127, in <module>
HUB_PRIMITIVES = Extension(name=»gevent.__hub_primitives»,
File «C:Users2824~1AppDataLocalTempeasy_insta ll-5v4ut0p8cffi-1.14.0setup.py», line 105, in uses_msvc
include_dirs=include_dirs)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libdistutilscommandconfig.py», line 225, in try_compile
self._compile(body, headers, include_dirs, lang)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libdistutilscommandconfig.py», line 127, in _compile
src = self._gen_temp_sourcefile(body, headers, lang)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libdistutilscommandconfig.py», line 109, in _gen_temp_sourcefile
with open(filename, «w») as file:
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolssandbox.py», line 418, in _open
self._violation(«open», path, mode, *args, **kw)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolssandbox.py», line 407, in _violation
raise SandboxViolation(operation, args, kw)
setuptools.sandbox.SandboxViolation: SandboxViolation: open(‘_configtest.c’, ‘w’) {}

The package setup script has attempted to modify files on your system
that are not within the EasyInstall build area, and has been aborted.

This package cannot be safely installed by EasyInstall, and may not
support alternate installation locations even if you run its setup
script by hand. Please inform the package’s author and the EasyInstall
maintainers to find out if a fix or workaround is available.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File «<string>», line 1, in <module>
File «C:UsersКомпAppDataLocalTemppip-install-qnlnmqgsgeventsetup.py», line 427, in <module>
run_setup(EXT_MODULES, run_make=_BUILDING)
File «C:UsersКомпAppDataLocalTemppip-install-qnlnmqgsgeventsetup.py», line 328, in run_setup
setup(
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptools__init__.py», line 144, in setup
_install_setup_requires(attrs)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptools__init__.py», line 139, in _install_setup_requires
dist.fetch_build_eggs(dist.setup_requires)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolsdist.py», line 716, in fetch_build_eggs
resolved_dists = pkg_resources.working_set.resolve(
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagespkg_resources__init__.py», line 780, in resolve
dist = best[req.key] = env.best_match(
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagespkg_resources__init__.py», line 1065, in best_match
return self.obtain(req, installer)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagespkg_resources__init__.py», line 1077, in obtain
return installer(requirement)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolsdist.py», line 786, in fetch_build_egg
return cmd.easy_install(req)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolscommandeasy_install.py», line 679, in easy_install
return self.install_item(spec, dist.location, tmpdir, deps)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolscommandeasy_install.py», line 705, in install_item
dists = self.install_eggs(spec, download, tmpdir)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolscommandeasy_install.py», line 890, in install_eggs
return self.build_and_install(setup_script, setup_base)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolscommandeasy_install.py», line 1158, in build_and_install
self.run_setup(setup_script, setup_base, args)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolscommandeasy_install.py», line 1144, in run_setup
run_setup(setup_script, args)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolssandbox.py», line 253, in run_setup
raise
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libcontextlib.py», line 131, in __exit__
self.gen.throw(type, value, traceback)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolssandbox.py», line 195, in setup_context
yield
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libcontextlib.py», line 131, in __exit__
self.gen.throw(type, value, traceback)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolssandbox.py», line 166, in save_modules
saved_exc.resume()
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolssandbox.py», line 141, in resume
six.reraise(type, exc, self._tb)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptools_vendorsix.py», line 685, in reraise
raise value.with_traceback(tb)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolssandbox.py», line 154, in save_modules
yield saved
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolssandbox.py», line 195, in setup_context
yield
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolssandbox.py», line 250, in run_setup
_execfile(setup_script, ns)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolssandbox.py», line 45, in _execfile
exec(code, globals, locals)
File «C:Users2824~1AppDataLocalTempeasy_insta ll-5v4ut0p8cffi-1.14.0setup.py», line 127, in <module>
HUB_PRIMITIVES = Extension(name=»gevent.__hub_primitives»,
File «C:Users2824~1AppDataLocalTempeasy_insta ll-5v4ut0p8cffi-1.14.0setup.py», line 105, in uses_msvc
include_dirs=include_dirs)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libdistutilscommandconfig.py», line 225, in try_compile
self._compile(body, headers, include_dirs, lang)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libdistutilscommandconfig.py», line 127, in _compile
src = self._gen_temp_sourcefile(body, headers, lang)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libdistutilscommandconfig.py», line 109, in _gen_temp_sourcefile
with open(filename, «w») as file:
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolssandbox.py», line 418, in _open
self._violation(«open», path, mode, *args, **kw)
File «c:usersкомпappdatalocalprogramspythonpytho n38-32libsite-packagessetuptoolssandbox.py», line 407, in _violation
raise SandboxViolation(operation, args, kw)
setuptools.sandbox.SandboxViolation: SandboxViolation: open(‘_configtest.c’, ‘w’) {}

The package setup script has attempted to modify files on your system
that are not within the EasyInstall build area, and has been aborted.

This package cannot be safely installed by EasyInstall, and may not
support alternate installation locations even if you run its setup
script by hand. Please inform the package’s author and the EasyInstall
maintainers to find out if a fix or workaround is available.

—————————————-
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Cover image for How to convert .py to .exe? Step by step guide.

Eshleron

Eshleron

Posted on Jan 24, 2019

• Updated on Mar 10, 2022

Auto PY to EXE

The only tool that we are gonna be using is Auto PY to EXE!

Auto PY to EXE is an amazing application for making .exe file out of your project whether it is one .py file or any number of them.
The application has a nice gui and looks like this:

alt text

How to start

Step 1. Installation

Installing using PyPI:

To install the application run this line in cmd:

pip install auto-py-to-exe

To open the application run this line in cmd:

auto-py-to-exe

Note: if you have any problems installing this way or you want to install it from GitHub go to the main page or watch this instructional video by the developer of «Auto PY to EXE» himself.

For more additional information use this

«Issues When Using auto-py-to-exe»

Step 2. Converting

There are few main options you need to choose:

  1. Pick your .py file
  2. Pick «One Directory» or «One File» option
  3. Pick additional files

1. Pick your .py file

If you have multiple files choose one that starts the program.

2.1. «One Directory» option

alt text

Pretty simple. When choosing «One Directory» option «Auto PY to EXE» will put all dependencies in one folder. You can choose Output directory in «Advanced» menu. If you have media files like icons and backgrounds you shouldn’t have any problems using them inside your .exe if you place media files/folders in the Output directory.
Something like this:

alt text

2.2. «One File» option

alt text

When choosing «One File» option «Auto PY to EXE» will create one .exe file containing all dependencies but NOT MEDIA FILES. If your program has only default Windows gui with no icons, backgrounds, media files or you are OK with placing media folder near .exe file feel free to skip the following explanation. For those who want to pack media files into .exe file itself read paragraph 3.

3. Pick additional files

There is a menu in «Auto PY to EXE» called «Additional Files» that lets you add files of your choice. There is a catch though. «Auto PY to EXE» uses pyinstaller which unpacks the data into a temporary folder and stores this directory path in the _MEIPASS environment variable. Your project won’t find necessary files because the path changed and it won’t see the new path either. In other words, if option «One File» is chosen picked files in the «Additional Files» menu will not be added to .exe file. To work around this you should use this code provided by developer of Auto PY to EXE here

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
try:
    # PyInstaller creates a temp folder and stores path in _MEIPASS
    base_path = sys._MEIPASS
except Exception:
    base_path = os.path.abspath(".")

return os.path.join(base_path, relative_path)

Enter fullscreen mode

Exit fullscreen mode

To use this code in your project replace the link to the media file you have now
For example:

setWindowIcon(QIcon('mediaiconslogo.png'))

Enter fullscreen mode

Exit fullscreen mode

with

setWindowIcon(QIcon(resource_path('logo.png'))

Enter fullscreen mode

Exit fullscreen mode

Now the link will be referenced correctly and chosen files successfully packed into .exe file.

For comparison:
Possible link before

"C:UsersUserPycharmProjectsmediaiconslogo.png"

Enter fullscreen mode

Exit fullscreen mode

Possible link after

"C:UsersUserAppDataLocalTemp\_MEI34121logo.png"

Enter fullscreen mode

Exit fullscreen mode

Press CONVERT .PY TO .EXE

alt text

Wait

alt text

Step 3. Run your program!

Now everything is done!

Run it. Test it. See what`s up.

Make sure everything works well.

You made One Directory

Every file you need should be in the single directory.

You made One File

This way you should have single .exe file. If you had a need and if done correctly your .exe file will be packed with all media inside it. You will not need any media files/folders present with .exe file for it to display them properly.


P.S.

If you have any feedback or suggestions on what important information should be added feel free to let me know!
This guide is not a description of every possible option done every possible way.
I hope you found that information useful!
Good luck with your projects!

Hey 😍

Want to help the DEV Community feel more like a community?

Head over to the Welcome Thread and greet some new community members!

It only takes a minute of your time, and goes a long way!

Read next


jimajs profile image

How to convert mp4 to mp3 using python

Jima Victor — Jan 19


cliffsilla profile image

Essential Design Patterns in Java

Clifford Silla — Jan 26


whoisryosuke profile image

Learning DirectX 12 in 2023

Ryosuke — Jan 30


snehalkadwe profile image

How to create and use traits in Laravel

Snehal Kadwe — Jan 30

Once unpublished, all posts by eshleron will become hidden and only accessible to themselves.

If eshleron is not suspended, they can still re-publish their posts from their dashboard.

Note:

Once unpublished, this post will become invisible to the public and only accessible to Eshleron.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community 👩‍💻👨‍💻 safe. Here is what you can do to flag eshleron:

Make all posts by eshleron less visible

eshleron consistently posts content that violates DEV Community 👩‍💻👨‍💻’s
code of conduct because it is harassing, offensive or spammy.

Время прочтения
3 мин

Просмотры 179K

С помощью Auto PY to EXE можно с лёгкостью преобразовывать файлы .py в файлы .exe. Благодаря этому ваш проект на Python будет работать как десктопное приложение и вы сможете запускать приложение на других машинах без необходимости установки Python.

В этой статье я расскажу, как преобразовать проект на Python в исполняемый файл. Решение будет работать вне зависимости от количества файлов .py в приложении. Стоит учесть, что Auto PY to EXE работает только с Python 3.5 или выше.

Установка Auto PY to EXE

Установка через pip

При помощи следующей команды можно установить текущую версию Auto PY to EXE.

$ pip install auto-py-to-exe

Установка с GitHub

Также можно выполнить установку напрямую с GitHub. Для установки Auto PY to EXE с GitHub необходимо сначала клонировать репозиторий GitHub.

$ git clone https://github.com/brentvollebregt/auto-py-to-exe.git

Затем нужно перейти в папку auto-py-to-exe.

$ cd auto-py-to-exe

Теперь необходимо запустить файл setup.py.

$ python setup.py install

Можно также проверить версию при помощи следующей команды:

auto-py-to-exe --version

Проверяем версию

Текущая версия Auto PY to EXE 2.9.0 и теперь она установлена на ваш компьютер.

Открываем приложение

Чтобы открыть Auto PY to EXE, нужно выполнить в терминале следующую команду:

$ auto-py-to-exe

Откроется удобное приложение с GUI:

Интерфейс пользователя Auto PY to EXE

Теперь с помощью этого интерфейса можно преобразовать файл .py в .exe.

Процесс преобразования

Шаг 1. Добавляем местоположение файла

Для преобразования .py в .exe сначала необходимо указать путь к файлу Python. Достаточно перейти к местоположению файла, который нужно преобразовать, а затем добавить путь.

Пример:

Добавляем местоположение файла

Я добавил местоположение основного файла Python моего проекта. Здесь я использую для примера один из своих проектов на Python. Это приложение с GUI, визуализирующее различные алгоритмы сортировки. О создании этого проекта можно прочитать здесь: Build a Sorting Algorithm Visualizer in Python

Шаг 2. Выбор «One Directory» или «One File»

В интерфейсе есть опция выбора «One Directory» или «One File». Мой проект на Python содержит несколько других файлов, поэтому я выбрал «One Directory». Эта опция создаст папку со всеми необходимыми файлами, а также с файлом .exe.

One directory или One file

Шаг 3. Выбор «Console Based» или «Window Based»

После этого нужно будет выбрать тип приложения: консольное (Console Based) или оконное (Window Based). Если выбрать «Window Based», то это скроет весь консольный вывод приложения. Если ваш проект генерирует консольный вывод, то нужно выбрать «Console Based». Если у вас приложение с GUI или вам не нужно отображать пользователю консольный вывод, то выберите «Window Based». Я выбрал второй вариант, потому что моё приложение имеет GUI.

Console Based или Window Based

Шаг 4. Преобразование

Далее отобразятся другие опции, такие как добавление значков, дополнительных файлов и т.д. Выберите нужные опции самостоятельно. Ну а наш файл .py уже к преобразованию. Достаточно нажать на кнопку CONVERT .PY TO .EXE .

Нажмите кнопку для преобразования

Для завершения процесса придётся немного подождать.

Папка с результатами

После завершения процесса можно будет выбрать опцию открытия папки с результатами.

По умолчанию папка с результатами будет создана там, откуда вы запускали Auto PY to EXE. Я открывал Auto PY to EXE с рабочего стола, поэтому папка создана на нём. В папке находится множество файлов и папок. Но нам важен файл с расширением .exe. В моём случае это main.exe. При двойном нажатии будет запускаться программа.

Готово! Наш проект на Python теперь преобразован в исполняемый файл. Его можно запускать на других компьютерах без необходимости установки Python.

Ресурсы

  • https://pypi.org/project/auto-py-to-exe/
  • https://github.com/brentvollebregt/auto-py-to-exe

На правах рекламы

Серверы для всех, в том числе, и для разработчиков! VDS с посуточной оплатой на базе новейших процессоров AMD EPYC и хранилища на основе NVMe дисков от Intel для размещения проектов любой сложности, создавайте собственную конфигурацию сервера в пару кликов!

Подписывайтесь на наш чат в Telegram.

A .py to .exe converter using a simple graphical interface and PyInstaller in Python.

Empty interface

PyPI Version
PyPI Supported Versions
License
Downloads Per Month
Supported Platforms
Donate

阅读中文版的README ,点击 这里

Demo

auto-py-to-exe Demo

Getting Started

Prerequisites

  • Python : 3.6-3.11

To have the interface displayed in the images, you will need chrome. If chrome is not installed or —no-chrome is supplied, the default browser will be used.

As of PyInstaller 4.0, Python 2.7 is no longer supported. Read «Python 2.7 Support» below for steps on how to use this tool with Python 2.7.

Installation and Usage

Installing Via PyPI

You can install this project using PyPI:

$ pip install auto-py-to-exe

Then to run it, execute the following in the terminal:

$ auto-py-to-exe

Installing Via GitHub

$ git clone https://github.com/brentvollebregt/auto-py-to-exe.git
$ cd auto-py-to-exe
$ python setup.py install

Then to run it, execute the following in the terminal:

$ auto-py-to-exe

Running Locally Via Github (no install)

You can run this project locally by following these steps:

  1. Clone/download the repo
  2. Open cmd/terminal and cd into the project
  3. Execute python -m pip install -r requirements.txt

Now to run the application, execute python -m auto_py_to_exe. A Chrome window in app mode will open with the project running inside.

Make sure you are in the directory below auto_py_to_exe (you will be after step 3) when calling python -m auto_py_to_exe or you will need to reference the folder auto_py_to_exe absolutely/relatively to where you currently are.

Using the Application

  1. Select your script location (paste in or use a file explorer)
    • Outline will become blue when file exists
  2. Select other options and add things like an icon or other files
  3. Click the big blue button at the bottom to convert
  4. Find your converted files in /output when completed

Easy.

Arguments

Usage: auto-py-to-exe [-nc] [-c [CONFIG]] [-o [PATH]] [filename]

Argument Type Description
filename positional/optional Pre-fill the «Script Location» field in the UI.
-nc, —no-chrome optional Open the UI using the default browser (which may be Chrome). Will not try to find Chrome.
-nu, —no-ui optional Don’t try to open the UI in a browser and simply print out the address that the application can be accessed at.
-c [CONFIG], —config [CONFIG] optional Provide a configuration file (json) to pre-fill the UI. These can be generated in the settings tab.
-o [PATH], —output-dir [PATH] optional Set the default output directory. This can still be changed in the ui.
-bdo [FOLDER_PATH], —build-directory-override [FOLDER_PATH] optional Override the default build directory. Useful if you need to whitelist a folder to stop your antivirus from removing files.
-lang [LANGUAGE_CODE], —language [LANGUAGE_CODE] optional Hint the UI what language it should default to when opening. Language codes can be found in the table under «Translations» below.

If you are running this package locally, you will need to call python -m auto_py_to_exe instead of auto-py-to-exe

JSON Configuration

Instead of inserting the same data into the UI over and over again, you can export the current state by going to the «Configuration» section within the settings tab and exporting the config to a JSON file. This can then be imported into the UI again to re-populate all fields.

This JSON config export action does not save the output directory automatically as moving hosts could mean different directory structures. If you want to have the output directory in the JSON config, add the directory under nonPyinstallerOptions.outputDirectory in the JSON file (will need to create a new key).

Video

If you need something visual to help you get started, I made a video for the original release of this project; some things may be different but the same concepts still apply.

Issues Using the Tool

If you’re having issues with the packaged executable or using this tool in general, I recommend you read my blog post on common issues when using auto-py-to-exe. This post covers things you should know about packaging Python scripts and fixes for things that commonly go wrong.

If you believe you’ve found an issue with this tool, please create an issue (click «Get started») and fill out the template provided by the «Bug report» option. If your issue is only associated with your application, please do not create an issue in this repository — instead, comment on the help post, video or create a new discussion.

When filling out the template, be sure to clearly explain what’s happening, give reproduction steps and a minimal reproducible example and explain what you believe should have happened. Without these, it’s going to take longer to identify the issue.

Translations

Language Code Translator Translated
Arabic (العربية) ar Tayeb-Ali UI
Brazilian Portuguese (Português Brasileiro) pt_br marleyas UI (partial)
Chinese Simplified (简体中文) zh jiangzhe11 UI and README
Chinese Traditional (繁體中文) zh_tw startgo UI
Czech cz Matto58 UI
English en UI and README
French (Français) fr flaviedesp UI
German (Deutsch) de hebens UI (partial)
Greek (Ελληνικά) gr sofronas UI
Indonesian (Bahasa Indonesia) id MarvinZhong UI
Italian (Italiano) it itsEmax64 UI
Japanese (日本語) ja NattyanTV UI
Russian (Русский) ru Oleg UI
Spanish (Español) sp enriiquee UI
Spanish Latam (Español Latam) sp_la Matyrela UI
Serbian sr rina UI
Thai (ภาษาไทย) th teerut26 UI (partial)
Turkish (Türkçe) tr mcagriaksoy UI
Ukrainian (Українська) ua AndrejGorodnij UI

Want to add a translation for another language? Update i18n.js and submit a PR or attach it in an issue.

Python 2.7 Support

As of PyInstaller v4.0 released on Aug 9 2020, Python 2.7 is no longer supported; although you can still use this tool with Python 2.7 by installing an older version of PyInstaller. PyInstaller v3.6 was the last version that supported Python 2.7; to install this, first uninstall any existing versions of PyInstaller and then execute python -m pip install pyinstaller==3.6.

Testing

Tests are located in tests/ and are run using pytest:

$ pip install pytest
$ pip install -e .
$ pytest

Screenshots

Empty interface Filled out
Converting Completed

Понравилась статья? Поделить с друзьями:
  • Authz dll ошибка
  • Authz core error ah01630 client denied by server configuration
  • Authorization error warning failed to login you may have entered an incorrect username or password
  • Authorization error user have no subscription
  • Authorization error use the log out telegram