python怎么在同一行输入_Python:“打印”和“输入”在一行

如果我理解正确,你要做的是获得输入而不回应换行符.如果您使用的是Windows,则可以使用msvcrt模块的getwch方法获取输入的单个字符而不打印任何内容(包括换行符),然后打印字符(如果它不是换行符).否则,您需要定义一个getch函数:

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.")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值