После того как я собрал свой код с помощью PyInstaller
Я получил такую ошибку
И не знаю что с ней делать
Помогите пожалуйста
Код:
def SayHi():
print('Hi')
input()
SayHi()
PS я просто учусь собирать написанные программы
-
Вопрос заданболее трёх лет назад
-
3222 просмотра
Пригласить эксперта
Я попробовал и у меня всё получилось . Возможно у тебя возникли проблемы из за табуляций и синтаксиса вот отформатированный код:
def SayHi():
print('Hi')
input()
SayHi()
Для преобразование в exe юзал pyinstaller
-
Показать ещё
Загружается…
05 июн. 2023, в 19:14
3000 руб./за проект
05 июн. 2023, в 19:06
3000 руб./за проект
05 июн. 2023, в 19:04
5000 руб./за проект
Минуточку внимания
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
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.
answered Nov 21, 2016 at 12:25
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
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
7,1597 gold badges39 silver badges39 bronze badges
answered Apr 12, 2018 at 16:50
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:
-
adding
--hidden-importflags as needed for any missing modules -
cleaning up the associated folders and spec files:
rmdir /s /q dist
rmdir /s /q build
del /s /q my_service.spec
- Running the commands for installation as Administrator
answered Jan 9, 2019 at 22:32
JacobIRRJacobIRR
8,4148 gold badges38 silver badges63 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
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
Fatih1923Fatih1923
2,6553 gold badges21 silver badges28 bronze badges
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
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
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
18.1k16 gold badges45 silver badges60 bronze badges
answered Mar 16, 2021 at 16:43
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
|
0 / 0 / 0 Регистрация: 12.10.2019 Сообщений: 17 |
|
|
1 |
|
|
11.02.2020, 17:55. Показов 30619. Ответов 11
Сделал программку, попробовал перевести в .exe Failed to execute script main Бывало ли у кого-нибудь это? (main это название кода)
0 |
|
242 / 177 / 73 Регистрация: 17.10.2018 Сообщений: 749 |
|
|
11.02.2020, 18:47 |
2 |
|
Бывало ли у кого-нибудь это? Я думаю у всех бывало)))
Можете сказать как это исправить? Для начала скажите, что вы сделали))) Чем и как компилировали в exe, в формате py работает скрипт? Может использует зависимости, а вы пытаетесь без них запускать?
0 |
|
0 / 0 / 0 Регистрация: 12.10.2019 Сообщений: 17 |
|
|
11.02.2020, 18:50 [ТС] |
3 |
|
В программе используется TKinter. Использовал «auto-py-to-exe». При запуске через код (PyCharm) всё работает хорошо.
Может использует зависимости, а вы пытаетесь без них запускать? Про зависимость не понял.
0 |
|
242 / 177 / 73 Регистрация: 17.10.2018 Сообщений: 749 |
|
|
11.02.2020, 18:55 |
4 |
|
Решение
Про зависимость не понял. Например, вы в модуль main импортируете другой вами же созданный модуль по определенному пути (или из этого же каталога), а скомпилированный файл exe скопировали в другое место и запускаете оттуда. Он не видит импортированный модуль — соответственно — Не удалось выполнить сценарий main
1 |
|
0 / 0 / 0 Регистрация: 12.10.2019 Сообщений: 17 |
|
|
11.02.2020, 19:07 [ТС] |
5 |
|
вы в модуль main импортируете другой вами же созданный модуль по определенному пути (или из этого же каталога) Я импортировал только «txt» файлы Переносились они или нет, при «переделки» в «exe», я не знаю Если их надо как-то переносить, то как?
0 |
|
242 / 177 / 73 Регистрация: 17.10.2018 Сообщений: 749 |
|
|
11.02.2020, 19:14 |
6 |
|
Я импортировал только «txt» файлы Это как? Импортировали или обращались к ним в коде? Если обращались, то по какому пути? И остался ли путь прежним? Добавлено через 1 минуту Попробуйте так еще создать exe
0 |
|
0 / 0 / 0 Регистрация: 12.10.2019 Сообщений: 17 |
|
|
11.02.2020, 19:15 [ТС] |
7 |
|
Я просто открывал их с помощью «open()» и читал их они находились в том же каталоге
Если обращались, то по какому пути?
0 |
|
5407 / 3831 / 1214 Регистрация: 28.10.2013 Сообщений: 9,554 Записей в блоге: 1 |
|
|
11.02.2020, 19:15 |
8 |
|
попробовал перевести в .exe Python в exe не компилируется. То, что делают на выходе всякие упаковщики, это просто архив и в этом архиве должно быть все — вся библиотека Python и все зависимости, которые использует ваш скрипт.
Если их надо как-то переносить Как работать с этим — читайте в документации к упаковщику, которые вы используете.
0 |
|
242 / 177 / 73 Регистрация: 17.10.2018 Сообщений: 749 |
|
|
11.02.2020, 19:21 |
9 |
|
Python в exe не компилируется. То, что делают на выходе всякие упаковщики, это просто архив и в этом архиве должно быть все — вся библиотека Python и все зависимости, которые использует ваш скрипт. Вообще согласен. Получается каталог с большим содержимым (вложение).
Не предназначен Python для этого. Но иногда нужно. Миниатюры
0 |
|
0 / 0 / 0 Регистрация: 12.10.2019 Сообщений: 17 |
|
|
11.02.2020, 19:29 [ТС] |
10 |
|
Всё разобрался! Всем спасибо!
0 |
|
5407 / 3831 / 1214 Регистрация: 28.10.2013 Сообщений: 9,554 Записей в блоге: 1 |
|
|
11.02.2020, 19:32 |
11 |
|
Но иногда нужно. Легко можно обойтись использованием emdedded версии Python + установка в него всех нужных библиотек + свой скрипт + лаунчер скрипта в каталоге Scripts. И никаких шаманств и извратов с запихиванием всего в один файл.
0 |
|
0 / 0 / 0 Регистрация: 15.11.2015 Сообщений: 84 |
|
|
23.12.2020, 15:45 |
12 |
|
Здравствуйте, как вы решили данную проблему подскажите пожалуйста Добавлено через 38 секунд
0 |
Comments
rom1v
added a commit
that referenced
this issue
Nov 30, 2021
rom1v
changed the title
1.21 failed to execute error.
1.21 failed to execute error on Windows 7
Nov 30, 2021
rom1v
added a commit
that referenced
this issue
Nov 30, 2021
According to this bug report on Firefox:
<https://bugzilla.mozilla.org/show_bug.cgi?id=1460995>
> CreateProcess fails with ERROR_NO_SYSTEM_RESOURCES on Windows 7. It
> looks like the reason why is because PROC_THREAD_ATTRIBUTE_HANDLE_LIST
> doesn't like console handles.
To avoid the problem, do not pass console handles to
PROC_THREAD_ATTRIBUTE_HANDLE_LIST.
Refs #2783 <#2783>
Refs f801d8b
Fixes #2838 <#2838>

“ Failed to execute default web broweser/ input/output error.”
Для решения данной ошибки необходимо установить web broweser iceweasel
apt-get install iceweasel
Похожее
Вам также может понравиться
В связи с тем что Kali Linux поддерживает работу с ARM устройствами то можно установить данную систему на Raspberry Pi . Для установки […]
После входа в систему через UltraVNC замечаем картину что наш Kali Linux не русифицирован после нескольких действий изменим ситуацию:
Сегодня мы установим Tight VNC на Raspberry Pi с установленной операционной системой Kali Linux для визуального контроля за системой. Для установки Tight […]



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

