I tried making a text writing program but the text deleting part doesn't seem to work. It should delete the text, but it just replaces the text with my new input. I am new to python so I would appreciate a simple answer. Here is my code:
import os
import msvcrt
lst = []
while True:
userinput = msvcrt.getch()
if userinput == "b'\\x08'": # delete last input
lst.pop()
os.system('cls' if os.name == 'nt' else "printf '\033c'")
print("".join(lst))
elif userinput == "b'\\r'": # enter key
lst.append("\n")
else:
lst.append(userinput.decode("ASCII")) #normal text
os.system('cls' if os.name == 'nt' else "printf '\033c'")
print("".join(lst))
When I input "Hello" it prints:
>Hello
then press Backspace, I expect:
>Hell
but it just stays
>Hello
And when I press a button after that, e.g. "f" then it prints out:
>Hellf
you're comparing against the serialized representation of the bytes. It will never match.
Instead:
if userinput == b'\b': # delete last input
and:
elif userinput == b'\r': # enter key
\b is the same as \x08, but more readable
Related
I've tried every solution that I found on google so far and nothing seems to work...
client_input = ""
def listen_for_input(): # reads the input and adds to string returns
whether pressed enter
while msvcrt.kbhit(): # there is input waiting to be read
key = str(msvcrt.getch())
if key == b'\r' or b'\n': # pressed enter
return True
else:
global client_input
client_input += key.decode("utf-8") # Add encoded char to
string
return False
After the else statement catches invalid input and advises the user of this any input after this is caught as invalid input even when the input should be valid. Also, I'm very new to Python so any suggestions on the rest of the code would be appreciated. Below is the code I have written:
from __future__ import division #Allows for division to return a float value
from colorama import init,Fore,Style,Back #Allows for formating color and stylizing text output to terminal screen
init(convert=True) #Allows Colorama to work on Windows 10 machine
import os
running=True
def printAnswer(sign,userInput1,userInput2,answer):
"Prints the formated answer to the screen"
print
print Fore.RED, Style.BRIGHT,userInput1, sign, userInput2, "=", answer, "\n" #Changes text to red
print Style.RESET_ALL #Changes text back to normal from Red
try:
input= raw_input("Press any key to continue")
except NameError:
pass
def printAnswerRemainder(sign,userInput1,userInput2,answerInt,remainder):
"Prints the formated division answer with remainder"
print Fore.Red, Style.BRIGHT, "\n", userInput2, sign, userInput1, "=", answerInt," Remainder ", remainder, "\n" #Changes text color to red
print Style.RESET_All #Resets text color back to normal
def newAdd(userInput1,userInput2):
"Performs the addition function"
sign="+"
answer=userInput1+userInput2
printAnswer(sign,userInput1,userInput2,answer)
def newSub(userInput1,userInput2):
"Performs the Subtraction function"
sign="-"
answer=userInput1-userInput2
printAnswer(sign,userInput1,userInput2,answer)
def newDivision(userInput1, userInput2):
"Performs divsion function giving a decimal answer and an answer with the remainder"
sign="/"
answer=userInput2/userInput1
answerInt=userInput2//userInput1
remainder=userInput2%userInput1
printAnswerRemainder(sign,userInput1,userInput2,answerInt,remainder)
printAnswer(sign, userInput2, userInput1, answer)
def newMult(userInput1,userInput2):
sign="X"
answer=userInput1*userInput2
printAnswer(sign,userInput1,userInput2,answer)
while running==True:
os.system('cls' if os.name == 'nt' else 'clear') #Clears the terminal of previous activity
userSelect=raw_input("Please enter the number of the type of operation you would like to complete:\n\t 1.Addition\n\t 2.Subtraction\n\t 3.Division\n\t 4.Multiplication\n\t 5.Exit\n\n-------> ")
if userSelect=="1":
addNum1=input("Enter the first number to add:\n")
addNum2=input("Enter the second nummebr to add:\n")
newAdd(addNum1,addNum2)
elif userSelect=="2":
subNum1=input("Enter the number to subtract from: \n")
subNum2=input("Enter the number you would like to subtract: \n")
newSub(subNum1,subNum2)
elif userSelect=="3":
divNum1=input("Enter the dividend: \n")
divNum2=input("Enter the divisor: \n")
newDivision(divNum2,divNum1)
elif userSelect=="4":
multNum1=input("Enter the number that is being multiplied: \n")
multNum2=input("Enter the number to be multiplied by: \n")
newMult(multNum1,multNum2)
elif userSelect=="5":
running=False
**else:
print "The command was invalid"
try:
input= raw_input("Press any key to continue")
except NameError:
pass**
In this else clause, you are overwriting the build-in function input:
try:
input= raw_input("Press any key to continue")
Instead, this should work fine:
try:
anykey = raw_input("Press any key to continue")
I have created a Python script that can take commands from a pipe (named pipe1). You can find the Script on Pastebin.
I tested the script with this other script:
import sys
fw = open("pipe1", "w" )
fw.write('fd\n')
fw.close()
and it worked.
Now I want to control the script with another Python script, that could write in the pipe if I press w, a, s, d or p and display me the keys, that i press.
In this example I just want to print the keys that I press. I would later add the fw.write commands to write in the pipe, which I tested before:
def key_inp(event):
print 'Key:', event.char
key_press = event.char
sleep_time = 0.030
while True:
try:
if key_press.lower() == 'w':
print "w"
elif key_press.lower() == 's':
print "s"
elif key_press.lower() == 'a':
print "a"
elif key_press.lower() == 'd':
print "d"
elif key_press.lower() == 'q':
print "q"
elif key_press.lower() == 'e':
print "e"
elif key_press.lower() == 'p':
print "stop"
except(KeyboardInterrupt):
print('Finished')
My problem is, that the script that i wrote (and improved with a stackoverflow member) closes immediately when i open it.
Can anyone explain me why, and how i can fix it so that the script stays open the whole time until i interrupt it with Ctrl+c?
EDIT: This answer relies on installing the readchar module. You can install it via pip: pip install readchar.
The code you are trying to use has no functionality: you only define a function, but never call upon it. On top of that, it contains indentation errors.
Something along the lines of what you are trying to achieve, but with a dot as finish key:
import readchar
while True:
key = readchar.readkey()
key = key.lower()
if key in ('wsadqe'):
print 'Key:', key
elif key == 'p':
print "stop"
sleep_time = 0.030
if key == '.':
print "finished"
break
My code is below:
import msvcrt
while True:
if msvcrt.getch() == 'q':
print "Q was pressed"
elif msvcrt.getch() == 'x':
sys.exit()
else:
print "Key Pressed:" + str(msvcrt.getch()
This code is based on this question; I was using it to acquaint myself with getch.
I've noticed that it takes 3 pressing the key 3 times to output the text once. Why is this? I'm trying to use it as an event loop, and that's too much of a lag...
Even if I type 3 different keys, it only outputs the 3rd keypress.
How can I force it to go faster? Is there a better way to achieve what I'm trying to achieve?
Thanks!
evamvid
you call the function 3 times in your loop. try calling it only once like this:
import msvcrt
while True:
pressedKey = msvcrt.getch()
if pressedKey == 'q':
print "Q was pressed"
elif pressedKey == 'x':
sys.exit()
else:
print "Key Pressed:" + str(pressedKey)
You can optimize things a little bit by also using themsvcrt.kbhit function which will allow you callmsvcrt.getch()only as much as is necessary:
while True:
if msvcrt.kbhit():
ch = msvcrt.getch()
if ch in '\x00\xe0': # arrow or function key prefix?
ch = msvcrt.getch() # second call returns the scan code
if ch == 'q':
print "Q was pressed"
elif ch == 'x':
sys.exit()
else:
print "Key Pressed:", ch
Note that theKey Pressedvalue printed won't make sense for things like function keys. That's because it those cases it's really the Windows scan code for the key, not a regular key code for the character.
So I've been doing a little bit of reading up on how to exit a while loop by the user pressing the enter key and I've come up with the following:
import sys, select, os
switch = 1
i = 1
while switch == 1:
os.system('cls' if os.name == 'nt' else 'clear')
print "I'm doing stuff. Press Enter to stop me!"
print i
while sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
line = raw_input()
if not line:
print "Finished! =]"
switch = 0
else:
print "Finished! =]"
switch = 0
i = i+1
Is there a way to tidy this up? In particular the "if not line" and the following "else" look messy. Can they be combined into one? A better alternative to using "switch"?
Initially if I typed a bunch of characters and then hit enter it didn't stop the loop. I would have to press enter again. The if not and else components are intended to set it up such that it would exit on the first press of enter.
This worked for me:
import sys, select, os
i = 0
while True:
os.system('cls' if os.name == 'nt' else 'clear')
print "I'm doing stuff. Press Enter to stop me!"
print i
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
line = raw_input()
break
i += 1
You only need to check for the stdin being input once (since the first input will terminate the loop). If the conditions line/not line have result for you, you can combine them to one if statement. Then, with only one while statement being used, you can now use break instead of setting a flag.