Python program stops right away - python-3.x

So I tried to record they keystrokes of my keyboard, when I use the python IDLE and write it in there, it works, but when i run it in the terminal with python3.8.1 it ends right away. That's the code:
import keyboard
def on_key(key):
print(key)
keyboard.on_press(on_key, suppress=False)

Related

Is there a reset function in the Python console?

Is there a function that can be called from within the Python console that has the exact same effect as doing the following:
Calling
exit()
to exit the console, followed by calling
python
at the command prompt to re-enter a fresh python console.
NB: I am not seeking to just clear or de-clutter the screen, because using CTRL+L accomplishes that quite easily.
If you want to get rid of the variables defined in the session then this should do your job.
import gc
del <variable_name>
gc.collect()

why is pdb on Python 3 ignoring my CTRL+C and just displaying "--KeyboardInterrupt--"

Under pdb in Python 2 I could CTRL-C and quit my Python program.
Under Python 3.6 I doesn't do that, just displays --KeyboardInterrupt-- and ignores me. In order to quit, I need to CTRL-D instead, but that will also terminate my bash session if I "do one too many".
Can I bring back CTRL+C behavior?
Python 3.6, macOS Sierra.
I still consistently have the same behavior. Maybe it’s a glitch in my environment but otherwise I can’t see the benefit of explicitly ignoring a user’s request to terminate a program with CTRL+C.
However, I have found that hitting ‘q’ triggers pdb quit which mostly ends up with the desired result, termination of the program. And, unlike CTRL+D has no risk of closing the launching bash session either.
edit - this did the trick 😀
(I have code that is made to trap exceptions, which is why a simple q/quit was hit or miss)
as per Is there a way to prevent a SystemExit exception raised from sys.exit() from being caught?
🧨 : note its warning about no cleanup code being run
# ~/.pdbrc
alias qq import os; os._exit(1)

Multithreaded Music Playing with Pygame in Terminal

I am attempting to make a text game and add some music to it and maybe sounds too, however, the "Big and Greatest" answer was Pygame. After testing with it, I found that when you use ANY Pygame function, it stops the current terminal session from printing any more output, this stops the game from continuing.
I first tried the usual...
from pygame import *
def some_function():
mixer.load("music.mp3")
mixer.music.play(0)
clock = time.Clock()
clock.tick(10)
while mixer.music.get_busy():
clock.tick(10)
Rest_of_function
And of course this does not work because it is a loop and is doing it in order so I next tried...
from file_with_music import * #added threading to this file
def main():
file_with_music.start()
Rest_of_Function
This however did not work as the annoying "Welcome to pygame" popup blocked terminal output again...
SO the next step was to make a new file and...
from Main import *
from Intro_Sounds import *
if __name__ == '__main__':
Intro_Thread.start() #Intro did not start because pygame popup was somehow called
Music_Thread.start()
Even after putting them both in threads, it still did not work...
As a side note, there is a function built into Main that is meant to execute
Music_Thread.join()
Music_Thread.stop()
After certain input is met.
The expected result is for it to play music in the background while the terminal continues printing out input and accepting input up until the input that would kill the Music thread is input. Of course, it did not work, and I am at a loss...
How can music be played without freezing the terminal.
The pygame.mixer sadly doesn't have this capability (as far as I know). Use winsound instead:
import winsound # only on windows tho...
winsound.PlaySound('sound.wav', winsound.SND_ASYNC) # this will play the sound and...
print('I can still print :D') # this can still print :D
After trying a few things I found...
Pygame is not friendly with sound and terminal output, so it won't work.
WxPython no longer has a functional sound module, making it useless.
Other projects are abandoned or OS specific...
However, I found that PyOpenAL actually works, although it can't understand mp3 files or 32bit float wav. Instead of using multithreading I switched to multiprocessing (making a 2000 line script to properly learn how the module works) and now the sound plays (and loops) while allowing terminal output.
TL:DR
PyOpenAL is the winner.
please try as follow--
from pygame import *
def some_function():
pygame.mixer.music.load("music.mp3")
pygame.mixer.music.play(0)
clock = time.Clock()
clock.tick(10)
while pygame.mixer.music.get_busy():
clock.tick(10)
Rest_of_function

Press enter stops computing python

I'm doing some engineering analysis with the help of a FEA program and Python. When the analysis ends I need to press a key to continue. But this is not a normal press any key to continue. Every code executed with the scripts stops. Like a handput debug break. Nothing runs until I press something or switch windows.
I cant use send keys and subprocesses because running code completely stops. Only solution I could come up with is to use another script in another command window with simple send keys command. This extra script is useless if computer is used or another window is active.
I'm a beginner level programmer and maybe I'm missing something simple. I guess the problem is caused by the FEA programs code but I'm not sure. So is there any way to prevent my code from stopping? Thank you for your time.
It seems that the FEA program does the windowing and you cannot do much about it. I actually automate scripting in DIANA FEA. For this program I would try something like pywinauto.
https://github.com/pywinauto/pywinauto
And call your python script from another python script.
from pywinauto import Desktop, Application
import time
app = Application().start("FEA_program.exe my_python_script.py")
while True:
time.sleep(5)
# send key presses to the app every arbitrary seconds

Making Python text green and using Spinning cursor - Newbies questions

I want to make my Python script file,when I "announce" something to the user, to be green like this:
How can this be done?I saw a script using this with sys.stdout.write but I dont understand how to use it, Im using a simple "print" commands..
Also, I would like to have the Spinning cursor spin as long as this command runs and only stops when this command stops(finishes):
print('running network scan')
output = subprocesss.check_output('nmap -sL 192.168.1.0/24',shell=True)
print('Done')
Any way to do that (unknown time until task is done)?
Im using a code suggested by nos here:
Spinning Cursor
So, about getting the terminal color to be green, there is a neat package called colorama that generally works great for me. To check whether the process is running or not, I would recommend using Popen instead of check_output, since the latter does not allow you to communicate with the process as far as I know. But you need to since you want to know if your subprocess is still running. Here is a little code example that should get you running:
import subprocess
import shlex
import time
import sys
import colorama
def spinning_cursor():
"""Spinner taken from http://stackoverflow.com/questions/4995733/how-to-create-a-spinning-command-line-cursor-using-python/4995896#4995896."""
while True:
for cursor in '|/-\\':
yield cursor
# Create spinner
spinner = spinning_cursor()
# Print and change color to green
print(colorama.Fore.GREEN + 'running network scan')
# Define command we want to run
cmd = 'your command goes here'
# Split args for POpen
args=shlex.split(cmd)
# Create subprocess
p = subprocess.Popen(args,stdout=subprocess.PIPE)
# Check if process is still running
while p.poll()==None:
# Print spinner
sys.stdout.write(spinner.next())
sys.stdout.flush()
sys.stdout.write('\b')
print('Done')
# Grab output
output=p.communicate()[0]
# Reset color (otherwise your terminal is green)
print(colorama.Style.RESET_ALL)

Resources