I am trying to make a simple IRC client in Python (as kind of a project while I learn the language).
I have a loop that I use to receive and parse what the IRC server sends me, but if I use raw_input
to input stuff, it stops the loop dead in its tracks until I input something (obviously).
How can I input something without the loop stopping?
(I don’t think I need to post the code, I just want to input something without the while 1:
loop stopping.)
I’m on Windows.
Advertisement
Answer
For Windows, console only, use the msvcrt
module:
JavaScript
x
12
12
1
import msvcrt
2
3
num = 0
4
done = False
5
while not done:
6
print(num)
7
num += 1
8
9
if msvcrt.kbhit():
10
print "you pressed",msvcrt.getch(),"so now i will quit"
11
done = True
12
For Linux, this article describes the following solution, it requires the termios
module:
JavaScript
1
25
25
1
import sys
2
import select
3
import tty
4
import termios
5
6
def isData():
7
return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])
8
9
old_settings = termios.tcgetattr(sys.stdin)
10
try:
11
tty.setcbreak(sys.stdin.fileno())
12
13
i = 0
14
while 1:
15
print(i)
16
i += 1
17
18
if isData():
19
c = sys.stdin.read(1)
20
if c == 'x1b': # x1b is ESC
21
break
22
23
finally:
24
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
25
For cross platform, or in case you want a GUI as well, you can use Pygame:
JavaScript
1
30
30
1
import pygame
2
from pygame.locals import *
3
4
def display(str):
5
text = font.render(str, True, (255, 255, 255), (159, 182, 205))
6
textRect = text.get_rect()
7
textRect.centerx = screen.get_rect().centerx
8
textRect.centery = screen.get_rect().centery
9
10
screen.blit(text, textRect)
11
pygame.display.update()
12
13
pygame.init()
14
screen = pygame.display.set_mode( (640,480) )
15
pygame.display.set_caption('Python numbers')
16
screen.fill((159, 182, 205))
17
18
font = pygame.font.Font(None, 17)
19
20
num = 0
21
done = False
22
while not done:
23
display( str(num) )
24
num += 1
25
26
pygame.event.pump()
27
keys = pygame.key.get_pressed()
28
if keys[K_ESCAPE]:
29
done = True
30