Ошибка failed to execute script

I am having a tough time overcoming this error, I have searched everywhere for that error message and nothing seems relevant to my situation:

"failed to execute script new-app" 

new-app is my python GUI program. When I run pyinstaller using this command:

pyinstaller.exe --onedir --hidden-import FileDialog --windowed --noupx new-app.py

It does work smoothly. In addition, when I execute the command line to run the gui program, it works perfectly and the GUI is generated using this command:

.distnew-appnew-app.exe

But when I go to that file hopefully to be able to click the app to get the GUI, it gives me the error said above. Why is that?

I am using python2.7 and the OS is Windows 7 Enterprise.

Any inputs will be appreciated and thanks a lot in advance.

asked Nov 21, 2016 at 9:08

aBiologist's user avatar

aBiologistaBiologist

2,0072 gold badges14 silver badges20 bronze badges

0

Well I guess I have found the solution for my own question, here is how I did it:

Eventhough I was being able to successfully run the program using normal python command as well as successfully run pyinstaller and be able to execute the app «new_app.exe» using the command line mentioned in the question which in both cases display the GUI with no problem at all. However, only when I click the application it won’t allow to display the GUI and no error is generated.

So, What I did is I added an extra parameter —debug in the pyinstaller command and removing the —windowed parameter so that I can see what is actually happening when the app is clicked and I found out there was an error which made a lot of sense when I trace it, it basically complained that «some_image.jpg» no such file or directory.

The reason why it complains and didn’t complain when I ran the script from the first place or even using the command line «./» is because the file image existed in the same path as the script located but when pyinstaller created «dist» directory which has the app product it makes a perfect sense that the image file is not there and so I basically moved it to that dist directory where the clickable app is there!

So The Simple answer is to place all the media files or folders which were used by code in the directory where exe file is there.

Second method is to add «—add-data <path to file/folder>»(this can be used multiple times to add different files) option in pyinstaller command this will automatically put the given file or folder into the exe folder.

GurjasdeepSingh's user avatar

answered Nov 21, 2016 at 12:25

aBiologist's user avatar

aBiologistaBiologist

2,0072 gold badges14 silver badges20 bronze badges

3

In my case i have a main.py that have dependencies with other files. After I build that app with py installer using this command:

pyinstaller --onefile --windowed main.py

I got the main.exe inside dist folder. I double clicked on this file, and I raised the error mentioned above.
To fix this, I just copy the main.exe from dist directory to previous directory, which is the root directory of my main.py and the dependency files, and I got no error after run the main.exe.

answered Jul 1, 2020 at 12:59

monti's user avatar

montimonti

3112 silver badges9 bronze badges

4

Add this function at the beginning of your script :

import sys, os 
    def resource_path(relative_path):
        if hasattr(sys, '_MEIPASS'):
            return os.path.join(sys._MEIPASS, relative_path)
        return os.path.join(os.path.abspath("."), relative_path)

Refer to your data files by calling the function resource_path(), like this:

resource_path('myimage.gif')

Then use this command:

pyinstaller --onefile --windowed --add-data todo.ico;. script.py

For more information visit this documentation page.

Jules Dupont's user avatar

Jules Dupont

7,1697 gold badges39 silver badges39 bronze badges

answered Apr 12, 2018 at 16:50

J-Mourad's user avatar

J-MouradJ-Mourad

1792 silver badges3 bronze badges

In case anyone doesn’t get results from the other answers, I fixed a similar problem by:

  1. adding --hidden-import flags as needed for any missing modules

  2. cleaning up the associated folders and spec files:

rmdir /s /q dist

rmdir /s /q build

del /s /q my_service.spec

  1. Running the commands for installation as Administrator

answered Jan 9, 2019 at 22:32

JacobIRR's user avatar

JacobIRRJacobIRR

8,4548 gold badges38 silver badges65 bronze badges

I was getting this error for a different reason than those listed here, and could not find the solution easily, so I figured I would post here.

Hopefully this is helpful to someone.

My issue was with referencing files in the program. It was not able to find the file listed, because when I was coding it I had the file I wanted to reference in the top level directory and just called

"my_file.png"

when I was calling the files.

pyinstaller did not like this, because even when I was running it from the same folder, it was expecting a full path:

"C:Filesmy_file.png"

Once I changed all of my paths, to the full version of their path, it fixed this issue.

answered May 1, 2020 at 22:01

Shyrtle's user avatar

ShyrtleShyrtle

6475 silver badges20 bronze badges

2

I got the same error and figured out that i wrote my script using Anaconda but pyinstaller tries to pack script on pure python. So, modules not exist in pythons library folder cause this problem.

answered Jan 10, 2019 at 15:45

Fatih1923's user avatar

Fatih1923Fatih1923

2,6553 gold badges21 silver badges28 bronze badges

I had a similar problem, this was due to the fact that I am using anaconda and not installing the dependencies in pip but in anaconda. What helped me was to install the dependencies in pip.

answered Apr 22, 2021 at 5:38

Joey Schuitemaker's user avatar

That error is due to missing of modules in pyinstaller. You can find the missing modules by running script in executable command line, i.e., by removing ‘-w’ from the command. Once you created the command line executable file then in command line it will show the missing modules. By finding those missing modules you can add this to your command :
» —hidden-import = missingmodule «

I solved my problem through this.

answered Mar 22, 2020 at 17:18

Arshad's user avatar

I found a similar issue but none of the answers up above helped. I found a solution to my problem activating the base environment. Trying once more what I was doing without base I got my GUI.exe executed.

As stated by @Shyrtle, given that once solved my initial problem I wanted to add a background image, I had to pass the entire path of the image even if the file.py and the image itself were in the same directory.

Tomerikoo's user avatar

Tomerikoo

18.2k16 gold badges47 silver badges60 bronze badges

answered Mar 16, 2021 at 16:43

Spartan 117's user avatar

Spartan 117Spartan 117

1191 silver badge14 bronze badges

In my case (level noob) I forgot to install library «matplotlib». Program worked in Pycharm, but not when I tried open from terminal. After installed library in Main directory all was ok.

answered Jul 27, 2021 at 15:38

Kajman's user avatar

@LipillaiDave @ebadali Problem solved with run .spec script (pyinstaller main.spec)
My spec script is:

# -*- mode: python -*-

block_cipher = None


a = Analysis(['main.py'],
             pathex=['e:\myapp'],
             binaries=[],
             datas=[('e:\myapp\templates\main.glade', 'templates')],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)

pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)

exe = EXE(pyz, a.scripts, exclude_binaries=True,
          name='Title of app', debug=False, strip=False,
          upx=True, console=False)

coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas,
               strip=False, upx=True, name='myapp')

The information above covers most normal uses of PyInstaller.
However, the variations of Python and third-party libraries are
endless and unpredictable.
It may happen that when you attempt to bundle your app either
PyInstaller itself, or your bundled app, terminates with a Python traceback.
Then please consider the following actions in sequence, before
asking for technical help.

Recipes and Examples for Specific Problems¶

The PyInstaller FAQ page has work-arounds for some common problems.
Code examples for some advanced uses and some common
problems are available on our PyInstaller Recipes page.
Some of the recipes there include:

  • A more sophisticated way of collecting data files
    than the one shown above (Adding Files to the Bundle).

  • Bundling a typical Django app.

  • A use of a run-time hook to set the PyQt5 API level.

  • A workaround for a multiprocessing constraint under Windows.

and others.
Many of these Recipes were contributed by users.
Please feel free to contribute more recipes!

Finding out What Went Wrong¶

Build-time Messages¶

When the Analysis step runs, it produces error and warning messages.
These display after the command line if the --log-level option allows it.
Analysis also puts messages in a warnings file
named build/name/warn-name.txt in the
work-path= directory.

Analysis creates a message when it detects an import
and the module it names cannot be found.
A message may also be produced when a class or function is declared in
a package (an __init__.py module), and the import specifies
package.name. In this case, the analysis can’t tell if name is supposed to
refer to a submodule or package.

The “module not found” messages are not classed as errors because
typically there are many of them.
For example, many standard modules
conditionally import modules for different platforms that may or may
not be present.

All “module not found” messages are written to the
build/name/warn-name.txt file.
They are not displayed to standard output because there are many of them.
Examine the warning file; often there will be dozens of modules not found,
but their absence has no effect.

When you run the bundled app and it terminates with an ImportError,
that is the time to examine the warning file.
Then see Helping PyInstaller Find Modules below for how to proceed.

Build-Time Dependency Graph¶

On each run PyInstaller writes a cross-referencing file about dependencies
into the build folder:
build/name/xref-name.html in the
work-path= directory is an HTML file that lists the full
contents of the import graph, showing which modules are imported
by which ones.
You can open it in any web browser.
Find a module name, then keep clicking the “imported by” links
until you find the top-level import that causes that module to be included.

If you specify --log-level=DEBUG to the pyinstaller command,
PyInstaller additionally generates a GraphViz input file representing the
dependency graph.
The file is build/name/graph-name.dot in the
work-path= directory.
You can process it with any GraphViz command, e.g. dot,
to produce
a graphical display of the import dependencies.

These files are very large because even the simplest “hello world”
Python program ends up including a large number of standard modules.
For this reason the graph file is not very useful in this release.

Build-Time Python Errors¶

PyInstaller sometimes terminates by raising a Python exception.
In most cases the reason is clear from the exception message,
for example “Your system is not supported”, or “Pyinstaller
requires at least Python 3.7”.
Others clearly indicate a bug that should be reported.

One of these errors can be puzzling, however:
IOError("Python library not found!")
PyInstaller needs to bundle the Python library, which is the
main part of the Python interpreter, linked as a dynamic load library.
The name and location of this file varies depending on the platform in use.
Some Python installations do not include a dynamic Python library
by default (a static-linked one may be present but cannot be used).
You may need to install a development package of some kind.
Or, the library may exist but is not in a folder where PyInstaller
is searching.

The places where PyInstaller looks for the python library are
different in different operating systems, but /lib and /usr/lib
are checked in most systems.
If you cannot put the python library there,
try setting the correct path in the environment variable
LD_LIBRARY_PATH in GNU/Linux or
DYLD_LIBRARY_PATH in macOS.

Getting Debug Messages¶

The --debug=all option (and its choices) provides a significant amount of diagnostic information.
This can be useful during development of a complex package,
or when your app doesn’t seem to be starting,
or just to learn how the runtime works.

Normally the debug progress messages go to standard output.
If the --windowed option is used when bundling a Windows app,
they are sent to any attached debugger. If you are not using a debugger
(or don’t have one), the DebugView the free (beer) tool can be used to
display such messages. It has to be started before running the bundled
application.

For a --windowed macOS app they are not displayed.

Consider bundling without --debug for your production version.
Debugging messages require system calls and have an impact on performance.

Getting Python’s Verbose Imports¶

You can build the app with the --debug=imports option
(see Getting Debug Messages above),
which will pass the -v (verbose imports) flag
to the embedded Python interpreter.
This can be extremely useful.
It can be informative even with apps that are apparently working,
to make sure that they are getting all imports from the bundle,
and not leaking out to the local installed Python.

Python verbose and warning messages always go to standard output
and are not visible when the --windowed option is used.
Remember to not use this for your production version.

Figuring Out Why Your GUI Application Won’t Start¶

If you are using the --windowed option,
your bundled application may fail to start with an error message like
Failed to execute script my_gui.
In this case, you will want to get more verbose output to find out
what is going on.

  • For macOS, you can run your application on the command line,
    i.e. ./dist/my_gui
    in Terminal instead of clicking on my_gui.app.

  • For Windows, you will need to re-bundle your application without the
    --windowed option.
    Then you can run the resulting executable from the command line,
    i.e. my_gui.exe.

  • For Unix and GNU/Linux there in no --windowed option.
    Anyway, if a your GUI application fails,
    you can run your application on the command line,
    i.e. ./dist/my_gui.

This should give you the relevant error that is preventing your
application from initializing, and you can then move on to other
debugging steps.

Operation not permitted error¶

If you use the –onefile and it fails to run you program with error like:

./hello: error while loading shared libraries: libz.so.1:
failed to map segment from shared object: Operation not permitted

This can be caused by wrong permissions for the /tmp directory
(e.g. the filesystem is mounted with noexec flags).

A simple way to solve this issue is to set,
in the environment variable TMPDIR,
a path to a directory in a filesystem mounted without noexec flags, e.g.:

Helping PyInstaller Find Modules¶

Extending the Path¶

If Analysis recognizes that a module is needed, but cannot find that module,
it is often because the script is manipulating sys.path.
The easiest thing to do in this case is to use the --paths option
to list all the other places that the script might be searching for imports:

pyi-makespec --paths=/path/to/thisdir 
             --paths=/path/to/otherdir myscript.py

These paths will be noted in the spec file in the pathex argument.
They will be added to the current sys.path during analysis.

Extending a Package’s __path__

Python allows a script to extend the search path used for imports
through the __path__ mechanism.
Normally, the __path__ of an imported module has only one entry,
the directory in which the __init__.py was found.
But __init__.py is free to extend its __path__ to include other directories.
For example, the win32com.shell.shell module actually resolves to
win32com/win32comext/shell/shell.pyd.
This is because win32com/__init__.py appends ../win32comext to its __path__.

Because the __init__.py of an imported module
is not actually executed during analysis,
changes it makes to __path__ are not seen by PyInstaller.
We fix the problem with the same hook mechanism we use for hidden imports,
with some additional logic; see Understanding PyInstaller Hooks below.

Note that manipulations of __path__ hooked in this way apply only
to the Analysis.
At runtime all imports are intercepted and satisfied from within the
bundle. win32com.shell is resolved the same
way as win32com.anythingelse, and win32com.__path__
knows nothing of ../win32comext.

Once in a while, that’s not enough.

Changing Runtime Behavior¶

More bizarre situations can be accommodated with runtime hooks.
These are small scripts that manipulate the environment before your main script runs,
effectively providing additional top-level code to your script.

There are two ways of providing runtime hooks.
You can name them with the option --runtime-hook=path-to-script.

Second, some runtime hooks are provided.
At the end of an analysis,
the names in the module list produced by the Analysis phase are looked up in
loader/rthooks.dat in the PyInstaller install folder.
This text file is the string representation of a
Python dictionary. The key is the module name, and the value is a list
of hook-script pathnames.
If there is a match, those scripts are included in the bundled app
and will be called before your main script starts.

Hooks you name with the option are executed
in the order given, and before any installed runtime hooks.
If you specify --runtime-hook=file1.py --runtime-hook=file2.py then the execution order at runtime will be:

  1. Code of file1.py.

  2. Code of file2.py.

  3. Any hook specified for an included module that is found
    in rthooks/rthooks.dat.

  4. Your main script.

Hooks called in this way, while they need to be careful of what they import,
are free to do almost anything.
One reason to write a run-time hook is to
override some functions or variables from some modules.
A good example of this is the Django runtime
hook (see loader/rthooks/pyi_rth_django.py in the
PyInstaller folder).
Django imports some modules dynamically and it is looking
for some .py files.
However .py files are not available in the one-file bundle.
We need to override the function
django.core.management.find_commands
in a way that will just return a list of values.
The runtime hook does this as follows:

import django.core.management
def _find_commands(_):
    return """cleanup shell runfcgi runserver""".split()
django.core.management.find_commands = _find_commands

Getting the Latest Version¶

If you have some reason to think you have found a bug in PyInstaller
you can try downloading the latest development version.
This version might have fixes or features that are not yet at PyPI.
You can download the latest stable version and the latest development
version from the PyInstaller Downloads page.

You can also install the latest version of PyInstaller directly
using pip:

pip install https://github.com/pyinstaller/pyinstaller/archive/develop.zip

Asking for Help¶

When none of the above suggestions help,
do ask for assistance on the PyInstaller Email List.

Then, if you think it likely that you see a bug in PyInstaller,
refer to the How to Report Bugs page.

When we use pyinstaller to pack python script to exe application, we may get Failed to execute script Error. In this tutorial, we will introduce you how to fix.

Failed to execute script error looks like:

pyinstaller failed to execute script

How to fix this error?

The simplest way is we pack python script to exe application with console based. Here is an example:

pyinstaller --noconfirm --onefile --console  "E:/workspace-nlp/PythonScript/main.py"

Then, we will run main.exe with command prompt in windows 10.

run python exe from cmd

As to us, we can find the reason why main.exe reports Failed to execute script error.

pyinstaller ModuleNotFoundError

Install python socks library, you can read this tutorial:

Fix ModuleNotFoundError: No module named ‘socks’ Error – Python Tutorial

Finally, we will pack our python script again, we find this error is fixed.

0 / 0 / 0

Регистрация: 12.10.2019

Сообщений: 17

1

11.02.2020, 17:55. Показов 30710. Ответов 11


Студворк — интернет-сервис помощи студентам

Сделал программку, попробовал перевести в .exe
Выдаёт ошибку при открытии значка.

Failed to execute script main

Бывало ли у кого-нибудь это?
Можете сказать как это исправить?

(main это название кода)



0



242 / 177 / 73

Регистрация: 17.10.2018

Сообщений: 749

11.02.2020, 18:47

2

Цитата
Сообщение от Methodius
Посмотреть сообщение

Бывало ли у кого-нибудь это?

Я думаю у всех бывало)))

Цитата
Сообщение от Methodius
Посмотреть сообщение

Можете сказать как это исправить?

Для начала скажите, что вы сделали))) Чем и как компилировали в exe, в формате py работает скрипт? Может использует зависимости, а вы пытаетесь без них запускать?



0



0 / 0 / 0

Регистрация: 12.10.2019

Сообщений: 17

11.02.2020, 18:50

 [ТС]

3

В программе используется TKinter.

Использовал «auto-py-to-exe».

При запуске через код (PyCharm) всё работает хорошо.

Цитата
Сообщение от Lekks
Посмотреть сообщение

Может использует зависимости, а вы пытаетесь без них запускать?

Про зависимость не понял.



0



242 / 177 / 73

Регистрация: 17.10.2018

Сообщений: 749

11.02.2020, 18:55

4

Лучший ответ Сообщение было отмечено Methodius как решение

Решение

Цитата
Сообщение от Methodius
Посмотреть сообщение

Про зависимость не понял.

Например, вы в модуль main импортируете другой вами же созданный модуль по определенному пути (или из этого же каталога), а скомпилированный файл exe скопировали в другое место и запускаете оттуда. Он не видит импортированный модуль — соответственно — Не удалось выполнить сценарий main



1



0 / 0 / 0

Регистрация: 12.10.2019

Сообщений: 17

11.02.2020, 19:07

 [ТС]

5

Цитата
Сообщение от Lekks
Посмотреть сообщение

вы в модуль main импортируете другой вами же созданный модуль по определенному пути (или из этого же каталога)

Я импортировал только «txt» файлы

Переносились они или нет, при «переделки» в «exe», я не знаю

Если их надо как-то переносить, то как?



0



242 / 177 / 73

Регистрация: 17.10.2018

Сообщений: 749

11.02.2020, 19:14

6

Цитата
Сообщение от Methodius
Посмотреть сообщение

Я импортировал только «txt» файлы

Это как? Импортировали или обращались к ним в коде?

Если обращались, то по какому пути? И остался ли путь прежним?

Добавлено через 1 минуту
pyinstaller —onefile example.py

Попробуйте так еще создать exe



0



0 / 0 / 0

Регистрация: 12.10.2019

Сообщений: 17

11.02.2020, 19:15

 [ТС]

7

Я просто открывал их с помощью «open()» и читал их

они находились в том же каталоге

Цитата
Сообщение от Lekks
Посмотреть сообщение

Если обращались, то по какому пути?



0



Эксперт Python

5407 / 3831 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

11.02.2020, 19:15

8

Цитата
Сообщение от Methodius
Посмотреть сообщение

попробовал перевести в .exe

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

Цитата
Сообщение от Methodius
Посмотреть сообщение

Если их надо как-то переносить

Как работать с этим — читайте в документации к упаковщику, которые вы используете.
И да, хватит засорять форум темами про упаковку в exe. Не предназначен Python для этого.



0



242 / 177 / 73

Регистрация: 17.10.2018

Сообщений: 749

11.02.2020, 19:21

9

Цитата
Сообщение от Garry Galler
Посмотреть сообщение

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

Вообще согласен. Получается каталог с большим содержимым (вложение).

Цитата
Сообщение от Garry Galler
Посмотреть сообщение

Не предназначен Python для этого.

Но иногда нужно.

Миниатюры

Failed to execute script main
 



0



0 / 0 / 0

Регистрация: 12.10.2019

Сообщений: 17

11.02.2020, 19:29

 [ТС]

10

Всё разобрался!

Всем спасибо!



0



Эксперт Python

5407 / 3831 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

11.02.2020, 19:32

11

Цитата
Сообщение от Lekks
Посмотреть сообщение

Но иногда нужно.

Легко можно обойтись использованием emdedded версии Python + установка в него всех нужных библиотек + свой скрипт + лаунчер скрипта в каталоге Scripts. И никаких шаманств и извратов с запихиванием всего в один файл.



0



0 / 0 / 0

Регистрация: 15.11.2015

Сообщений: 85

23.12.2020, 15:45

12

Здравствуйте, как вы решили данную проблему подскажите пожалуйста

Добавлено через 38 секунд
Methodius, Здравствуйте, как вы решили данную проблему подскажите пожалуйста



0



  • Ошибка failed to download metadata for repo appstream centos 8
  • Ошибка failed to create xaudio2 engine try installing the latest directx
  • Ошибка failed to allocate video memory doom eternal
  • Ошибка failed to create signature error ошибка исполнения функции 0x8007065b проверка
  • Ошибка failed security check for loco nonce