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
I'm trying to make a program that takes a command and executes it in the console of any operating system and prints the response in python. For this I'm using subprocess.check_output. The program works fine with the ipconfig command (I'm on windows), and the response gets printed after no time. With the notepad command, it opens notepad and only continues when I close notepad. Is it possible to just continue without notepad being closed?
Code:
import subprocess
def executeCommand(command):
return subprocess.check_output(command).decode('ISO-8859-1')
def cmdCommand(command):
pool = ThreadPool(processes=1)
asynch_result = pool.apply_async(executeCommand, [command])
for i in range(3):
if asynch_result.get() is not None:
return asynch_result.get()
sleep(1)
pool.terminate()
return "No result gotten"
print(cmdCommand("ipconfig"))
print(cmdCommand("notepad"))
I'm currently writing a piece of code to test windows app based on pyautowin.
When of the test is to check if we can minimized the window.
Below is the code:
MyApp.Start_(bittorrentApp)
time.sleep(2)
w_handle = pywinauto.findwindows.find_windows(title=u'Bittorrent Automation Task', class_name='WindowsForms10.Window.8.app.0.2bf8098_r15_ad1')[0]
window = MyApp.window_(handle=w_handle)
window.Click()
window.ClickInput(coords = (300,10))
time.sleep(1)
lStyles = win32api.GetWindowLong(GWL_STYLE);
if( lStyles & WS_MINIMIZE ):
print "minimized"
else:
print "not minimized"
I have imported win32api and I can minimized the window.
By the way
lStyles = win32api.GetWindowLong(GWL_STYLE);
return an error, saying GWL_STYLE is not defined
Any idea ?
pywinauto already has all such functionality.
if window.HasStyle(pywinauto.win32defines.WS_MINIMIZE):
window.Minimize()
That's all in HwndWrapper class. You can see all its attributes when typing window.WrapperObject(). in popup hint. WrapperObject() call is usually hidden for readability, but it's called implicitly anyway.
BTW, GetWindowLong(handle, style) has 2 parameters.
i just started learning blender and its scripting and tried to run its sample code
import bge
def main():
cont = bge.logic.getCurrentController()
own = cont.owner
sens = cont.sensors['mySensor']
actu = cont.actuators['myActuator']
if sens.positive:
cont.activate(actu)
else:
cont.deactivate(actu)
main()
and get the following error:
ImportError: No module named 'bge'
i searched for a solution but couldn't find any.how to solve this problem?
i am using blender 2.65
Running import bge does not work when you press "Run script" or try to issue this command in the terminal. You have to press "P" to activate game engine mode. To run your script, connect a controller to the script.
import 'bge' must be 'blender game', rather than blender rendering
give an 'always' run python scripts in 'game logic editor'
start game
In python when running scripts is there a way to stop the console window from closing after spitting out the traceback?
You can register a top-level exception handler that keeps the application alive when an unhandled exception occurs:
def show_exception_and_exit(exc_type, exc_value, tb):
import traceback
traceback.print_exception(exc_type, exc_value, tb)
raw_input("Press key to exit.")
sys.exit(-1)
import sys
sys.excepthook = show_exception_and_exit
This is especially useful if you have exceptions occuring inside event handlers that are called from C code, which often do not propagate the errors.
If you doing this on a Windows OS, you can prefix the target of your shortcut with:
C:\WINDOWS\system32\cmd.exe /K <command>
This will prevent the window from closing when the command exits.
try:
#do some stuff
1/0 #stuff that generated the exception
except Exception as ex:
print ex
raw_input()
On UNIX systems (Windows has already been covered above...) you can change the interpreter argument to include the -i flag:
#!/usr/bin/python -i
From the man page:
-i
When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command. It does not read the $PYTHONSTARTUP file. This can be useful to inspect global variables or a stack trace when a script raises an exception.
You could have a second script, which imports/runs your main code. This script would catch all exceptions, and print a traceback (then wait for user input before ending)
Assuming your code is structured using the if __name__ == "__main__": main() idiom..
def myfunction():
pass
class Myclass():
pass
def main():
c = Myclass()
myfunction(c)
if __name__ == "__main__":
main()
..and the file is named "myscriptname.py" (obviously that can be changed), the following will work
from myscriptname import main as myscript_main
try:
myscript_main()
except Exception, errormsg:
print "Script errored!"
print "Error message: %s" % errormsg
print "Traceback:"
import traceback
traceback.print_exc()
print "Press return to exit.."
raw_input()
(Note that raw_input() has been replaced by input() in Python 3)
If you don't have a main() function, you would use put the import statement in the try: block:
try:
import myscriptname
except [...]
A better solution, one that requires no extra wrapper-scripts, is to run the script either from IDLE, or the command line..
On Windows, go to Start > Run, enter cmd and enter. Then enter something like..
cd "\Path\To Your\ Script\"
\Python\bin\python.exe myscriptname.py
(If you installed Python into C:\Python\)
On Linux/Mac OS X it's a bit easier, you just run cd /home/your/script/ then python myscriptname.py
The easiest way would be to use IDLE, launch IDLE, open the script and click the run button (F5 or Ctrl+F5 I think). When the script exits, the window will not close automatically, so you can see any errors
Also, as Chris Thornhill suggested, on Windows, you can create a shortcut to your script, and in it's Properties prefix the target with..
C:\WINDOWS\system32\cmd.exe /K [existing command]
From http://www.computerhope.com/cmd.htm:
/K command - Executes the specified command and continues running.
In windows instead of double clicking the py file you can drag it into an already open CMD window, and then hit enter. It stays open after an exception.
Dan
if you are using windows you could do this
import os
#code here
os.system('pause')
Take a look at answer of this question: How to find exit code or reason when atexit callback is called in Python?
You can just copy this ExitHooks class, then customize your own foo function then register it to atexit.
import atexit
import sys, os
class ExitHooks(object):
def __init__(self):
self.exit_code = None
self.exception = None
def hook(self):
self._orig_exit = sys.exit
sys.exit = self.exit
sys.excepthook = self.exc_handler
def exit(self, code=0):
self.exit_code = code
self._orig_exit(code)
def exc_handler(self, exc_type, exc, *args):
self.exception = exc
hooks = ExitHooks()
hooks.hook()
def goodbye():
if not (hooks.exit_code is None and hooks.exception is None):
os.system('pause')
# input("\nPress Enter key to exit.")
atexit.register(goodbye)
Your question is not very clear, but I assume that the python interpreter exits (and therefore the calling console window closes) when an exception happens.
You need to modify your python application to catch the exception and print it without exiting the interpreter. One way to do that is to print "press ENTER to exit" and then read some input from the console window, effectively waiting for the user to press Enter.