如果我理解正確,你要做的是獲得輸入而不回顯換行符。如果您使用的是Windows,則可以使用msvcrt模塊的getwch方法獲取單個字符以便輸入而不打印任何內容(包括換行符),然後打印該字符(如果它不是換行符)。否則,你就需要定義一個殘培功能:
import sys
try:
from msvcrt import getwch as getch
except ImportError:
def getch():
"""Stolen from http://code.activestate.com/recipes/134892/"""
import tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def input_():
"""Print and return input without echoing newline."""
response = ""
while True:
c = getch()
if c == "\b" and len(response) > 0:
# Backspaces don't delete already printed text with getch()
# "\b" is returned by getch() when Backspace key is pressed
response = response[:-1]
sys.stdout.write("\b \b")
elif c not in ["\r", "\b"]:
# Likewise "\r" is returned by the Enter key
response += c
sys.stdout.write(c)
elif c == "\r":
break
sys.stdout.flush()
return response
def print_(*args, sep=" ", end="\n"):
"""Print stuff on the same line."""
for arg in args:
if arg == inp:
input_()
else:
sys.stdout.write(arg)
sys.stdout.write(sep)
sys.stdout.flush()
sys.stdout.write(end)
sys.stdout.flush()
inp = None # Sentinel to check for whether arg is a string or a request for input
print_("I have", inp, "apples and", inp, "pears.")
@jherran請從帖子的''
的去除,因爲他們不需要。 –