如何在Python 3中输入文本时不使用input() [英] How to not issue a new line in Python 3 when entering text with input()

查看:1380
本文介绍了如何在Python 3中输入文本时不使用input()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 3 中创建了一个基本实用程序,用户在其中输入命令并将反馈打印到控制台中。当使用 input() sys.stdin.readline()函数输入数据时,这是命令行会话可能看起来像(包括\r和\\\
字符)

I'm making a basic utility in Python 3 where the user inputs a command and gets feedback printed out into the console. When entering data using the input() or sys.stdin.readline() functions this is what the command-line session may look like (including \r and \n characters)

1. What is your name:\n
2. <user input>\n
3. Your name is <variable>.\n

但是,我想在用户命中输入后显示 \r \\\
字符,如第2行所示。在用户键入所有内容并按Enter后,它将显示为

But, I would like to display a \r character after the user hits enter instead of the \n character, as shown on line 2. After the user had typed everything in and hit enter it would look like this

1. What is your name:\n
2. Your name is <variable>.\n


$ b b

(因为第2行在输入的数据后面会有一个 \r 字符,将cursur返回最左边)

(because line 2 would have a \r character after the entered data, returning the cursur back to the far left)

有人知道我可以实现这个方法吗?

Does anybody know of a way I might accomplish this?

推荐答案

我几乎认为 msvcrt 模块仅适用于Windows。

Well, I discovered this method although I am almost cirtain that the msvcrt module is for Windows only.

import msvcrt
import sys

def msgInput(prompt):
    print(prompt, end='')
    data= b''
    while True:
        char= msvcrt.getch()
        if char != b'\r':
            print(char.decode(), end='')
            sys.stdout.flush()
            data= data+char
        else:
            print('\r', end='')
            break
    return data.decode()

如果有人知道任何跨平台方法,请分享。

If anybody knows of any cross-platform methods, please share.

更新 - 很遗憾,此方法有许多限制,例如用户无法使用箭头键导航输入的文本。

Update - Unfortunately this method has many limitations, such as the user cannot navigate the entered text with the arrow keys.

这篇关于如何在Python 3中输入文本时不使用input()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆