首页 > 解决方案 > 在python中通过控制台输入数据

问题描述

我想在python中输入数据,但是在输入数据时,右侧必须输出例如,公斤:

简单的代码:

weight = float(input('Enter your weight: (kg)'))

输出:

Enter your weight: some_number (kg) 

我希望在输入数据时 kg 始终位于数字的右侧。我认为问题很清楚,如果有什么不明白的请告诉我。提前谢谢你!

标签: python

解决方案


如果你四处挖掘,你会发现名为getch. 这使用来自py-getch 的代码:

import sys

try:
    from msvcrt import getch
except ImportError:
    def getch():
        import tty
        import termios
        fd = sys.stdin.fileno()
        old = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            return sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old)

ascii_numbers = [ord('0') + x for x in range(10)]
weight = 0.0
while True:
    message = f"Enter your weight: {weight:9.2f} (kg)"
    sys.stdout.write("\r" + message)
    sys.stdout.flush()
    c = ord(getch())
    if c == 13:
        break
    elif c in ascii_numbers:
        c = c - ord('0')
        weight = (weight * 10) + (float(c) / 100)
    elif c == 127:
        weight = weight / 10
print("")

这很丑陋,但我上次的经历ncurses更丑陋。

警告

该程序忽略调用Ctrl-C内部getch。可以修改此代码,以便停止程序的唯一方法是终止进程。对不起。


推荐阅读