Failed to execute script main ошибка

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,4248 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

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

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 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

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.1k16 gold badges45 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

@embryo10

Windows 7×64 SP1
Python 2.7.13
PyInstaller-3.3.dev0+5b6288b
PySide 1.2.4

import sys
from PySide import QtGui
from PySide import QtCore

app = QtGui.QApplication(sys.argv)
label = QtGui.QLabel("Hello World")
label.show()
app.exec_()
sys.exit()

with

pyinstaller --name Check main.py

compiles (with no errors) a Check.exe that when it runs gives me the

Traceback (most recent call last):
  File "main.py", line 2, in <module>
  File "d:appsdevpythonpython27Libsite-packagesPyInstallerloaderpyimod03_importers.py", line 396, in load_module
    exec(bytecode, module.__dict__)
  File "site-packagesPySide__init__.py", line 41, in <module>
  File "site-packagesPySide__init__.py", line 11, in _setupQtDirectories
  File "site-packagesPySide_utils.py", line 95, in get_pyside_dir
  File "site-packagesPySide_utils.py", line 88, in _get_win32_case_sensitive_name
  File "site-packagesPySide_utils.py", line 63, in _get_win32_short_name
WindowsError: [Error 2] The system cannot find the file specified.
Failed to execute script main

error.
The Pyside installation directory is

D:AppsDEVPYTHONPython27Libsite-packagesPySide

Any ideas?
Should I write this path somewhere?

@ghost

I would recommend that you use pyqt because it’s better supported.

@embryo10

«Better» support than what?
Not compiling a «hello world» script?
I was hoping for an actual solution to this…

@ghost

We run tests on PyQt. We don’t run tests on PySide. Therefore, it’s not surprising that PySide doesn’t work, aside from what the README says. You have two options:

  • You can implement support for PySide
  • You can use PyQt5, which is the most likely to work

I was hoping for an actual solution to this…

In case you decide to attempt the first option, what you need to do is implement a runtime hook that monkeypatches that specific function so that it doesn’t fail and possibly an additional hook that includes the required directories. Runtime hooks are in PyInstaller/loader/rthooks and Hooks are in PyInstaller/hooks.

You may be surprised by the tone of my response, but I will inform you that PyInstaller is more advanced than any other freezer and even at that, it still requires a LOT of maintenance to support 90% of use cases. Python is simply not a language designed to make freezing easy.

@embryo10

I don’t really have any option.
I can’t use PyQt for licensing reasons and I don’t know how to implement support for PySide, since if I did I wasn’t gonna ask for help on this.

You may be surprised by the tone of my response, but I will inform you that PyInstaller is more advanced than any other freezer and even at that, it still requires a LOT of maintenance to support 90% of use cases.

The first alternative that I checked (cx_freeze) could compile that simple script.
My problem is that I’m already using PyInstaller 2.1 for some time now, and I have learn some of its quirks (copying some directories manually when needed for complicated projects) after a lot of experimentation, and its working.
I have to update because of a newer kivy version, but I don’t want to start from scratch.

Anyway, are there any resources or suggestions about adding this path to the PyInstaller?

@ghost

What’s the file it’s looking for? [print it]

@embryo10

WindowsError: [Error 2] The system cannot find the file specified.
Failed to execute script main

It must be referring to the main.py (the name of the simple script)

@ghost

Those two messages are completely unrelated. The first is the error message which doesn’t show the file. You need to discover it by modifying utils.py to print the file.

The second message comes from PyInstaller: it simply says that PyInstaller could not execute the entry point.

@embryo10

Yes, they are unrelated.
It was looking for the _utils.pyc file inside the PySide directory.
I copied these where it wants them and now we are facing the real problem.

Traceback (most recent call last):
  File "site-packagesPyInstallerloaderrthookspyi_rth_qt4plugins.py", line 43
, in <module>
ImportError: No module named PyQt4.QtCore
Failed to execute script pyi_rth_qt4plugins

The reason for this is the PySide import that fails

try:
    from PySide.QtCore import QCoreApplication
except ImportError:
    from PyQt4.QtCore import QCoreApplication

and then tries to import PyQt.

@ghost

try:

from PyInstaller.utils.hooks import collect_submodules
hiddenimports += collect_submodules('PySide')

On another note, your problems may come from the fact that you appear to be using PySide, which has been replaced by PySide2.

@embryo10

Where should I put this?
Trying the .spec file, gives me
NameError: name 'hiddenimports' is not defined

Pyside2 is not replacing PySide just yet
Its still work in progress.

@embryo10

Tried this

from PyInstaller.utils.hooks import collect_submodules
hiddenimports = []
hiddenimports += collect_submodules('PySide')

and

a = Analysis(['main.py'],
             pathex=['C:\Users\X\Desktop\DEV\PROJECTS\4Build\_Check'],
             binaries=[],
             datas=[],
             hiddenimports=hiddenimports,
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)

that did run but gave me the original No module named PyQt4.QtCore error.

@embryo10

Back to search.
@xoviat
I couldn’t find a way to add the hiddenimports code you gave me, but, trying to find why it doesn’t import PySide I ditch the try/except and followed the errors.
I got this

  File "site-packagesPyInstallerloaderrthookspyi_rth_qt4plugins.py", line 41, in <module>
  File "d:appsdevpythonpython27libsite-packagesPyInstallerloaderpyimod03_importers.py", line 688, in load_module
    module = imp.load_module(fullname, fp, filename, ext_tuple)
ImportError: DLL load failed: The specified procedure could not be found.
Failed to execute script pyi_rth_qt4plugins

When I printed the fullname, fp, filename, ext_tuple and I’ve got

PySide.QtCore <open file 'D:\Apps\DEV\PROJECTS\4Build\_Check\dist\Check\PySide.QtCore.pyd', mode 'rb' at 0x0232C968> D:AppsDEVPROJECTS4Build_CheckdistCheckPySide.QtCore.pyd ('.pyd', 'rb', 3)

which I think it means that it cannot find the PySide.QtCore.pyd file.
The file is there but keeps giving me the same error.
Any ideas?

@embryo10

In the pyimod03_importers.py file (where the error happens) there is this comment:
# Python 2 implementation - TODO drop or improve it. 'imp' module is no longer built-in. and I wonder if this is why The specified procedure could not be found.

@ghost

Don’t waste your time on pyimod03_importers. That error means that PyInstaller is putting in a DLL that works with a different Python version. Try to find where the DLL is that Python uses by default and then compare it to the DLL that PyInstaller has included.

@embryo10

So, any other ideas?
What about the

from PyInstaller.utils.hooks import collect_submodules
hiddenimports += collect_submodules('PySide')

How should I use it?

@ghost

Note: this is psuedocode for what you should look at:

> import PySide.QtCore
> print(PySide.QtCore.__file__)
> assert open(PySide.QtCore.__file__).read() == open('D:AppsDEVPROJECTS4Build_CheckdistCheckPySide.QtCore.py').read()

@ghost

How should I use it?

Don’t. That was for a different error that you don’t have but I thought you did earlier.

@embryo10

IOError: [Errno 22] invalid mode ('r') or filename: 'D:\Apps\DEV\PROJECTSx04Build\_Check\dist\Check\PySide.QtCore.py'

@ghost

It’s psuedocode. What you need to do is run the first two lines, find where that file is located, and then compare it to the file in the PyI project.

@ghost

> import PySide.QtCore
> print(PySide.QtCore.__file__)

@ghost

run that in the REPL and it will tell you

@embryo10

D:/Apps/DEV/PYTHON/Python27/lib/site-packages/PySide/QtCore.pyd

@ghost

are the contents of that file the same as the contents of the file in the PyI project?

@embryo10

No there aren’t.
I copied the QtCore.pyd and rename it PySide.QtCore.pyd but I still get the same error…

@ghost

let me look at the c++ and then I’ll come back to this later

@embryo10

@ghost

Using python 2.7.13 and PyInstaller 3.3.dev0+c7a24e5, I was unable to replicate this problem. Below is the directory listing that I have. What is different?


    Directory: C:UsersUserDownloadsdisttest


Mode                LastWriteTime         Length Name                                                                  
----                -------------         ------ ----                                                                  
d-----        5/18/2017  10:04 AM                qt4_plugins                                                           
-a----        5/18/2017  10:04 AM          92672 bz2.pyd                                                               
-a----        5/18/2017  10:04 AM           1052 Microsoft.VC90.CRT.manifest                                           
-a----        5/18/2017  10:04 AM         245760 msvcm90.dll                                                           
-a----        5/18/2017  10:04 AM         854160 msvcp90.dll                                                           
-a----        5/18/2017  10:04 AM         642192 msvcr90.dll                                                           
-a----        5/18/2017  10:07 AM              0 out.txt                                                               
-a----        5/18/2017  10:04 AM         141824 pyside-python2.7.dll                                                  
-a----        5/18/2017  10:04 AM        2293760 PySide.QtCore.pyd                                                     
-a----        5/18/2017  10:04 AM        8679424 PySide.QtGui.pyd                                                      
-a----        5/18/2017  10:04 AM         808448 PySide.QtNetwork.pyd                                                  
-a----        5/18/2017  10:04 AM        3407872 python27.dll                                                          
-a----        5/18/2017  10:04 AM        2992640 Qt3Support4.dll                                                       
-a----        5/18/2017  10:04 AM        3251712 QtCore4.dll                                                           
-a----        5/18/2017  10:04 AM       10889728 QtGui4.dll                                                            
-a----        5/18/2017  10:04 AM        1364480 QtNetwork4.dll                                                        
-a----        5/18/2017  10:04 AM         921088 QtOpenGL4.dll                                                         
-a----        5/18/2017  10:04 AM         255488 QtSql4.dll                                                            
-a----        5/18/2017  10:04 AM         353280 QtSvg4.dll                                                            
-a----        5/18/2017  10:04 AM         468992 QtXml4.dll                                                            
-a----        5/18/2017  10:04 AM          11776 select.pyd                                                            
-a----        5/18/2017  10:04 AM         152576 shiboken-python2.7.dll                                                
-a----        5/18/2017  10:04 AM         805692 test.exe                                                              
-a----        5/18/2017  10:04 AM           1012 test.exe.manifest                                                     
-a----        5/18/2017  10:04 AM         692224 unicodedata.pyd                                                       
-a----        5/18/2017  10:04 AM         120832 _ctypes.pyd                                                           
-a----        5/18/2017  10:04 AM        1482240 _hashlib.pyd                                                          


    Directory: C:UsersUserDownloadsdisttestqt4_plugins


Mode                LastWriteTime         Length Name                                                                  
----                -------------         ------ ----                                                                  
d-----        5/18/2017  10:04 AM                accessible                                                            
d-----        5/18/2017  10:04 AM                codecs                                                                
d-----        5/18/2017  10:04 AM                graphicssystems                                                       
d-----        5/18/2017  10:04 AM                iconengines                                                           
d-----        5/18/2017  10:04 AM                imageformats                                                          


    Directory: C:UsersUserDownloadsdisttestqt4_pluginsaccessible


Mode                LastWriteTime         Length Name                                                                  
----                -------------         ------ ----                                                                  
-a----        5/18/2017  10:04 AM          45056 qtaccessiblecompatwidgets4.dll                                        
-a----        5/18/2017  10:04 AM         245248 qtaccessiblewidgets4.dll                                              


    Directory: C:UsersUserDownloadsdisttestqt4_pluginscodecs


Mode                LastWriteTime         Length Name                                                                  
----                -------------         ------ ----                                                                  
-a----        5/18/2017  10:04 AM         145920 qcncodecs4.dll                                                        
-a----        5/18/2017  10:04 AM         176128 qjpcodecs4.dll                                                        
-a----        5/18/2017  10:04 AM          81408 qkrcodecs4.dll                                                        
-a----        5/18/2017  10:04 AM         159744 qtwcodecs4.dll                                                        


    Directory: C:UsersUserDownloadsdisttestqt4_pluginsgraphicssystems


Mode                LastWriteTime         Length Name                                                                  
----                -------------         ------ ----                                                                  
-a----        5/18/2017  10:04 AM          16896 qglgraphicssystem4.dll                                                
-a----        5/18/2017  10:04 AM          26624 qtracegraphicssystem4.dll                                             


    Directory: C:UsersUserDownloadsdisttestqt4_pluginsiconengines


Mode                LastWriteTime         Length Name                                                                  
----                -------------         ------ ----                                                                  
-a----        5/18/2017  10:04 AM          43520 qsvgicon4.dll                                                         


    Directory: C:UsersUserDownloadsdisttestqt4_pluginsimageformats


Mode                LastWriteTime         Length Name                                                                  
----                -------------         ------ ----                                                                  
-a----        5/18/2017  10:04 AM          33280 qgif4.dll                                                             
-a----        5/18/2017  10:04 AM          34816 qico4.dll                                                             
-a----        5/18/2017  10:04 AM         239616 qjpeg4.dll                                                            
-a----        5/18/2017  10:04 AM         279040 qmng4.dll                                                             
-a----        5/18/2017  10:04 AM          26112 qsvg4.dll                                                             
-a----        5/18/2017  10:04 AM          25088 qtga4.dll                                                             
-a----        5/18/2017  10:04 AM         358912 qtiff4.dll                                                            



@embryo10

In the dist directory I have these directories that you don’t:
«4Build_CheckdistCheckadodbapi»
«4Build_CheckdistCheckDemos»
«4Build_CheckdistCheckinclude»
«4Build_CheckdistCheckisapi»
«4Build_CheckdistChecklibs»
«4Build_CheckdistCheckpywin»
«4Build_CheckdistChecktest»
«4Build_CheckdistCheckwin32com»
«4Build_CheckdistCheckwin32comext»

and these extra files:
«4Build_CheckdistCheck_socket.pyd»
«4Build_CheckdistCheck_ssl.pyd»
«4Build_CheckdistChecklicense.txt»
«4Build_CheckdistCheckmfc90.dll»
«4Build_CheckdistCheckmfc90u.dll»
«4Build_CheckdistCheckmfcm90.dll»
«4Build_CheckdistCheckmfcm90u.dll»
«4Build_CheckdistCheckMicrosoft.VC90.CRT.manifest»
«4Build_CheckdistCheckMicrosoft.VC90.MFC.manifest»
«4Build_CheckdistCheckperfmondata.dll»
«4Build_CheckdistCheckpythoncom27.dll»
«4Build_CheckdistCheckpythoncomloader27.dll»
«4Build_CheckdistCheckpythonservice.exe»
«4Build_CheckdistCheckPythonwin.exe»
«4Build_CheckdistCheckPyWin32.chm»
«4Build_CheckdistCheckpywin32.pth»
«4Build_CheckdistCheckpywin32.version.txt»
«4Build_CheckdistCheckpywin32-218-py2.7.egg-info»
«4Build_CheckdistCheckpywintypes27.dll»
«4Build_CheckdistCheckscintilla.dll»
«4Build_CheckdistCheckunicodedata.pyd»
«4Build_CheckdistCheckwin32api.pyd»
«4Build_CheckdistCheckwin32evtlog.pyd»

The contents of the qt4_plugins folders are the same.
I couldn’t compare the sizes (I think they are different)
How can I take the print you took? Is it some command I can use in the cmd.exe?

@ghost

The powershell command is ls -r

@ghost

actually let me upload my program and you can see whether it works on your computer.

@embryo10

Do you use Windows 7 x64?

@ghost

@ghost

@embryo10

The test.exe runs fine.
Comparing your files with the same mine, shows that all of them are different.
What version of PySide are you using?
Is your Python 32bit?
Is the different windows version enough to justify these differences?

@ghost

PySide 1.2.4
Windows 10 x64
Python 2.7 x64

@ghost

@embryo10

I think the problem is the Python 2.7 x86
Can you check this?

@embryo10

@xoviat
Any news for the Python 2.7.13 x86 support (in x64 systems)?
Can I help testing this here in some way?

@ghost

I’ll test this sometime soon, but I’m honestly not optimistic that I’ll be able to reproduce this issue, and if I cannot reproduce the issue, there is very little chance of me fixing it.

@embryo10

I think that if you install the 32bit version of python in your x64 system, you will have the same problems with PyInstaller.
You can also try a VM.
If you need any testing, tell me.
… and thank you for your time…

@ghost

I think that if you install the 32bit version of python in your x64 system, you will have the same problems with PyInstaller.

Nope. Everything works fine with Python 2.7.13 x86, as I thought it would.

@ghost

If you need any testing, tell me.

How about posting the output of the example script using log-level=TRACE.

@embryo10

The contents of the warncheck.txt are

missing module named PyQt4 - imported by d:appsdevpythonpython27libsite-packagesPyInstallerloaderrthookspyi_rth_qt4plugins.py
missing module named org - imported by copy
missing module named console - imported by pyreadline.console.ansi
missing module named startup - imported by pyreadline.keysyms.common, pyreadline.keysyms.keysyms
missing module named System - imported by pyreadline.clipboard.ironpython_clipboard, pyreadline.keysyms.ironpython_keysyms, pyreadline.console.ironpython_console, pyreadline.rlmain
missing module named _scproxy - imported by urllib
missing module named EasyDialogs - imported by getpass
missing module named termios - imported by getpass
missing module named pwd - imported by posixpath, getpass
missing module named SOCKS - imported by ftplib
missing module named rourl2path - imported by urllib
missing module named IronPythonConsole - imported by pyreadline.console.ironpython_console
missing module named clr - imported by pyreadline.clipboard.ironpython_clipboard, pyreadline.console.ironpython_console
missing module named 'org.python' - imported by pickle
missing module named fcntl - imported by tempfile, subprocess
missing module named riscosenviron - imported by os
missing module named riscospath - imported by os
missing module named riscos - imported by os
missing module named ce - imported by os
missing module named _emx_link - imported by os
missing module named os2 - imported by os
missing module named posix - imported by os
missing module named resource - imported by posix

Trying to get the TRACE output with

pyinstaller --name Check -i Check.ico --log-level=TRACE main.py > x.txt

produces an empty x.txt file.
Is there another way?

@embryo10

OK got it.
It was the STDERR that we wanted.
z.txt

@embryo10

This is a better one.
The other was created from a link, so some addresses are wrong…
err.txt

@embryo10

@xoviat
So, did you discover anything in the log?

@ghost

Honestly it’s going to be a few weeks until I will be able to look at this. I have some other things I need to take care of first.

@embryo10

Its OK, as long as you find what’s wrong with this…
I’ll postpone the update to v3 for the time being.

@embryo10

Update:
After installing the python 2.7.13 x86 from scratch and all the dependencies, PyInstaller compiles the executable just fine!
I’m sorry for your lost time and thank you for your efforts….

@ghost

@github-actions
github-actions
bot

locked as resolved and limited conversation to collaborators

Nov 18, 2022

0 / 0 / 0

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

Сообщений: 17

1

11.02.2020, 17:55. Показов 30645. Ответов 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

Сообщений: 84

23.12.2020, 15:45

12

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

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



0



Troubleshooting

Hints for solving common problems that may arise when
using fbs.

My frozen app won’t start

In this scenario, fbs run works but running the
binary obtained from fbs freeze gives an error.
On Windows, the error is typically shown in a dialog:

'Failed to execute script main' dialog when running a PyQt / PySide app

Besides main, the error message may also
mention fbs_pyinstaller_hook – see
further below.


Failed to execute script main

To get more information in this case, run the following
commands:

fbs clean
fbs freeze --debug

When you then start the standalone binary of your
application from the command line, you should see a
lot more debug output. If it contains an
ImportError, see the

section on Dependencies

in fbs’s Manual for a possible solution.


Failed to execute script fbs_pyinstaller_hook

This typically happens when your code does not create an

ApplicationContext.
This is required for fbs to work. Please see the

tutorial
for an example.

  • The most common mistake
  • PyQt and PyInstaller versions
  • My frozen app won’t start

How to Fix Backup and Sync "failed to execute script main"

Today’s post is about how to fix the Google Drive Backup and sync error of “failed to execute script main”.

So, here’s the background. Yesterday morning, I woke up my computer from sleep mode. Google Drive should be running all the time to back up my files, but yesterday, the Backup and sync icon was disappeared from my taskbar.

I tried to open the program again, but got the following error:

Google Drive Backup and Sync Traceback Error

(A screenshot from Google Drive Help Community)

After clicked on “OK”, the “failed to execute script main” window popped up.

Google Drive Backup and Sync Failed to Execute Script Main

(A screenshot from Google Drive Help Community)

By following the suggestions that I found online, I tried:

  • Restarted the PC (didn’t work for me).
  • Downloaded the latest version of Google Backup and sync, uninstalled the former version, then installed the latest one (didn’t work for me).
  • Cleaned up any leftover install/Google Drive folders/subfolders/temp files, restarted the computer, reinstalled the program, and then ran Google Drive as administrator (didn’t work for me).

Fortunately, I opened Windows Security to have a look. Found Google.exe was been blocked. After allowed it manually, the problem was solved.

I totally relate to how software issues like this can drive you crazy, so I’ve put up some solutions that might be helpful to fix the “Backup and sync failed to execute script main” error.

Solution for Fixing Google Drive “failed to execute script main” on Windows 10, 8, 7, etc.: Check the Protection History of Your Antivirus Software

Windows Security shows a green tick and doesn’t prompt any message does not mean that it hasn’t blocked something. Some other antivirus protections might be the same, so this is the first solution you should check.

**Check both Windows Security and your antivirus software, in case you have one.

Steps:

  1. Open “Windows Security” > “Virus & threat protection” > “Protection history”.
  2. Look at the “App or process blocked” item, if you find something like googledrivesync.exe, GOOGLE.EXE, etc. you need to click on “Actions” > “Allow on device”.
  3. Reopen Google Backup and sync.

Allow Google Drive in Windows Security to Solve Failed to Execute Script Main

Follow These Steps If It Still Doesn’t Work

  1. Make sure you are using a Windows login account that has full administrator privileges.

Using Windows with Administrator Account

  1. Uninstall Backup and sync in Control PanelProgramsPrograms and Features
  2. Restart your computer.
  3. Clean up any leftover files of Backup and sync:
    1. Delete the folder and all subfolders found here: C:Program FilesGoogleDrive (Depending on where the installation failed, this may not be present)
    2. Delete the folder and all subfolders found here: C:UsersYOUR-WINDOWS-USERNAMEAppDataLocalGoogleDrive (Depending on where the installation failed, this may not be present)
    3. Clean up as much of your Windows Temp folder as possible: C:WindowsTemp (Some files are unable to be deleted. You can just skip those).
  4. Clean out any partial registry keys:
    1. Press Windows Key + R
    2. type regedit then click OK to run
    3. Accept the request by the operating system to permit the command.
    4. Navigate to the key location: ComputerHKEY_LOCAL_MACHINESOFTWAREGoogleDrive (Depending on where the installation failed, this may not be present).
    5. If present, on the left side, right click the Drive entry and select delete.
  5. Download and install the latest version of Backup and sync from Google.

To our reader who’s reading this post: if you have tried other solutions that work for you, welcome to drop a comment below. It definitely can save someone’s day! 😊

Photo of Susanna

Susanna is the content manager and writer of Filelem. She has been an experienced editor and book layout designer for many years, and interested in trying and testing various productivity software. She is also a huge fan of Kindle, who has been using Kindle Touch for nearly 7 years and carrying Kindle almost wherever she goes. Not long ago the device was at the end of its life so Susanna happily bought a Kindle Oasis.

Понравилась статья? Поделить с друзьями:
  • Failed to authenticate ourselves to peer ошибка
  • F78 ошибка милле посудомоечная машина
  • F75 ошибка котла вайлант турбо тек
  • F75 ошибка котла protherm panther
  • F75 vaillant ошибка методы устранения форум