msvcrt Module equivalent on Ubuntu - python

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

Related

My python script closes as soon as I interact with it

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()

How can I allow python users with a version lower than python2.7 to run my program that uses `sysconfig`?

I made a python program which uses the sysconfig module. How can I allow python users with a python version lower than python2.7 to also run that program? I can not find this library in PyPI.
Before I had also used argparse and this was also not installed by default in python versions lower than python2.7. But I could just add it in my requirements file because it can be downloaded using pip.
You'll need to write a version of your code that works without sysconfig - your code would look something like this:
try:
import sysconfig
HAS_SYSCONFIG = True
except ImportError:
HAS_SYSCONFIG = False
...
if HAS_SYSCONFIG:
# sysconfig code here
else:
# compatibility code here
You could also try backporting sysconfig to an earlier version of python and including it with your script, but that may be more work than it's worth.

Simulating keystrokes in python using pywin32

I am looking to simulate keystrokes in python 3.2 in windows 7 to be sent to a GUI.I have python win32 module installed on my pc.The order is alt+t+r+name+enter.What would be the best way of sending these keystrokes to the active window?any sample code would be of a great help.
Thanking you.
(I have seen some module called sendkeys but can that be used with pywin32?i am not allowed to install any other modules)
I know this may not be perfect. We have a testing application using python 2.7. We leverage the windows scripting host to send keys. I have not had time to port anything over to python 3, but this might get you in the right direction. It should be pretty similar.
import win32api
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.Run("app")
win32api.Sleep(100)
shell.AppActivate("myApp")
win32api.Sleep(100)
shell.SendKeys("%")
win32api.Sleep(500)
shell.SendKeys("t")
win32api.Sleep(500)
shell.SendKeys("r")
win32api.Sleep(500)
shell.SendKeys("name")
win32api.Sleep(500)
shell.SendKeys("{ENTER}")
win32api.Sleep(2500)
Here is a list of the send key commands for Windows Scripting Host.
Update
This uses pywin32. It is installed by default in the ActiveState version of python (which is the one I am using). I am not sure, but I do not believe, that it is installed by default in the plain vanilla version of python.

Python REPL tab completion on MacOS

Before upgrading to lion, I had tab complete working in a python shell via terminal. Following these instructions, it was possible to have tab complete working.
Since upgrading to Lion, I am now unable to get tab complete working in a terminal session of Python. I've followed the above instructions to the letter, and it still does not work.
Is there a difference with the readline module in Lion? Hooking in to the 'tab:complete' option no longer seems to work. I'm wondering if it is terminal that is ignoring readline, or if it is python itself.
Python version: 2.7.1
Edit:
By tab complete, I mean I could do something like the following:
# django
import MyModel
MyModel.objects.a[TAB] # will complete to all()
Apple does not ship GNU readline with OS X. It does ship BSD libedit which includes a readline compatibility interface. The system Pythons shipped by Apple and the 64-bit/32-bit Pythons from python.org installers are built with libedit. The problem is that the commands supported by libedit are completely different from those of readline (see for example the discussion here). The traditional 32-bit-only python.org installers do use GNU readline as do some other 3rd-party distributors of Python for OS X, like MacPorts. Chances are that you were previously using such a Python and not a recent Apple one. You do have a few options, besides modifying Django: you can install the third-party replacement readline module; or you can use another Python that comes with GNU readline. However, you should not use the python.org 32-bit-only Pythons on 10.7 because, unfortunately, Xcode 4 on 10.7 no longer includes gcc-4.0 and the OS X 10.4u SDK which those Pythons need to build and install packages with C extension modules.
Putting the following in the python startup file will enable tab completion for both the libedit interface and the typical readline module. For more information on the python startup file, see here
import readline
import rlcompleter
if 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
As it uses libedit/editline, the syntax to enable autocompletion is a little bit different.
You can first force emacs bindings (as it is with readline if I'm not wrong) by typing :
readline.parse_and_bind("bind -e")
Then you can add autocompletion linked to your TAB button (man editrc) :
readline.parse_and_bind("bind '\t' rl_complete")
And if you want to support indenting and has a history (found on internet), it should look like that (unless I made a mistake) :
import readline,rlcompleter
### Indenting
class TabCompleter(rlcompleter.Completer):
"""Completer that supports indenting"""
def complete(self, text, state):
if not text:
return (' ', None)[state]
else:
return rlcompleter.Completer.complete(self, text, state)
readline.set_completer(TabCompleter().complete)
### Add autocompletion
if 'libedit' in readline.__doc__:
readline.parse_and_bind("bind -e")
readline.parse_and_bind("bind '\t' rl_complete")
else:
readline.parse_and_bind("tab: complete")
### Add history
import os
histfile = os.path.join(os.environ["HOME"], ".pyhist")
try:
readline.read_history_file(histfile)
except IOError:
pass
import atexit
atexit.register(readline.write_history_file, histfile)
del histfile

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