本文整理汇总了Python中msvcrt.getch函数的典型用法代码示例。如果您正苦于以下问题:Python getch函数的具体用法?Python getch怎么用?Python getch使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getch函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: anykey
def anykey(message=""):
if message:
print(message)
from msvcrt import getch
# getch returns b'[character]', so we turn it into a string
# and strip out the b' and ' parts
while msvcrt.kbhit():
char = getch()
# some inputs need to be compared using their number, for some reason
if ord(char) == 224:
# aha! an arrow key!
char = ord(getch())
if char == 72:
char = movementButtons[0] # up
elif char == 80:
char = movementButtons[1] # down
elif char == 75:
char = movementButtons[2] # left
elif char == 77:
char = movementButtons[3] # right
elif ord(char) == 3:
char = "q" # KeyboardInterrupt
elif ord(char) == 27:
char = "p" # Esc
elif ord(char) == 8:
char = "\x7F" # backspace
elif ord(char) == 18:
char = "\x12" # ctrl-R
else:
char = str(char)[2:-1]
if char == "q":
quit(True)
return char.lower()
开发者ID:ninedotnine,项目名称:funtimes,代码行数:35,代码来源:funtoolkit.py
示例2: submenu
def submenu(string_name_of_submenu):
print(
"{} (press 1, 2 or ESC):\n\t1. Donor\n\t2. Event\n\tEsc. Back to the Main menu".format(string_name_of_submenu))
action = ord(getch())
while action not in list(ALL_ACTION.values()):
action = ord(getch())
if action == ALL_ACTION['KEY_ONE']:
if not file_is_empty(DONOR_PATH):
loading()
if LIST == string_name_of_submenu:
list_donor()
if SEARCH == string_name_of_submenu:
search_donor()
if MODIFY == string_name_of_submenu:
modofy_donor()
if action == ALL_ACTION['KEY_TWO']:
if not file_is_empty(EVENT_PATH):
loading()
if LIST == string_name_of_submenu:
list_events()
if SEARCH == string_name_of_submenu:
search_event()
if MODIFY == string_name_of_submenu:
modify_event()
if action == ALL_ACTION['KEY_ESC']:
menu()
开发者ID:knapeczadam,项目名称:G_PY_bloodySoftware_T4F,代码行数:26,代码来源:main.py
示例3: getch
def getch():
"""getch() for Windows and Linux.
This won't work unless run from a terminal.
"""
# this must be executed from a terminal
if not is_executed_from_console():
system_exit("libastyle.getch() must be run from the console")
# WINDOWS uses msvcrt
if os.name == "nt":
# clear buffer
while msvcrt.kbhit():
msvcrt.getch()
# read char
ch_in = msvcrt.getch()
# LINUX uses termios and tty
else:
# clear buffer
sys.stdin.flush()
# read char
fd_in = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd_in)
try:
tty.setraw(sys.stdin.fileno())
ch_in = sys.stdin.read(1)
if ch_in == '\x1b': # alt key (27)
ch_in = sys.stdin.read(1)
finally:
termios.tcsetattr(fd_in, termios.TCSADRAIN, old_settings)
# convert to unicode for Python 3
return ch_in.decode('utf-8')
开发者ID:amremam2004,项目名称:astyle,代码行数:30,代码来源:libastyle.py
示例4: __call__
def __call__(self):
msvcrt = self.msvcrt
c = msvcrt.getch()
if c == '\x00' or c == '\xE0': #functions keys
msvcrt.getch()
return c
开发者ID:AshitaPrasad,项目名称:sfepy,代码行数:7,代码来源:getch.py
示例5: load_text
def load_text(file_location, progress_file):
text = np.genfromtxt(file_location,dtype='str')
text_temp = []
start_index = 0
progress_text = []
if progress_file:
progress_text = np.genfromtxt(progress_file,dtype=str)
if len(progress_text) > 0:
index = np.where(text == progress_text[len(progress_text)-1])
start_index = index[0]
print 'start:'+str(start_index)
key = ''
prev_word = []
for word in text[start_index+1:]:
print word
key = msvcrt.getch()
if key == 'k':
progress_text = np.append(progress_text, word)
elif key == 'b':
progress_text = np.append(progress_text, prev_word)
print prev_word + ' added. add:'+ word+'?'
key = msvcrt.getch()
if key == 'k':
progress_text = np.append(progress_text, word)
else:
print '--'
elif key == 'q':
break
else:
print '--'
prev_word = word
np.savetxt('KeptWords.txt',progress_text,delimiter='\n', fmt="%s")
开发者ID:ninehundred1,项目名称:MiscStuff,代码行数:33,代码来源:Quick_Delete_entries.py
示例6: maps
def maps(summ):
count = 0
os.system(clear_fn)
quit = ''
for x in full:
if summ == x['summoner']:
count += 1
print 'Champion: %s' % (x['champion'])
print 'Date: %s - Won: %s - Length: %s' % (x['datetime'], x['won'], x['length'])
try:
print 'Kills: %s - Deaths: %s - Assists: %s - KDR: %.2f' % (x['kills'], x['deaths'], x['assists'], x['kills'] / x['deaths'])
except ZeroDivisionError:
print 'Kills: %s - Deaths: %s - Assists: %s - KDR: 0' % (x['kills'], x['deaths'], x['assists'])
print 'Dealt: Phyiscal: %s - Magical: %s - Total: %s' % (com(x['physicalDamageDealt']), com(x['magicDamageDealt']), com(x['physicalDamageDealt'] + x['magicDamageDealt']))
print 'Received: Phyiscal: %s - Magical: %s - Total: %s' % (com(x['physicalDamageTaken']), com(x['magicDamageTaken']), com(x['physicalDamageTaken'] + x['magicDamageTaken']))
print 'Gold: %s - Healing: %s - CreepScore: %s ' % (com(x['gold']), com(x['healed']), com(x['neutralMinionsKilled'] + x['minions']))
length = getsec(x['length'])
print 'Gold/Min: %s - CS/Min: %.2f\n' % (com((x['gold'] / length) * 60), ((x['neutralMinionsKilled'] + x['minions']) / length) * 60)
if quit == 'q' or quit == 'Q':
break
if count >= 2:
print 'Press a key to view more or Q to quit\n'
quit = msvcrt.getch()
count = 0
os.system(clear_fn)
print '\nPress a Key to continue'
msvcrt.getch()
开发者ID:sjet13,项目名称:lolpact,代码行数:30,代码来源:LoLPaCT.py
示例7: keypress
def keypress(self):
while True:
key = msvcrt.getch()
key1 = ""
if key == u'\xe0'.encode('latin-1'):
key1 = msvcrt.getch()
print "Key:" + key + key1
key = key + key1
if key == u'\xe0M'.encode('latin-1'):
print 'Right'
self.tts.next()
if key == u'\xe0K'.encode('latin-1'):
print 'Left'
self.tts.previous()
if key == 'h':
print 'Hello'
if key == 'e':
self.tts.stopSpeak()
break;
开发者ID:suhas-p-bharadwaj,项目名称:Speech-based-web-browser-for-the-Visually-Impaired,代码行数:25,代码来源:EventHandler.py
示例8: main
def main():
grid = [[0]*4 for i in range(4)]
x, y = random.randrange(4), random.randrange(4)
grid[y][x] = 2 if random.random() < .9 else 4
while True:
print('\n' * H)
print(grid_fmt.format(*[i or '' for r in grid for i in r]))
gridcp = [r[:] for r in grid]
if not (move_up(gridcp) or move_down(gridcp) or
move_left(gridcp) or move_right(gridcp)):
print('Game over!')
break
moved = False
k = msvcrt.getch()
if msvcrt.kbhit():
k += msvcrt.getch()
if k == b'\xe0H':
moved = move_up(grid)
elif k == b'\xe0P':
moved = move_down(grid)
elif k == b'\xe0K':
moved = move_left(grid)
elif k == b'\xe0M':
moved = move_right(grid)
elif k in (b'\x1b', b'q'):
break
if moved:
x, y = random.randrange(4), random.randrange(4)
while grid[y][x]:
x, y = random.randrange(4), random.randrange(4)
grid[y][x] = 2 if random.random() < .9 else 4
开发者ID:rmccampbell,项目名称:PythonProjects,代码行数:31,代码来源:2048.py
示例9: wait
def wait():
try:
import msvcrt
print("Press any key to continue")
msvcrt.getch()
except Exception:
pass
开发者ID:frc2423,项目名称:2008-2012,代码行数:7,代码来源:upload.py
示例10: getkey
def getkey(fullterm=False):
"""Return a key from the current console, in a platform independent way"""
# there's probably a better way to initialize the module without
# relying onto a singleton pattern. To be fixed
global _INIT
if not _INIT:
_INIT = _init_term(fullterm)
if os.name == 'nt':
# w/ py2exe, it seems the importation fails to define the global
# symbol 'msvcrt', to be fixed
import msvcrt
while 1:
z = msvcrt.getch()
if z == '\3':
raise KeyboardInterrupt('Ctrl-C break')
if z == '\0':
msvcrt.getch()
else:
if z == '\r':
return '\n'
return z
elif os.name == 'posix':
c = os.read(sys.stdin.fileno(), 1)
return c
else:
import time
time.sleep(1)
return None
开发者ID:eblot,项目名称:pyftdi,代码行数:28,代码来源:term.py
示例11: exit_script
def exit_script(self, error):
#exit script when an error occured
print error
print 'Configuration script stoped.\n'
print 'Press any key to continue...'
msvcrt.getch()
sys.exit(1)
开发者ID:eaudeweb,项目名称:naaya,代码行数:7,代码来源:ptkinit.py
示例12: main
def main():
print("""Please use the Spacebar to tap,
press any other key to finish or r to restart""")
data = []
msvcrt.getch()
lasttime = time.time()
while True:
if msvcrt.kbhit():
key = ord(msvcrt.getch())
if key == 32:
data.append(time.time() - lasttime)
lasttime = time.time()
elif key == 114:
main()
break
else:
invData = [60 / x for x in data]
for d in invData:
print(d)
break
avg = sum(data) / float(len(data))
os.system('cls')
print("""Please use the Spacebar to tap,
press any other key to finish or r to restart""")
print('Average BPM:', 60 // avg)
开发者ID:hpcchkop,项目名称:schuhlager,代码行数:25,代码来源:bpm.py
示例13: p_opts_screen
def p_opts_screen(self, def_num, min_op, max_op, menu):
enter_not_pressed = True
while enter_not_pressed:
cls()
print()
print()
print()
print(menu[def_num])
key = ord(getch())
if key == 224:
key = ord(getch())
if key == 72: # -UP-
if def_num == min_op:
pass
else:
def_num -= 1
if key == 80: # -DOWN-
if def_num == max_op:
pass
else:
def_num += 1
elif key == 13:
enter_not_pressed = False
return def_num
elif key == 27:
return False
开发者ID:EverettDW,项目名称:roleplay,代码行数:26,代码来源:screen.py
示例14: get_user_command
def get_user_command(self):
"""Get a command from the user.
This method displays a prompt to the user and returns when one of
the command keys is pressed.
"""
self.cmd_line.display_command()
cmd_string = ''
cmd_key = None
self.tab_count = 0
while not cmd_key in ['ENTER_POSIX', 'ENTER_WIN']:
key = getch()
# If a special key, act on it
if key in _COMMAND_KEY:
cmd_key = _COMMAND_KEY[key]
# Windows does things oddly for some keys
if not os.name == 'posix' and cmd_key == 'SPECIAL_WIN':
key = getch()
cmd_key = _WIN_COMMAND_KEY.get(key)
if cmd_key is None:
continue
self._process_command_keys(cmd_key)
cmd_string = self.cmd_line.get_command()
# else add key to command buffer
else:
cmd_string = self.cmd_line.get_command()
self.cmd_line.add(key)
cmd_string = self.cmd_line.get_command()
sys.stdout.flush()
self.position = 0
return cmd_string
开发者ID:akhan786,项目名称:LaunchDevelopment,代码行数:32,代码来源:console.py
示例15: alarm
def alarm(hours, minutes, seconds):
time.sleep(abs(hours * 3600 + minutes * 60 + seconds))
while msvcrt.kbhit():
msvcrt.getch()
while not msvcrt.kbhit():
winsound.Beep(440, 250)
time.sleep(0.25)
开发者ID:bhramoss,项目名称:code,代码行数:7,代码来源:recipe-510390.py
示例16: get_command
def get_command():
"""Uses the msvcrt module to get key codes from buttons pressed to navigate through the game. The arrows,
enter, tab, Page Down, and escape keys are used so far."""
cmd = ""
while 1:
key = ord(getch())
if key == 224:
key = ord(getch())
cmd = arrow_keys.get(key, "")
return cmd
elif key == 13:
putch("\n")
break
elif key == 8:
cmd = cmd[:-1]
putch(chr(8))
putch(" ")
putch(chr(8))
elif key == 27:
cmd = 'q'
return cmd
elif key == 9:
cmd = 'tab'
return cmd
else:
putch(chr(key))
cmd += chr(key)
return cmd
开发者ID:TeddyBerhane,项目名称:PyCharm,代码行数:28,代码来源:Zombie+Raid.py
示例17: get_key
def get_key(timeout=0.0):
"""Non-blocking version of getch"""
if timeout < 0:
# Revert to blocking version
return getch()
char = None
if os.name == 'nt':
import msvcrt
start = time.time()
while True:
if msvcrt.kbhit():
char = msvcrt.getch()
if char in b'\x00\xe0':
# special key, two bytes
char += msvcrt.getch()
break
if time.time() > (start + timeout):
break
else:
# poll at most every 50 ms
time.sleep(0.05)
elif os.name == 'posix':
from select import select
rlist, wlist, xlist = select([sys.stdin], [], [], timeout)
if sys.stdin in rlist:
char = sys.stdin.read()
return char
开发者ID:Kopachris,项目名称:py-id003,代码行数:31,代码来源:termutils.py
示例18: get_char
def get_char(self):
ch = msvcrt.getch()
if len(ch) == 1:
if ch in string.printable:
return ch
elif ch == '\x08':
self.delchar()
elif ch == '\xe0':
ch = msvcrt.getch()
if ch == self.CODE_LEFT:
if self.cursor > 0:
self.print_text(self.MOVE_LEFT)
self.cursor -= 1
elif ch == self.MOVE_RIGHT:
if self.cursor < len(self.line):
pad = len(self.line) - self.cursor
self.print_text(self.line[self.cursor:] + (pad - 1) * self.MOVE_LEFT)
self.cursor += 1
elif ch == self.MOVE_UP:
self.clear_line()
cmd = self.history.getnext()
if cmd:
self.insert_text(cmd)
elif ch == self.MOVE_DOWN:
self.clear_line()
cmd = self.history.getprev()
if cmd:
self.insert_text(cmd)
return None
开发者ID:alepee,项目名称:dff,代码行数:29,代码来源:complete_raw_input.py
示例19: main
def main(channel = 'Z'):
##channel = 'X' # This can be 'X' or 'Y' or 'Z' channels
min_position = -4 # mm
max_position = 12.2 # m
rate = 0.5 # number of points written per second to the stage
density = 2 # number of points across the full scale range
wait = 6 # Wait time before sweeping back in seconds
x_mm_array_f = numpy.linspace(min_position,max_position,density)
x_mm_array_b = numpy.linspace(max_position,min_position,density)
xps = qt.instruments['xps']
while 1:
if (msvcrt.kbhit() and (msvcrt.getch() == 'q')): break
print 'Sweeping %s forward...' % channel
for i in x_mm_array_f:
xps.set('abs_position%s' % channel, i)
time.sleep(1.0/rate)
time.sleep(wait)
if (msvcrt.kbhit() and (msvcrt.getch() == 'q')): break
print 'Sweeping %s backward...' % channel
for i in x_mm_array_b:
xps.set('abs_position%s' % channel, i)
time.sleep(1.0/rate)
time.sleep(wait)
f_string = 'set_abs_position' + channel
# Create function that corresponds to the abs_position set function of
# the correct channel, then call it to reset the voltage to 0.
reset_channel = getattr(xps, f_string)
reset_channel(0.0)
return
开发者ID:berkdiler,项目名称:measurement,代码行数:33,代码来源:xps_back_and_forth.py
示例20: __call__
def __call__(self):
import msvcrt
k=ord(msvcrt.getch())
if k == 0 or k == 224: #Special keys
return 1000+ord(msvcrt.getch()) #return 1000+ 2nd code
else:
return k
开发者ID:willkelleher,项目名称:rokudo,代码行数:7,代码来源:rokudo.py
注:本文中的msvcrt.getch函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论