Ошибка при запуске exe python

I am trying to use Pyinstaller to create a python 2.7 executable in windows 7. I followed all the suggestions in the manual (using pip-win and Pywin32) but once the file has been created I cannot open the application and I get the error message:

«Windows cannot access the specified the specified device, path, or file. You may not have the appropriate permissions to access the item.»

Does anyone have any idea why this might be happening and what I can do to prevent it? Sorry if this question is a bit vague, I will try and provide more details if I can.

Thanks in advance

asked Jan 6, 2014 at 20:01

alkey's user avatar

2

after hours and bad answers i found this and worked: Pyinstaller exe not working on other computer(with other windows ver.)

in short: find the location of pythonXX.dll and add it to the libraries example command:

pyinstaller -F --icon "C:/iconspath/ico.ico" --add-data "C:/pythoninstallpath/python37.dll;."  .mypyprogram.py 

or simpler send both the generated exe and the pythonXX.dll

(XX is the version in my case is python37.dll)

answered Jan 3 at 17:01

Alessandro Blue's user avatar

this isn’t a direct solution to your question, but it might be a good workaround. instead of packaging your python script in a .exe file, just use py.exe to start your .py file using:
http://www.orbitals.com/programs/pyexe.html

answered Jan 6, 2014 at 20:58

Nothing 2 Lose's user avatar

Nothing 2 LoseNothing 2 Lose

1801 gold badge3 silver badges8 bronze badges

2

I had this same problem after I turned my .py file to an .exe file using pyinstaller (I’m using Python 3.6).

It would run fine on my computer, but when sending it to others to run, firstly the computer would try to stop it from running (understandable, but you can tell Windows that you trust it when the pop-up appears). It would then be saved to their computer. I tried to run the file and got the same pop-up you did. I figured it was their anti-virus stopping it from running, so opened the anti-virus software and added an exception for my file. After that it worked fine.

Granted, it’s an inconvenient way to do it, but until I learn further it works for now.

answered Oct 27, 2017 at 16:03

Chuck's user avatar

ChuckChuck

232 silver badges10 bronze badges

I had the same problem since today (the last days was working fine).
I figured out that the problem was when I create the .exe file with —icon, if you don’t create the file with the —icon should work fine.

answered May 15, 2019 at 23:17

Pedro's user avatar

PedroPedro

2014 silver badges8 bronze badges

I’m building a simple script of python 3.5.2 which imports pyrebase (firebase library), tkinter and openpyxl

script standalone from pycharm or cmd works perfectly.

I’m trying to generate an exe for it, I have tried to use many combinations python3.4 — python3.6, py2exe, pyinstaller, cx_Freeze and nothing worked for me.

The last thing I’m trying now it pyinstaller — python 3.5.2
now I’m usig pyinstaller to exe gui https://github.com/brentvollebregt/auto-py-to-exe

build complete successfully, when I try to run from cmd: python file.exe I get error of:

   SyntaxError: Non-UTF-8 code starting with 'x90' in file outputEMAInnerSpeechMain.exe on line 1

while I have

    # coding: utf-8

in my code

when try to run from cmd: file.exe I get the following error:

    File "site-packagesCryptoUtil_raw_api.py", line 168, in load_pycryptodome_raw_lib 
OSError: Cannot load native module 'Crypto.Hash._SHA256'

I have tried everything I find in the interent to build an exe from my script but I’m not succeeding, please help

my code:

# coding: utf-8
import sys
from tkinter import *
from tkinter import filedialog
import datetime
from openpyxl import Workbook
from openpyxl.styles import colors
from openpyxl.styles import Font, Color
import pyrebase
from collections import defaultdict

config = {
    "apiKey": "****",
    "authDomain": "****,
    "databaseURL": "****",
    "storageBucket": "****"
}

f  = pyrebase.initialize_app(config)
firebaseData = f.database()
firebaseStorage = f.storage()

root = Tk()
welcomeLabel = Label(root, text="Please fill in "path" where you want data to be exportedn"
                            "and press export to excel button to start",     anchor=W, justify=LEFT)
welcomeLabel.grid(row=0, sticky=W, padx=10, pady=10)
pathLabelBase = "Path: "
pathLabel = Label(root, text=pathLabelBase, anchor=W, justify=LEFT)
pathLabel.grid(row=1, column=0, sticky=W, padx=10, pady=10)

statusLabel = Label(root, text="", anchor=W, justify=LEFT)
statusLabel.grid(row=3, sticky=W, padx=10, pady=10)


def browsefunc():
    dirName = filedialog.askdirectory()
    if dirName != "":
        statusLabel.config(text="")
    pathLabel.config(text=pathLabelBase + dirName)


browseButton = Button(root, text="Browse", command=browsefunc)
browseButton.grid(row=1, column=1, sticky=W,  padx=10, pady=10)


def exportToExcel():
    dirPath = pathLabel.cget("text")
    if pathLabelBase == dirPath:
        statusLabel.config(text="Please choose directory to export excel file to.nBy clicking on "Browse" button.",
                      fg="red")
    return
   ...fetching data from firebase and creating excel file

exportButton = Button(root, text="Export to excel", fg="blue",     command=exportToExcel)
exportButton.grid(row=2, column=1, sticky=W, columnspan=2, padx=10, pady=10)

root.mainloop()

Any is help is appreciated!

Thanks in advance

Здравствуйте!
Я написал программу в pyCharm и она отлично работает если её запускать в pyCharm.
Я решил сделать .exe файл при помощи pyinstaller, py2exe, auto_py_to_exe, cx_Freeze, на выходе имею .exe-файл файл который начинает правильно отрабатывать, но в итоге программа заходит в блок except. Также пробовал использовать другие библиотеки для создания .exe, cx_Freeze, auto-py-to-exe
Python 3.6 32-bit
Также у меня создался файл *.pyc, и если его запустить, то отрабатывает всё хорошо.
Основной код больше, скину саму суть:

Подключаемся к ОРС:
import OpenOPC

opc = OpenOPC.client()
servers = opc.servers()
print(servers)
try:
    opc.connect(servers[0])
except:
    print("не удалось подключиться к ОРС - серверу")

while:
    try:
       #обрабатываем полученнные значения
    except:
        print("error read item")
        opc.close()

Как я понимаю проблема в виртуальной среде, но в cmd.exe я установил все необходимые библиотеки как в проекте pycharm.
Вот так отрабатывает скрипт OpcSender.py из консоли или из pyCharm
5ee4cf446397e452835910.png
Вот так отрабатывает OpcSender.exe
5ee4d00c712e2569966194.png
Что посоветуете? заранее спасибо.

16 / 0 / 2

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

Сообщений: 94

1

07.05.2022, 17:37. Показов 6073. Ответов 18


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

Всем привет!
Подскажите пожалуйста новичку — написал простенькую програмку на python с использованием библиотеки PyAutoGui. В PyCharm все работает, но когда компилирую в exe файл(через команду

Код

pyinstaller -F WorkHelper1.py

), то при запуске EXEшника выдает ошибку «ModuleNotFoundError: No module named ‘pyautogui'».
Как это исправить?

Не работает программа после компиляции в exe ModuleNotFoundError



0



Am I evil? Yes, I am!

Эксперт PythonЭксперт Java

16956 / 9178 / 2634

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

Сообщений: 20,898

07.05.2022, 17:46

2

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

Как это исправить?

Не использовать pyinstaller



0



16 / 0 / 2

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

Сообщений: 94

07.05.2022, 17:48

 [ТС]

3

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

Не использовать pyinstaller

Посоветуйте, что в таком случае лучше использовать?



0



Am I evil? Yes, I am!

Эксперт PythonЭксперт Java

16956 / 9178 / 2634

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

Сообщений: 20,898

07.05.2022, 17:49

4

Интерпретатор питона



0



16 / 0 / 2

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

Сообщений: 94

07.05.2022, 17:53

 [ТС]

5

Основная задача — запуск программы на компьютерах, где python не установлен.
Как скомпилировать в EXE, чтобы не возникало ошибки при запуске?



0



Am I evil? Yes, I am!

Эксперт PythonЭксперт Java

16956 / 9178 / 2634

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

Сообщений: 20,898

07.05.2022, 17:54

6

Напиши на С++.

PS. pyinstaller не компилирует в .exe



0



16 / 0 / 2

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

Сообщений: 94

07.05.2022, 18:47

 [ТС]

7

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

Напиши на С++

с такими советами, тебе в ветку С++

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

PS. pyinstaller не компилирует в .exe

упаковывает…



0



1001 / 345 / 59

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

Сообщений: 922

07.05.2022, 20:08

8

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

Основная задача — запуск программы на компьютерах, где python не установлен.

1. Оставляете в покое pyinstaller
2. Скачиваете python embedded инструкция
3. Создаете файл .bat для запуска скрипта
4. Делаете ярлык для запуска .bat

Ношу свою прогу с собой на флешке и запускаю где это нужно

Миниатюры

Не работает программа после компиляции в exe ModuleNotFoundError
 



3



1001 / 345 / 59

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

Сообщений: 922

07.05.2022, 20:17

9

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

Как скомпилировать в EXE, чтобы не возникало ошибки при запуске?

pyinstaller штука прикольная, когда на ютубе делают .exe для 10 строк кода и кнопки, когда с дефолтными настройками он все пакует. В общем pyinstaller не так прост в обращении как его представляют на просторах интернета и с ним придется изрядно повозится.



0



1511 / 481 / 56

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

Сообщений: 8,134

07.05.2022, 20:17

10

Цитата
Сообщение от Михалыч
Посмотреть сообщение

1. Оставляете в покое pyinstaller
2. Скачиваете python embedded инструкция
3. Создаете файл .bat для запуска скрипта
4. Делаете ярлык для запуска .bat
Ношу свою прогу с собой на флешке и запускаю где это нужно

хотелось услышать скептиков…………….



0



Михалыч

07.05.2022, 20:20

Не по теме:

Ципихович Эндрю, с чем связан скептицизм? вполне рабочий вариант)



0



1511 / 481 / 56

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

Сообщений: 8,134

07.05.2022, 20:29

12

Цитата
Сообщение от Михалыч
Посмотреть сообщение

с чем связан скептицизм?

у меня его нет………….
я спрашивал если есть такие, то их мнение……….

Цитата
Сообщение от Михалыч
Посмотреть сообщение

вполне рабочий вариант)

ну и хорошо, не пробовал, не знаю………….



0



16 / 0 / 2

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

Сообщений: 94

10.05.2022, 20:47

 [ТС]

13

Михалыч, огромное спасибо! Сделал по вашей инструкции, все работает!



0



1001 / 345 / 59

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

Сообщений: 922

11.05.2022, 08:48

14

emkaa, я рад, что у вас получилось!

От меня «+» что попробовали и разобрались)



0



1001 / 345 / 59

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

Сообщений: 922

20.06.2022, 22:08

15

Цитата
Сообщение от Михалыч
Посмотреть сообщение

2. Скачиваете python embedded инструкция

Ссылка перестала работать. Сохранил как pdf



3



2 / 2 / 0

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

Сообщений: 41

03.10.2022, 20:58

16

Вам поможет параметр «скрытый импорт» или «вся коллекция»
pyinstaller -F WorkHelper1.py —hidden-import «pyautogui» иили —collect-all «pyautogui»



1



1511 / 481 / 56

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

Сообщений: 8,134

27.01.2023, 11:44

17

вот дошли руки, точнее появился материал с чего можно попытаться сделать экзешник, стал смотреть
пдф файл: python embedded или как добавить python в свое
приложение
так там же описано как сделать, НО не экзешник как сказано в посте № 1

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

exe

а там описано как НЕ устанавливая питон его заиметь…..
кстати как сказано в пдф файле
Затем находим чистый Windows 10,
где Python никогда не был установлен. Скачиваем архив и распаковываем.
Запускаем любой тестовый скриптик.

есть у кого готовый? с какими модулями?



0



1511 / 481 / 56

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

Сообщений: 8,134

09.02.2023, 10:06

18

Цитата
Сообщение от Ципихович Эндрю
Посмотреть сообщение

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

попытка 2
порядок действий:
pyinstaller должен быть установлен в командной строке (ну естественно и сам pip)
установка: pip install pyinstaller
Python на ПК и все модули, требуемые вашему скрипту должны быть установлены
в командной строке ввести:
cd C:pythonProject
затем:
pyinstaller —onefile main.py
где C:pythonProject и main.py — путь к каталогу где лежит файл, который требуется превратить в экзешник и название этого файла, нажимаем Enter
по окончании работы в указанном каталоге появится:

Миниатюры

Не работает программа после компиляции в exe ModuleNotFoundError
 



0



1511 / 481 / 56

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

Сообщений: 8,134

09.02.2023, 12:17

19

не реклама, не бравада, просто если сам забуду — будет где посмотреть и вспомнить………

Добавлено через 2 часа 8 минут
ну и как говорится аппетит приходит во время еды))
есть ли такое понятие в пайтоне как поместить файл с данными в ресурсы? если да то как это сделать, какой файл возможно поместить в ресурсы и какова должна быть его структура?



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

09.02.2023, 12:17

19

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.

  • Ошибка при запуске ex machina меридиан 113
  • Ошибка при запуске death stranding directx 12
  • Ошибка при запуске ex machina 0xc0000005
  • Ошибка при запуске death stranding build dso 176 2099797
  • Ошибка при запуске everlasting summer