I code in PyCharm and went into C:\Users\MyUser\PyCharmProjects\MyFile and from there went into cmd in that directory, executed pyinstaller --onefile -w main.py. This worked perfect. I grabbed my main.exe from dist and put it into MyFile and executed it but upon doing so it brought up the following error:
Traceback (most recent call last):
File "main.py", line 2, in <module>
from pynput.mouse import Controller, Button
File "PyInstaller\loader\pyimod03_importers.py", line 540, in exec_module
File "pynput\__init__.py", line 40, in <module>
File "PyInstaller\loader\pyimod03_importers.py", line 540, in exec_module
File "pynput\keyboard\__init__.py, line 31, in <module>
File "pynput\_util\__init__.py", line 76, in backend
ImportError
[4752] Failed to execute script main
The purpose of my code is to move around your mouse rapidly until you hold down a, b, and c. Just a fun practical joke. Here is a copy of it:
import keyboard
from pynput.mouse import Controller, Button
import random
import tkinter as tk
root = tk.Tk()
mouse = Controller()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
while True:
xVar = random.randint(0, screen_width)
yVar = random.randint(0, screen_height)
mouse.position = (xVar, yVar)
if keyboard.is_pressed("a") and keyboard.is_pressed("b") and keyboard.is_pressed("c"):
break
I've honestly tried everything. I can't figure out what is going wrong with it. Any help would be appreciated. Thanks!
You have to add --hidden-import="pynput.keyboard._win32" --hidden-import "pynput.mouse._win32", so pyinstaller can include the backend that pynput uses. So something like:
pyinstaller --hidden-import="pynput.keyboard._win32" --hidden-import="pynput.mouse._win32" app.py
You can also add this to your spec file.
hiddenimports=["pynput.keyboard._win32", "pynput.mouse._win32"]
If you are using macOS then replace '_win32' with '_darwin' and if linux, replace with '_xorg'.
The other method is to fallback to a previous version which is not recommended, but just incase you want it. First pip uninstall pynput then:
pip install pynput==1.6.8
Related
I was working with python (which I rarely do) for a simple program that macros some functionalities with certain keyboard inputs. I decided to export the script to a .exe using pyinstaller so I go ahead and run command: pyinstaller --onefile code.py and it generates the code.exe as expected. Only for my .exe to crash instantly. I got a view of the error by running it with cmd and got this
Traceback (most recent call last):
File "code.py", line 1, in <module>
File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module
File "pynput\__init__.py", line 40, in <module>
File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module
File "pynput\keyboard\__init__.py", line 31, in <module>
File "pynput\_util\__init__.py", line 76, in backend
ImportError
[1284] Failed to execute script 'code' due to unhandled exception!
I'm certain there is an explanation to this so here are my imports:
from pynput import keyboard
from pynput.keyboard import Key
from pywinauto import application
from pywinauto.findwindows
import WindowAmbiguousError, WindowNotFoundError
import os
I couldn't seem to find any similar problems on here. Thank you in advance for the help.
In your .spec file, you should add all of your modules as "hidden imports", this usually fixes all module not found errors.
hiddenimport=["pynput","pywinauto"]
Then run pyinstaller with the spec file
pyinstaller my.spec
I'd also ensure you're using a virtual environment during this entire process.
I am having trouble with PyInstaller. I am trying to build the main file (Logical.py -> Logical.exe). When I run the file as a python script it runs fine (terminal: python Logical.py examples/led.lgc). When I run the exe built by PyInstaller (terminal: ./Logical examples/led.lgc), I get this error message:
Traceback (most recent call last):
File "Logical.py", line 2, in <module>
from pynput import keyboard
File "PyInstaller\loader\pyimod03_importers.py", line 540, in exec_module
File "pynput\__init__.py", line 40, in <module>
File "PyInstaller\loader\pyimod03_importers.py", line 540, in exec_module
File "pynput\keyboard\__init__.py", line 31, in <module>
File "pynput\_util\__init__.py", line 76, in backend
ImportError
[10688] Failed to execute script Logical
It appears to be upset about the pynput import, though I have no idea why. The imports of my source are below. loading and ui are both in the project directory and simpleANSI's source code is listed at the bottom of this post.
import sys, time, os, ctypes
from pynput import keyboard
from loading.loading import loadElement
from ui import vec2, widget, ansiManager
import simpleANSI as ANSI
import pdb
I run both of these repositories so I can guarantee that they will not change until I can get this fixed.
Full project source code - https://github.com/AwesomeCronk/Logical
Main file - https://github.com/AwesomeCronk/Logical/blob/master/Logical.py.
simpleANSI source code - https://github.com/AwesomeCronk/simpleANSI
I am using Python 3.9.5 on Windows 10 x64, PyInstaller version 4.3, pynput version 1.7.3.
EDIT: I dug through the Python lib files and found the destination of the traceback. This is the offending function in ...\python\3.9.5\Lib\site-packages\pynput\_util\__init__.py:
def backend(package):
"""Returns the backend module for a package.
:param str package: The package for which to load a backend.
"""
backend_name = os.environ.get(
'PYNPUT_BACKEND_{}'.format(package.rsplit('.')[-1].upper()),
os.environ.get('PYNPUT_BACKEND', None))
if backend_name:
modules = [backend_name]
elif sys.platform == 'darwin':
modules = ['darwin']
elif sys.platform == 'win32':
modules = ['win32']
else:
modules = ['xorg']
errors = []
resolutions = []
for module in modules:
try:
return importlib.import_module('._' + module, package)
except ImportError as e:
errors.append(e)
if module in RESOLUTIONS:
resolutions.append(RESOLUTIONS[module])
raise ImportError('this platform is not supported: {}'.format( # AwesomeCronk: This is the offending line
'; '.join(str(e) for e in errors)) + ('\n\n'
'Try one of the following resolutions:\n\n'
+ '\n\n'.join(
' * {}'.format(s)
for s in resolutions))
if resolutions else '')
I tried adding --hidden-import "pynput.keyboard._win32" --hidden-import "pynput.mouse._win32" to the PyInstaller args to no avail. I wound up rolling back pynput to version 1.6.8.
I have a python code that I wanted to turn into an exe.
I used pyinstaller with : pyinstaller --onefile -w script.py
After it finished making the exe file I double clicked the file but I got "Failed to execute script".
I also tried running it from the cmd but it gives the same fatal error.
Stuff to add:
The code imports a couple of files packages including a python code I made, as well as it makes files referenced to it's location.
Is there something I'm doing wrong?
the script has those imports:
import socket
import os
from PIL import ImageGrab
import cv2
import time
import json
import myFile
I ran the code under cmd and it gives this error:
File "script.py", line 3, in <module>
from PIL import ImageGrab
ModuleNotFoundError: No module named 'PIL'
Might be unrelated but now that I tried to do pyinstaller --onefile -w client.py.
After I ran it windows defender found this inside :
after running it in the terminal in pycharm with :
pyinstaller --onefile --hidden-import=PIL --hidden-import=Pillow --hidden-import=pynput client.py
I get this error (note that i moved it from the dist directory to the main one):
Traceback (most recent call last):
File "client.py", line 7, in <module>
import myFile
File "PyInstaller\loader\pyimod03_importers.py", line 540, in exec_module
File "myFile.py", line 1, in <module>
from pynput import mouse, keyboard
File "PyInstaller\loader\pyimod03_importers.py", line 540, in exec_module
File "pynput\__init__.py", line 40, in <module>
File "PyInstaller\loader\pyimod03_importers.py", line 540, in exec_module
File "pynput\keyboard\__init__.py", line 31, in <module>
File "pynput\_util\__init__.py", line 82, in backend
ImportError
[13364] Failed to execute script client
This may be due to pyinstaller not being able to properly find your dependencies and skipping some packages.
To fix any error like ModuleNotFoundError: No module named 'PIL' just add it as a hidden import:
pyinstaller --onefile --hidden-import=PIL -w script.py
For the second error this is a known issue with pyinstaller and pynput.
Find here some explanation.
The TLDR of it seems to be that you need to add --hidden-import=pynput.mouse._win32 --hidden-import=pynput.keyboard._win32 --hidden-import=pynput._util._win32 and any other sub-packages that give you errors.
Recently I was working with the module pyautogui when I got an error, at first I dismissed it but then when I tried to run other programs the same error, referring to the pyautogui program popped up even though the other program had nothing to do with pyautogui. This was all in VSC, so after opening and closing VSC a few times and the error still occurred when I imported any module I decided to build my programs in terminal instead. The same error shows up. Below I have pasted the error from my terminal which will still not allow me to make any python module import whatsoever. Any help is greatly appreciated.
I have upgraded, uninstalled, and reinstalled everything and still the same
>>> import random
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Aezene\random.py", line 15, in <module>
StartLocation = pyautogui.locateOnScreen('Start.png')
File "C:\Users\Aezene\AppData\Roaming\Python\Python39\site-packages\pyautogui\__init__.py",
line 175, in wrapper
return wrappedFunction(*args, **kwargs)
File "C:\Users\Aezene\AppData\Roaming\Python\Python39\site-packages\pyautogui\__init__.py",
line 213, in locateOnScreen
return pyscreeze.locateOnScreen(*args, **kwargs)
File "C:\Users\Aezene\AppData\Roaming\Python\Python39\site-packages\pyscreeze\__init__.py",
line 359, in locateOnScreen
screenshotIm = screenshot(region=None) # the locateAll() function must handle cropping to return
accurate coordinates, so don't pass a region here.
File "C:\Users\Aezene\AppData\Roaming\Python\Python39\site-packages\pyscreeze\__init__.py",
line 134, in wrapper
raise PyScreezeException('The Pillow package is required to use this function.')
pyscreeze.PyScreezeException: The Pillow package is required to use this function.
>>>
This happens because you haven't downloaded the "Pillow" package. You can download by using the command "pip install Pillow" or by using the following code:
from subprocess import *
from sys import *
call([executable, "-m", "pip, "install", "Pillow"])
You need to have this module because pyautogui's code won't run without it. If you install PyCharm and look at PyAutoGui's file code, you'll see that it is necessary to install the module
I have written a program that I have tried to turn into an executable using PyInstaller. Pyinstaller appears to have finished without any errors and I end up with an application in /dist/my_program. However, when I try to run that application a console window flashes up for a second with a traceback:
Edit: I have copied the traceback out. There may be a mistake as I had to type it up from a screenshot because it only flashes up.
Traceback (most recent call last):
File "<string>", line 14, in <module>
File "C:\Users\user\desktop\PyInstaller-2.1\PyInstaller\loader\pyi_importers.py", line 270, in load_module
exec(bytecode, module.__dict__)
File "C:\Users\user\desktop\PyInstaller-2.1\my_program\build\my_program\out00-PYZ.pyz\matplotlib.pyplot", line 108, in <module>
File "C:\Users\user\desktop\PyInstaller-2.1\my_program\build\my_program\out00-PYZ.pyz\matplotlib.backends", line 32, in pylab_setup
File "C:\Users\user\desktop\PyInstaller-2.1\PyInstaller\loader\pyi_importers.py", line 270, in load_module
exec(bytecode, module.__dict__)
File "C:\Users\user\desktop\PyInstaller-2.1\my_program\build\my_program\out00-PYZ.pyz\matplotlib.backends.backend_tkagg", line 7, in <module>
File "C:\Users\user\desktop\PyInstaller-2.1\my_program\build\my_program\out00-PYZ.pyz\six", line 194, in load_module
File "C:\Users\user\desktop\PyInstaller-2.1\my_program\build\my_program\out00-PYZ.pyz\six", line 108, in _resolve
File "C:\Users\user\desktop\PyInstaller-2.1\my_program\build\my_program\out00-PYZ.pyz\six", line 779, in _import_module
ImportError: No module named FileDialog
Below are the imports that I have in my code:
import Tkinter
from tkFileDialog import askopenfilename
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import subprocess
from PIL import Image, ImageTk
import os
Does anyone know whats causing this/what the fix is? I presume the error is the importation of tkFileDialog?
Edit2: the program runs fine when I run it in my interpreter (Spyder) but when I packaged it using PyInstaller the resulting application gives this error.
According to this question adding import FileDialog solves the problem. Matplotlib seems to need this.
However, I've used Pyinstaller on a script of mine also importing matplotlib and it gives no such error. So I don't know what exacly is the problem here.