My python script closes as soon as I interact with it - python

When I launch the script and press the "]" the script closes. And I know that it works because I tried it in IDLE and it works fine and the music is playing as intended.
import keyboard
from playsound import playsound
while True:
if keyboard.is_pressed(']'):
sound = playsound(r'C:\Users\jaros\Downloads\DoomMusic.mp3')
I tried using "time.sleep()" and "Input()" but nothing worked. The script just keeps closing whenever I press the "]" key.

Solution
To use the "keyboard" package properly, do it like this:
import keyboard
from playsound import playsound
while True:
keyboard.wait("]")
playsound(r"C:\Users\jaros\Downloads\DoomMusic.mp3")
Rationale
Both of the packages you reference (keyboard and playsound) seem to be third-party and not part of the standard library.
Playsound Is Old
Please be advised that the playsound package seems old and broken; the release on PyPI is from March 2020 and needs to be updated by the package maintainers. Pip version 22.3.1 prints a deprecation warning on installation:
DEPRECATION: playsound is being installed using the legacy 'setup.py install' method, because it does not have a 'pyproject.toml' and the 'wheel' package is not installed. pip 23.1 will enforce this behaviour change. A possible replacement is to enable the '--use-pep517' option. Discussion can be found at https://github.com/pypa/pip/issues/8559
The "playsound" module seems also seems to be broken on Windows, but working on macOS. On Windows 10 I am not able to make it work. I get horrible error messages of the type:
>>> playsound(r"C:\Users\traal\Downloads\Garry Schyman - Praan.mp3")
Error 277 for command:
open "C:\Users\traal\AppData\Local\Temp\PS0vt8vkrq.mp3"
A problem occurred in initializing MCI.
The source code for playsound states that it was tested on Windows 7 and Python 2.7 -- these are super old versions.
I would recommend looking for a different package than playsound, unless the package maintainers release an updated version soon.
Proper Use of the Keyboard Package
I googled the keyboard package, and it seems that the way you're using it is an anti-pattern. According to the documentation:
import keyboard
# Don't do this!
#
#while True:
# if keyboard.is_pressed('space'):
# print('space was pressed!')
#
# This will use 100% of your CPU and print the message many times.
# Do this instead
while True:
keyboard.wait('space')
print('space was pressed! Waiting on it again...')
# or this
keyboard.add_hotkey('space', lambda: print('space was pressed!'))
keyboard.wait()

Related

Python 3 Pyperclip Installed but Module not Found

I'm trying to copy some text to clipboad in my python program, so I've installed pyperclip via pip command via Windows command line interface, it says everything is successfully installed, not a problem. However, when I import the thing into my project, I get
from tkinter import *
from tkinter import ttk
import pyperclip
import binascii
#my code...
...
ModuleNotFoundError: No module named 'pyperclip'
So I was like *** that, maybe it's broken, I found a little library that does exactly the same, called "clipboard". Exactly the same installation procedure - from the command line. Same successful installation. Same ModuleNotFoundError. So clearly something wrong on my side, but I have no idea what it is, no idea where to look and what to do. I just want to be able to copy some text to clipboard. Multiplatform. That's it.
It's Python 3.8, Windows 10
pyperclip-1.8.0
pip-20.2.2
If I need to show you some logs or tell you something about my installation, please tell me what exactly to do and where to find information you may need. I'm good with instructions, but I don't have much (any) experience rummaging through logs and python installation folders.
Similar posts have slightly different problems, I didn't find any clear solution or hints that I could understand. No reply seemed like a solution to me.
Anyway, I would really appreciate any help from the community. Being unable to simply copy something to clipboard is killing me, especially since it's the only thing I can't implement. And it's just one function for one button to copy one short piece of text. It's like being stuck at 99% loading, when everything is done, and you just can't write the final line of code, haha.
Pycharm uses a virtualenv for pycharm projects. Navigate through:
Pycharm >> File >> Settings(or press Ctrl+Alt+S on win) >> Project:Name >> Project Interpreter >> Click on the plus(+) symbol above the scroll bar and type in pyperclip and press install package.
And this will install pyperclip for your Pycharm IDE. Since pycharm uses a virtual env for its projects you can change it in the project interpreter section as well, and then the pyperclip you installed from the cmd using pip, will be available to be used on that global version of python(now used by your Pycharm too).
If you still have any errors or doubts, do let me know :D
Cheers

RuntimeError: No recommended backend was available. (Keyring w/ Python)

I have a program which uses Yagmail and the keyring package to safley store email credentials. When I run this script in atom.io and idle it works.
However, after I packaged it with pyinstaller it is giving me this message:
RuntimeError: No recommended backend was available. Install a recommended 3rd party backend package; or, install the keyrings.alt package if you want to use the non-recommended backends. See https://pypi.org/project/keyring for details.
In my program I have
import keyring
I also have gone and installed keyring.alt
Since i cant add comments, i am adding my inputs in answer block. hope this helps.
I also had similar issue, where i used a keyring module to store passwordin my python script and packaged it using pyinstaller. My script ran perfect when i run it directly. But when i try to run the python exe , i got same error as below
"RuntimeError: No recommended backend was available. Install a recommended 3rd party backend package; or, install the keyrings.alt package if you want to use the non-recommended backends. See https://pypi.org/project/keyring for details."
I googled about this error and found below link (this may not be directly related but there someone gave a workaround). I added the workaround as suggested in the link (you have get which keyring backend you are using as well) and it worked.
Link: https://github.com/jaraco/keyring/issues/359
Code to find which keyring backend you are using
from keyring import get_keyring
get_keyring()
As suggested in the above like you can add the block somewhere in your script and then exe file will run perfectly.
Here's what I did, based on #Rena76's answer:
To get the default 'method' used to store the password, I imported get_keyring from keyring and executed the said function.
from keyring import get_keyring
print("Keyring method: " + str(get_keyring()))
The retrieved method was 'keyring.backends.chainer.ChainerBackend', which works fine on the script but not when exported to an .exe file. So I set 'keyring.backends.Windows.WinVaultKeyring' as my method, given that I'm using Windows.
keyring.core.set_keyring(keyring.core.load_keyring('keyring.backends.Windows.WinVaultKeyring'))
Finally, so that I'm able to save the credentials on Windows Vault, I'll import win32 libraries.
import win32api, win32, win32timezone
Now I can successfully perform Keyring functions, such as:
keyring.set_password(service_name='<service>', username='<username>', password='<password>')

msvcrt Module equivalent on Ubuntu

With python on windows, I have been making a game. However, this game requires the msvcrt module, which is only available on windows. I need the function msvcrt.getch(). If I was to make it possible to run this game on Ubuntu, or any linux computer in general, what module, if any, would I be able to use? I would be fine with it not working on a linux, but I would really like to find out a way. Again, is there a module, or any tools I can use, to use the msvcrt.getch function on ubuntu?
The library msvcrs is only available on Windows. If you want to use a release for Ubuntu, check getch function.
import getch
This function get the pressed-key in keyboard.
Hope it help!
From the command line, if necessary (as Luan Souza said above):
pip install getch
In your code:
try:
from getch import getch, getche # Linux
except ImportError:
from msvcrt import getch, getche # Windows

ipython up and down arrow strange behaviour

In my installation of ipython I have this strange problem where I cannot reliably move through command history with up and down arrows... a lot of the time it just doesn't work (nothing happens on the key press). Also sometimes writing normal characters at the end of the command just doesn't work.
My system: Mac OSX Lion
I have readline installed...
thank you for the help!
david
Make sure you installed readline before ipython.
sudo pip uninstall ipython
sudo pip install readline ipython
(I know this question is a few months old, but for future reference)
I had to install readline with easy_install readline and that fixed it.
Using pip install readline did not work for me, and ipython gave a warning:
******************************************************************************
libedit detected - readline will not be well behaved, including but not limited to:
* crashes on tab completion
* incorrect history navigation
* corrupting long-lines
* failure to wrap or indent lines properly
It is highly recommended that you install readline, which is easy_installable:
easy_install readline
Note that `pip install readline` generally DOES NOT WORK, because
it installs to site-packages, which come *after* lib-dynload in sys.path,
where readline is located. It must be `easy_install readline`, or to a custom
location on your PYTHONPATH (even --user comes after lib-dyload).
******************************************************************************
Following trouble in iPython and up-&-down arrows to access history, and browsing this post, a simple solution (turn off "Scroll lock") turned out to work for me.
This is an intentional feature of IPython. If you type "abc" and then hit the up arrow, it's going to scroll only through lines that start with "abc". If you hit lift/right while you're scrolling, it triggers the same behavior. The entire contents of the current line are interpreted as your search prefix, any only lines starting with all that will show up on further up/down keypresses.
You can change this behavior in your PYTHONSTARTUP file. I have the following lines:
import readline
# Prevent ctrl-p/ctrl-n/Up/Down from doing prefix searching
readline.parse_and_bind('"\\C-p": previous-history')
readline.parse_and_bind('"\\C-n": next-history')
readline.parse_and_bind('"\\e[A": previous-history')
readline.parse_and_bind('"\\e[B": next-history')
If you're curious, here are the bindings in IPython's source code that we're overriding.
Unrelated, but I also like to to override readline's default ctrl-w:
# Ctrl-W behavior more like Vim
readline.parse_and_bind('"\\C-w": backward-kill-word')

Python Sound ("Bell")

I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use import os and then use a command line speech program to say "Process complete". I much rather it be a simple "bell."
I know that there's a function that can be used in Cocoa apps, NSBeep, but I don't think that has much anything to do with this.
I've also tried
print(\a)
but that didn't work.
I'm using a Mac, if you couldn't tell by my Cocoa comment, so that may help.
Have you tried :
import sys
sys.stdout.write('\a')
sys.stdout.flush()
That works for me here on Mac OS 10.5
Actually, I think your original attempt works also with a little modification:
print('\a')
(You just need the single quotes around the character sequence).
If you have PyObjC (the Python - Objective-C bridge) installed or are running on OS X 10.5's system python (which ships with PyObjC), you can do
from AppKit import NSBeep
NSBeep()
to play the system alert.
I tried the mixer from the pygame module, and it works fine. First install the module:
$ sudo apt-get install python-pygame
Then in the program, write this:
from pygame import mixer
mixer.init() #you must initialize the mixer
alert=mixer.Sound('bell.wav')
alert.play()
With pygame you have a lot of customization options, which you may additionally experiment with.
I had to turn off the "Silence terminal bell" option in my active Terminal Profile in iTerm for print('\a') to work. It seemed to work fine by default in Terminal.
You can also use the Mac module Carbon.Snd to play the system beep:
>>> import Carbon.Snd
>>> Carbon.Snd.SysBeep(1)
>>>
The Carbon modules don't have any documentation, so I had to use help(Carbon.Snd) to see what functions were available. It seems to be a direct interface onto Carbon, so the docs on Apple Developer Connection probably help.
Building on Barry Wark's answer...
NSBeep() from AppKit works fine, but also makes the terminal/app icon in the taskbar jump.
A few extra lines with NSSound() avoids that and gives the opportunity to use another sound:
from AppKit import NSSound
#prepare sound:
sound = NSSound.alloc()
sound.initWithContentsOfFile_byReference_('/System/Library/Sounds/Ping.aiff', True)
#rewind and play whenever you need it:
sound.stop() #rewind
sound.play()
Standard sound files can be found via commandline locate /System/Library/Sounds/*.aiff
The file used by NSBeep() seems to be '/System/Library/Sounds/Funk.aiff'
By the way: there is a module for that. ;-)
Just install via pip:
pip3 install mac_alerts
run your sound:
from mac_alerts import alerts
alerts.play_error() # plays an error sound
Play sound worked for me. Install using pip
pip3 install playsound
To play sound
from playsound import playsound
playsound('beep.wav')
References:
Found the examples here
downloaded beep.wav from here

Categories