cx freeze python error in main script как исправить

cx_Freeze + virtualenv = баги и зигзаги

Установка cx_Freeze

Не подходит, потому что устанавливает cx_Freeze для Python2.

Попробуем через pip3:

Однако, как бы не так. На Убунте (другие ОС пока не пробовал) это вызывает следующую ошибку (прошу прощения за картинки. На момент написания статьи сделать текстовый копипаст оказалось затруднительно по причинам из серии «это долгая история»):

Порывшись по StackExchange, я понял, что без установки из исходников дело не обойдётся.

Скачал. Распаковал. Запустил:

Снова порылся по StackOverflow. Пришлось залезть в setup.py и заменить там строчку:

Попробовал запустить снова — и установилось! Ура!

На заметку

Собираем скрипт!

где main.py — имя основного (запускаемого) скрипта, а build — папка, куда пойдут исполняемый файл и библиотеки.

Следует учитывать, что в отличие от, скажем, компиляторов C++, cx_Freeze не отлавливает ошибки. Поэтому он может прекрасно всё собрать, но при запуске исполняемого файла посыпятся исключения, причём в довольно неразборчивом формате. Советую потестить код, пока он ещё питонический.

Думаю, что оптимизация кода для сборки в исполняемый файл — тема для отдельного обсуждения, ибо при сборке могут вылезти проблемы, которых при запуске скрипта через интерпретатор Python просто не было. Здесь расскажу об одной (слава богу, одной! больше просто не возникло) такой проблеме.

Мой скрипт обращается к внешним файлам с настройками. Но при запуске из исполняемого файла он почему-то стал воспринимать имя скрипта, как одну из папок на пути к файлу настроек. То есть, если собранный исполняемый файл под названием main находится в /tmp/001, а файл настроек — в /tmp/001/sett, то скрипт думал, что файл настроек на самом деле располагается в /tmp/001/main/sett. Что, естественно, бред. А если же запустить питоновый скрипт — этой проблемы нет.

Дело в том что я в начале своих программ зачастую впихиваю следующую строчку:

Эту переменную я потом использую при задании путей к файлам, которые всегда находятся в одном и том же месте относительно скрипта: файлы настроек, сохранения, токены, коды приложений, и т. д. Таким образом я гарантирую, что программа считает файл из правильного места вне зависимости от того, откуда она была запущена (например, из другой папки или через демона).

Собранные через cx_Freeze скрипты обычно либо неправильно интерпретируют глобальную переменную __file__, либо вообще ее не знают. Последнее как раз произошло, когда я попробовал собрать и запустить исполняемый файл из простенького тестового скрипта:

Проблема оказалась известной. Достаточно было слегка пропатчить мою программу:

В результате, всё завелось с полпинка! Отлично. Простая часть завершена! Переходим к повторению всего этого в виртуальной среде!

Ох уж эти виртуальные среды!

Если вы не пользуетесь virtualenv, полагаю, вас не очень заинтересует дальнейшее чтение этой статьи. Особенность заключается не только в установке cx_Freeze в среду, но и в запуске его таким образом, чтобы он пользовался именно зависимостями из среды, а не системными.

На заметку

Пользоваться средой в шелле (запускается через «source env/bin/activate») нам не придётся. Я пробовал, эффекта это не дало.

Установка

/path/to/my/project/env/bin/python3 setup.py install

Не очень удобно. Пришлось прописывать путь к интерпретатору Питона в нашей среде. Но всё установилось.

Сборка

Однострочный метод, описанный выше, здесь не пройдёт. Нужно использовать другой — через установочный файл.

Файл этот, в краткой форме, которая мне была вполне достаточна, выглядит следующим образом:

Самое главное здесь, это задать MAIN_SCRIPT_NAME, которая соответствует имени главного файла нашей программы.

Помещаем этот скрипт в папку проекта и переходим туда. Запускаем:

Источник

cx_Freeze:Python error in main script

On start up I am getting the following message, twice:

cx_Freeeze: Python error in main script

Traceback (most recent call last):

«C\atomdep\Python35\lib\site-packages\cx_freeze-5.0-py3.5-win32egg\cx_Freeze\initscripts\Console.py», line 21 in

File «C:\buildbot\playsclient-trunk\build\playstv_launcher.py», line 25 in

File «ExtensionLoader_PyQtCore.py», line 22 in

File «ExtensionLoader_PyQtCore.py», line 14, in _bootstrap_

File «C:\atomdep\Python35\lib\imp.py», line 342, in load_dynamic

ImportError: Module use of python26.dll conflicts with this version of Pytohn

Any help would be appreciated.

Report abuse

Replies (13) 

* Please try a lower page number.

* Please enter only numbers.

* Please try a lower page number.

* Please enter only numbers.

I also have same problem.

Report abuse

437 people found this reply helpful

Was this reply helpful?

Sorry this didn’t help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

I have this issue? any solution?

«C\atomdep\Python35\lib\site-packages\cx_freeze-5.0-py3.5-win32egg\cx_Freeze\initscripts\Console.py», line 21 in
File «C:\buildbot\playsclient-trunk\build\playstv_launcher.py», line 25 in
File «ExtensionLoader_PyQtCore.py», line 22 in
File «ExtensionLoader_PyQtCore.py», line 14, in _bootstrap_
File «C:\atomdep\Python35\lib\imp.py», line 342, in load_dynamic
ImportError: DLL load failed %1 is not a valid Win32 application

Report abuse

61 people found this reply helpful

Was this reply helpful?

Sorry this didn’t help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

This question is outside the scope of this site (for consumers) and to be sure you get the best answer it should be asked either on Technet (for IT Pro’s) or MSDN (for developers)

If you give us a link to the new thread we can point some resources to it

Report abuse

2 people found this reply helpful

Was this reply helpful?

Sorry this didn’t help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

Report abuse

35 people found this reply helpful

Was this reply helpful?

Sorry this didn’t help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

Uninstalling «Raptr» got rid of one message but not the other.

Any further help would be appreciated.

Report abuse

10 people found this reply helpful

Читайте также:  тема фауна в игре поле чудес ответ

Was this reply helpful?

Sorry this didn’t help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

From tha last line of your reply you have some connection to MS.

We, us consumer users is where MS get their money from but give us little if any help.

Things like this come up and we have to Google them to attempt to fix them ourselves as MS doesn’t care about customers.

So get someone who can tell us what it means and what we can do about it to come on here and read it, give us the answer so we can use our machines properly.

It only been doing it a while so it looks like some update used code that is not in the core we have so whatever update is at fault needs to update our code DLL.

I have this exact same problem. I, like the post above yours am just an ordinary computer user, not a developer or whatever.

We have a pop up comes up, we don’t know what it means or if it’s to do with our OS or maybe some bug or malware.

I have looked into it a little, Python is a programming language, who used it for what on the machine I have no idea, it’s a pensioner housewife from new so no mods or fancy things on it, email and skype for overseas children.

I went to the other sites you mentioned, far too technical and NOTHING about this problem which a load of use users have judging by the quantity of ‘me too’s’.

Источник

Как исправить ошибку CX_Freeze Python в основном скрипте?

Некоторые пользователи Windows сообщают, что они видят ошибку запуска CX_Freeze Python Error in Main Script при каждом запуске системы. В большинстве случаев проблема возникает после удаления сторонней программы. Оказывается, проблема не в конкретной ОС, поскольку встречается в Windows 7, Windows 8.1 и Windows 10.

В подавляющем большинстве случаев, когда сообщается об этой проблеме, ее причиной является плохо написанное приложение Phyton (скорее всего, Raptr или PlayTV). Если этот сценарий применим, вы сможете исправить проблему, удалив проблемное приложение. Вы можете сделать это либо обычным способом (через Программы и компоненты), либо с помощью мощного стороннего деинсталлятора.

Однако, если вы столкнулись с этой проблемой в игре (запущенной из Steam), вы можете столкнуться с ошибкой, вызванной серией временных файлов в папке AppData. В этом случае очистка содержимого папки AppData и переустановка игры должны решить проблему.

В случае, если вы видите ошибку при попытке запустить проект Phyton, который вы создали локально, вероятно, проблема возникает из-за отсутствующего патча в установке cx_freeze. В этом случае вы можете решить проблему, удалив весь пакет cx_freeze из окна CMD, а затем переустановив последнюю версию.

Если ничего не помогает, ваша последняя надежда на решение проблемы без сброса всех компонентов Windows – запустить несколько утилит (DISM и SFC), оборудованных для устранения большинства случаев повреждения системных файлов.

Удаление Raptr или PlayTV

Как выясняется, одним из наиболее распространенных случаев, приводящих к появлению ошибки запуска «CX_Freeze Python Error in Main Script», является программный продукт, который был написан с несогласованностью с использованием Python. В большинстве случаев затронутые пользователи подтвердили, что проблема была либо вызвано Raptr или PlayTV.

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

Когда дело доходит до этого, вы можете либо пойти традиционным путем (используя экран «Программы и компоненты», чтобы выполнить удаление), либо использовать мощный сторонний деинсталлятор, чтобы завершить работу. Начните с традиционного подхода и переходите ко второму руководству только в том случае, если первое не помогло.

Удаление из программ и функций

В случае, если та же проблема по-прежнему возникает, перейдите ниже и начните с удаления сторонних производителей.

Использование деинсталлятора

Примечание: держитесь подальше от портативной версии Revo, поскольку она не так эффективна, как версия InstallShield.

Примечание. Если вам будет предложено окно UAC (Контроль учетных записей), нажмите Да, чтобы предоставить доступ администратора.

Примечание. Если у вас установлены оба приложения, выполните этот шаг и приведенные ниже с обоими.

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

Переустановка скриптов cx_Freeze (если применимо)

Если вы столкнулись с ошибкой запуска «CX_Freeze Python в главном скрипте» при попытке запустить исполняемый файл вашего проекта Python, созданного с использованием cx_freeze, скорее всего, проблема возникает из-за отсутствующего патча в установке cx_freeze, которую вы Используем.

Если этот сценарий применим, вы сможете решить проблему, удалив весь пакет cx_freeze из окна CMD и переустановив последнюю версию по официальным каналам.

Вот несколько пошаговых руководств, которые проведут вас через весь процесс:

Если та же проблема все еще возникает или этот метод не применим, перейдите к следующему потенциальному решению ниже.

Удаление папки AppData из игры

Если вы видите «Ошибка Python CX_Freeze в основном скрипте» при попытке запустить игру, построенную на Python, возможно, вы имеете дело с поврежденными временными данными некоторого типа, присутствующими в папке AppData.

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

Если этот сценарий применим, следуйте приведенным ниже инструкциям, чтобы исправить ошибку «CX_Freeze Python Error in Main Script» при попытке запуска игры:

Примечание. По умолчанию команда% appdata% автоматически открывает папку Roaming в Appdata.

Если вы все еще видите, что «ошибка CX_Freeze Python в основном скрипте» все еще появляется, или это потенциальное исправление неприменимо, перейдите к следующему потенциальному исправлению ниже.

Запуск сканирования DISM и SFC

В случае, если ни один из методов исправления, описанных выше, не позволил вам решить проблему, ваш компьютер, скорее всего, имеет дело с повреждением системных файлов, которое не может быть решено обычным способом. Скорее всего, ошибка запуска CX_Freeze Python в основном скрипте возникает из-за плохо написанной программы, которая не удаляется должным образом (даже если пользователь следовал обычным каналам).

Читайте также:  Что такое пневматоз кишечника у взрослых мужчин и как лечить

Если этот сценарий применим, вы сможете решить проблему, используя несколько встроенных утилит (DISM и SFC), чтобы идентифицировать и исправить случаи поврежденных системных файлов, которые вызывают эту проблему.

SFC (System File Checker) – полностью локальный инструмент, работающий с использованием локально сохраненного кэша для замены поврежденных экземпляров исправными копиями. С другой стороны, инструменту DISM (развертывание и развертывание с обслуживанием образов) требуется стабильное подключение к Интернету, поскольку он использует подкомпонент Центра обновления Windows для извлечения исправных файлов, необходимых для замены поврежденных эквивалентов.

Поскольку эти два инструмента дополняют друг друга, мы рекомендуем пользователям быстро выполнять оба сканирования, чтобы максимально увеличить ваши шансы на устранение проблемы с повреждением системных файлов, которая вызывает проблему «Ошибка Python CX_Freeze в основном скрипте».

Чтобы выполнить сканирование SFC, следуйте пошаговым инструкциям здесь. После завершения операции перезагрузите компьютер и продолжите сканирование DISM после завершения следующей последовательности запуска.

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

Источник

Comments

StollenTorch commented Feb 1, 2018 •

System Details:
Intel i5
8gb ram
Asus 6gb gtx 1060

Issue Description and steps to reproduce:
I’ve tried uninstalling and reinstalling, running as an administrator, nothing helps

The text was updated successfully, but these errors were encountered:

We are unable to convert the task to an issue at this time. Please try again.

The issue was successfully created but we are unable to update the comment at this time.

StollenTorch commented Feb 2, 2018

It quite literally can’t open the program

DylanC commented Feb 2, 2018

osve001 commented Feb 5, 2018 •

Intel i5-7600
16GB RAM
Win7Pro x64
OpenShot-v2.4.1-x86_64.exe

Yesterday morning It was working fine. In the afternoon, It does not open. Nothing changed on the PC (sw or hw). Everything else on the PC is working fine. Then, I uninstalled Openshot, redownloaded and reinstalled it (several times) and get same error message.
I´ve been reading about it over here, but no solutions so far.
Nothing to do with projects, backups or preferences as it does not open. And, what’s more, after a clean installation, it does not open either (you get that message).

Thanks for your help.

silentdistrict commented Feb 6, 2018

Experience the exact same script. Was working almost perfectly yesterday then today it just started showing up with this message. Uninstalled, backup, nothing seems to be working.

contaminatedesert commented Feb 6, 2018

System Details:
Intel i5
8gb RAM
Acer Aspire E 15

Operating System / Distro:
Windows 10 x86

OpenShot Version:
2.4.1

Exact same thing happened to me. It was working one day and the next received identical error.

osve001 commented Feb 11, 2018

FIXED!
Hi everyone.
I noticed the following: I had two accounts on win7pro: admin (Openshot didn’t open anymore) and a standard user (Openshot WORKED fine).
So, I decided to update my pc.
After a clean installation of windows 10 pro everything works smoothly. I think my old win7pro was the problem.
I hope this helps.
Thank you all for your help

peanutbutterandcrackers commented Feb 11, 2018

Plus, a clean installation does not really seem like the best of fixes.

So, the point is, when run as the Standard user, Openshot works just fine? 😕 I’m a bit confused. But then again, it’s been quite a few years since I’ve deserted windows and all that stuff.

peanutbutterandcrackers commented Feb 11, 2018

DylanC commented Feb 11, 2018 •

Something around the accounts is causing issues but I think the problem is with AppImage or the way the AppImage is produced. Clean installs seem to be the only way reported that works for users.

peanutbutterandcrackers commented Feb 11, 2018

osve001 commented Feb 12, 2018 •

NOT WORKING again!
But FIXED another way.

Intel i5-7600
16GB RAM
Win10Pro x64

peanutbutterandcrackers commented Feb 13, 2018 •

I’m glad it works for you and that you have figured it out. I’ll point others in this direction too. 🙂

peanutbutterandcrackers commented Mar 12, 2018

Please do look forward to v2.4.2. This issue has been put on the list of the ‘critical bugs to be fixed’ for the release. OpenShot should finally work quite well on Windows Machines with v2.4.2. Please, do however continue to support OpenShot. Perhaps test the latest daily build if you have the time and report the issues as you encounter them. Thanks!

lowlight-ua commented Sep 3, 2018 •

I have this problem on 2.4.2, and the workarounds described here don’t work. Can’t start the program.
EDIT worked around the problem by installing a 32-bit version instead of 64-bit.

peanutbutterandcrackers commented Sep 4, 2018

Thank you for the info, @lowlight-ua. That should be helpful to the developers to fix the issue in the future releases

Flowo1f commented Oct 3, 2018

OPENSHOT STILL ISNT WORKING CHECK MY ERROR LINK HERE
#2182 (comment)

Flowo1f commented Oct 3, 2018

I Have been trying to solve this for days. Please Someone help @lowlight-ua @peanutbutterandcrackers @StollenTorch

zenz commented Jan 16, 2019

@Flowo1f same problem, not work.

p-p-j commented Jan 20, 2019

Wimads commented Apr 29, 2019

michaelh99 commented Feb 24, 2020

fwiw, I had this error the very first time I ran the 64 bit version 2.5.0 and the second time it came up just fine. It’s the only version that’s ever been installed on this machine

ferdnyc commented Mar 9, 2020

@michaelh99 Do you know which error, exactly? There have been a few different ones posted here, over time.

Читайте также:  обучение на фронтальный погрузчик в красноярске

michaelh99 commented Mar 9, 2020

@michaelh99 Do you know which error, exactly? There have been a few different ones posted here, over time.

This one, which only happens the first time the app is launched, after a new install. Note that I haven’t tried again after a reboot so there could be some other interaction I haven’t tested for.
I’ve just installed the 2.5.1 and got the same error as I did right after I installed 2.5.0. I had uninstalled 2.5.0 after my last post when I determined that it couldn’t be a replacement for me for Vegas Pro.

ferdnyc commented Mar 14, 2020

@michaelh99
Hmm. It’s trying to write to C:\WINDOWS\system32\config\systemprofile\.openshot_qt — no surprise it can’t, but odd that it would be trying.

Were you running OpenShot as Administrator, by any chance? (Or is it setting itself up to do that automatically? If so, that’s definitely unintended, only the installer should run as Administrator.)

. A replacement for Vegas Pro? No, I wouldn’t think so. But thanks for taking the time to test that out anyway.

michaelh99 commented Mar 14, 2020

Were you running OpenShot as Administrator, by any chance? (Or is it setting itself up to do that automatically? If so, that’s definitely unintended, only the installer should run as Administrator.)

No, installed and running as a normal user.

. A replacement for Vegas Pro? No, I wouldn’t think so. But thanks for taking the time to test that out anyway.

Well, not a full replacement but maybe something that would load and run faster for simple editing. OS is just different enough that I probably won’t use it that way.
I’d be happy to do additional testing for you on this issue if you can think of things you like me to try

ferdnyc commented Mar 14, 2020

@michaelh99 Appreciated! One quick thing you could check: Is there a HOME environment variable set in your user session? (You can check with echo %HOME% in a command shell, or there’s a list buried in one of the user-account configuration dialogs.) Unfortunately Python itself had a bug, not fixed until 3.8, where it would respect that environment variable if it’s set on Windows, instead of deferring to %USERPROFILE% like it’s supposed to.

martinlabarthe commented Jan 30, 2021

Hello guys and girls, solved this issue.

JanithK93 commented Mar 18, 2021

I had the same issue. I tried reinstalling and it didnt work. So I tried slightly different method.

cocozuniga commented Aug 25, 2021 •

El mismo problema que ocurre en algunos equipos con los accesos directos de MsOffice en W10 y W11

Источник

cx_Freeze: Python error in main script #391

Comments

robsonsobral commented Aug 21, 2017

Running on Windows 10 and installed using Chocolatey.

The text was updated successfully, but these errors were encountered:

We are unable to convert the task to an issue at this time. Please try again.

The issue was successfully created but we are unable to update the comment at this time.

kozec commented Aug 21, 2017

Does same thing happens when you install without Chocolatey?

(also, sorry, but I have no idea what’s written after «DLL load failed:» 🙂

robsonsobral commented Aug 21, 2017

After DLL load failed is written «It wasn’t possible to find the specified module».

Thank you for your patience.

tonirug commented Aug 22, 2017 •

Hi,
same problem here with standard install. Same problem also after downgrading from v0.9.2.5 to v0.9.2.4.
The problem happens only when syncthing-gtk is automatically launched at windows startup.
No problem when launching it manually.
OS is Windows 10 with all updates installed.
Best

kozec commented Aug 22, 2017

The problem happens only when syncthing-gtk is automatically launched at windows startup.
No problem when launching it manually.

Ok, now this is important part. That’s same as #385, issue that I still have no idea how can be even possible. @robsonsobral is it same on your side?

robsonsobral commented Aug 22, 2017

acolomb commented Aug 23, 2017

I can confirm this happens on my Windows 7 machine at work, also only during windows startup. Syncthing-Gtk 0.9.2.5 from Chocolatey.

kozec commented Aug 23, 2017 •

Can anyone of you confirm if registry value HKEY_CURRENT_USER\\Software\\SyncthingGTK\\InstallPath points to correct directory on your machine?

acolomb commented Aug 23, 2017

tonirug commented Aug 23, 2017

In W10 appears under Computer\HKEY_CURRENT_USER\Software\SyncthingGTK\InstallPath and the path is correct

koldKat commented Aug 30, 2017

I have the exact same issue. On W7 and W10 machines. Automatic start fails. Manual works just fine.

masgo commented Sep 12, 2017

Here is the English version of the error.

I am using Windows 10 Version 1703.

Maybe it is already obvious, but there is no C:\Python27 folder on my machine.

yaomtc commented Sep 13, 2017 •

I noticed I was missing Python 2.7 (don’t know if I had it installed previously and removed it?) so I installed it, making sure it went in the PATH, but that didn’t make a difference.

kozec commented Sep 16, 2017

Soo. I probably got it. Can anyone of you on Win10 try this build?

robsonsobral commented Sep 17, 2017

seiferflo commented Sep 20, 2017

hugalafutro commented Sep 24, 2017

Thanks for the update it now works as expected when autostarting.

yaomtc commented Oct 4, 2017

It also works again for me. Must be fixed now. Thanks a lot!

kozec commented Oct 4, 2017

Thanks for all confirmation, this is now fixed in latest release.

acolomb commented Dec 13, 2017

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Образовательный портал