Pyinstaller "Failed to execute script due to unhandled exception" Error - python

I made a simple program that works as a .py file, but when I use pyinstaller to make a .exe file, the command prompt opens and closes immediately. By screen recording opening the .exe, I was able to see the following error flash on the command prompt before it closed: "Failed to execute script "kahoot_spammer" due to unhandled exception!"
I am using pyinstaller --onefile kahoot_spammer.py to convert my .py to a .exe file. Here is the code in my program; which I plan on using at school to add a ton of users to the class Kahoot game:
from pynput.mouse import Button, Controller as mController
from pynput.keyboard import Key, Controller as kController
import time
mouse = mController()
keyboard = kController()
#ask user for the kahoot game pin, what name they want the fake players to have, and how many players to create
game_code = input("Game Code: ")
username = input("Username: ")
amount = input("Player Amount: ")
#delay the program so the user can switch to their browser with kahoot open
time.sleep(5)
#create players
for i in range(amount):
#enter game pin
mouse.position = (775, 500)
mouse.click(Button.left, 1)
keyboard.type(game_code)
mouse.position = (775, 550)
mouse.click(Button.left, 1)
time.sleep(0.5)
#enter username
mouse.position = (775, 520)
mouse.click(Button.left, 1)
keyboard.type(username + str(i))
mouse.position = (775, 570)
mouse.click(Button.left, 1)
time.sleep(0.2)
#open new tab with kahoot ready to go
keyboard.press(Key.ctrl)
keyboard.press("t")
keyboard.release(Key.ctrl)
keyboard.release("t")
keyboard.type("https://kahoot.it")
keyboard.press(Key.enter)
keyboard.release(Key.enter)
time.sleep(1)
Does anyone know how I can fix this error, and have the program run as it should? The .pyc file that is created alongside the .exe works as it should; the command prompt stays open and the program functions as expected.

I would suggest using pyinstaller --onefile --debug=all kahoot_spammer.py to get more debug information.
In my specific case my application failed when importing a logging object associated with my GUI library Kivy. So I commented out the line in my code that turned logging off and it works now.
This link helped me: https://pyinstaller.readthedocs.io/en/stable/when-things-go-wrong.html

Related

Python output insists I need "tkinter", yet none of the modules I have called use it

Being very new to Python, any help at all is greatly appreciated.
I'm trying to make a spammer thing to mess with my friends, and the output keeps insisting that I need "tkinter".
The modules that I'm using are pyautogui, time, and subprocess and some Googling has told me that none of those have to use tkinter for anything.
When I try to actually install tkinter it won't install (apt-get or pacman) What can I do?
Here is my code:
import pyautogui
import time
import subprocess
def sendNotif(title, message):
subprocess.run(['notify-send', title, message])
message = input("Enter message (leave blank to paste clipboard")
repeats = int(input("Number of times to send the message:"))
delay = int(input("Number of ms between each message (seconds x 1000): "))
isLoaded = input("Open your messaging application and press Enter when it's ready")
print("You have 5 seconds to refocus the message entering area of your chat application.")
time.sleep(5)
for i in range(0,repeats):
if message != "":
pyautogui.typewrite(message)
pyautogui.press("enter")
else:
pyautogui.hotkey('ctrl', 'v')
pyautogui.press("enter")
time.sleep(delay/1000)
sendNotif('Finished Sending Flood', 'Now we play the waiting game......')
print("Done")

How to run script with elevated privilege on windows but only the first time when i run it

So i already wrote a program that asks for admin privileges, but the problem is the admin have to grant permission every time it runs
so is there anyway that the program stays on admin privilege without asking for permission everytime
code example
from pyuac import main_requires_admin
#main_requires_admin
def main():
print("Do stuff here that requires being run as an admin.")
# The window will disappear as soon as the program exits!
input("Press enter to close the window. >")
if __name__ == "__main__":
main()

How to open a program using keyboard input?

My project is to make a program that you can run while you are playing games or other programs in the background.
When you press a certain key, your notepad should open and also close after you press the same key again.
I have managed to open notepad with subprocess and that works fine but I have no idea to make it open only when a certain key is pressed.
Thanks for any help!
EDIT:
What I tried already:
import subprocess
import keyboard
if keyboard.is_pressed('k'):
subprocess.Popen('C:\\Windows\\System32\\notepad.exe')
input()
here it just doesn't detect any keyboard input, the input() at the end makes the program not close instantly
import subprocess
import keyboard
keyboard.add_hotkey('ctrl+k', print,args=("hello", "test"))
input()
Here if I press "ctrl+k it" will print hello test that means the hotkey works fine. When I switch this part "print,args=("hello", "test")" to "subprocess.Popen('C:\Windows\System32\notepad.exe')"(it should open the program instead of printing hello test) the notepad opens instantly after I run the program and when I press "ctrl+k" I get a big error.
A more complex, but still working example could be the following. With this code your program will be always listening the keyboard, not only when you are focused on the input, so may be mre practical in your case
from pynput import keyboard
import subprocess
import threading
class MyException(Exception): pass
class Listening:
"""Is allways waiting for the keyboard input"""
def __init__(self):
self.notepad_open = False # to know the state
with keyboard.Listener(
on_press=self.on_press) as listener:
try:
listener.join()
except:
pass
def on_press(self, key):
try:
if key.char == "k":
if not self.notepad_open:
self.subprocess = \
subprocess.Popen('C:\\Windows\\System32\\notepad.exe')
self.notepad_open = True # update state
else:
self.subprocess.kill()
self.notepad_open = False # update state
except: # special key was pressed
pass
thread = threading.Thread(target=lambda: Listening())
thread.start()
The problem is that you check for the key 'k' only once at the beginning. If you want the program to correctly work then you should try this:
import time
import subprocess
import keyboard
while True:
if keyboard.is_pressed('k'):
subprocess.Popen('C:\\Windows\\System32\\notepad.exe')
time.sleep(5)
-I used the time so that you can only open the program once 5 seconds(If you're curious, see what happens without it)-

How to open command prompt in Administrator mode in python?

I'm a bit of a noob, so sorry in advance if I'm not doing this right.
I'm using python 3.6x
What I have so far that gets the command window open is
import os
os.open("start cmd")
but this comes up in the directory that I'm working from and not in administration mode.
I've also tried
import os
os.system("start /wait cmd /wait {tskill dwm}")
but that didn't work either. (tskill dwm is what I'm trying to get python to write in to command manager to fix a bug with windows' buttons not going away)
My overall goal is to just click this python script Blah.py and have it restart the windows viewer or whatever it's called. Doing this clears the stuck buttons. Overall this is just an exercise in practicing python. I know I could just disable the button fade out and that would take care of the issue. I just figured this would be a good learning opportunity.
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()
keyboard.press(Key.cmd)
keyboard.release(Key.cmd)
time.sleep(0.3)
keyboard.type("cmd")
time.sleep(1)
keyboard.press(Key.right)
keyboard.release(Key.right)
keyboard.press(Key.down)
keyboard.release(Key.down)
keyboard.press(Key.enter)
keyboard.release(Key.enter)
time.sleep(0.5)
keyboard.press(Key.tab)
keyboard.release(Key.tab)
keyboard.press(Key.tab)
keyboard.release(Key.tab)
keyboard.press(Key.enter)
keyboard.release(Key.enter)
exit
The answer is here
https://stackoverflow.com/a/11746382/7352806
import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'
if sys.argv[-1] != ASADMIN:
script = os.path.abspath(sys.argv[0])
params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
sys.exit(0)

How to return to command line from script running in the background

I have this panic button, and a script that responds to the button press.
if I send the process to the background, using the command $sudo python3 ./Panicbutton.py & I get the command line back. when I press the panic button, the script responds, and prints the message corresponding to the number of times the button was pressed. What I want it to do is go back to the background, whilst it waits for more button presses. pressing ctrl+c returns me to the command line, but I don’t want to need to press ctrl+c each time after the button is pressed. is there a way to return the script to the background while it awaits further key presses? How can I send the ctrl+c command to the terminal from the script? I don't want to terminate the process, I just want the command line prompt to return after the message is printed.
I am using Linux, and python3.4. Please assist.
heres the script:
# USB Panic Button interface code
# Copyright 2010 Ken Shirriff
# http://arcfn.com
import usb.core
x = 0
comment0 = """ PanicButton - interface to USB Panic Button This code requires PyUSB."""
class PanicButton:
def __init__(self):
# Device is: ID 1130:0202 Tenx Technology, Inc.
self.dev = usb.core.find(idVendor=0x1130, idProduct=0x0202)
if not self.dev:
raise ValueError("Panic Button not found")
try:
self.dev.detach_kernel_driver(0) # Get rid of hidraw
except Exception as e:
pass # already unregistered
def read(self):
comment1 = """ Read the USB port. Return 1 if pressed and released, 0 otherwise."""
#Magic numbers are from http://search.cpan.org/~bkendi/Device-USB-PanicButton-0.04/lib/Device/USB/PanicButton.pm
return self.dev.ctrl_transfer(bmRequestType=0xA1, bRequest=1, wValue=0x300, data_or_wLength=8, timeout=500)[0]
if __name__ == "__main__":
import time
button = PanicButton()
while 1:
if button.read():
global x
x = x + 1
if x < 5:
print(x)
elif x == 5:
print("Baby just screem if you want some more!")
elif x == 6:
print("Like AH!")
elif x == 7:
print("push it, push it.")
elif x == 8:
print("watch me work it.")
elif x == 9:
print("I'm PERFECT")
else:
x = 0
print("")
time.sleep(.5)
The script is always in the background, and does not go to the foreground at any point. It just looks that way because the script's output has the purely cosmetic effect of appearing to mess up the prompt.
Instead of pressing Ctrl-C, you can just write ls and press enter. You'll see that the shell works just fine and that your script is not in the foreground.
Bash can't really redraw the prompt because it doesn't control which other programs write to the screen. Consider finding a less invasive way of reporting button presses such as:
printing a bel character to make the terminal play a sound
changing the xterm's title
using tmux or screen to have a window or status bar message
using xmessage or similar to pop up a dialog box
having your bash prompt include messages from the script every time it redraws

Categories

Resources