python - 在python中通过控制台输入数据
问题描述
我想在python中输入数据,但是在输入数据时,右侧必须输出例如,公斤:
简单的代码:
weight = float(input('Enter your weight: (kg)'))
输出:
Enter your weight: some_number (kg)
我希望在输入数据时 kg 始终位于数字的右侧。我认为问题很清楚,如果有什么不明白的请告诉我。提前谢谢你!
解决方案
如果你四处挖掘,你会发现名为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
。可以修改此代码,以便停止程序的唯一方法是终止进程。对不起。
推荐阅读
- url - JsonObjectRequest 请求从 url 获取数据在虚拟而非物理电话上工作
- javascript - 从绘图管理器中删除折线工具
- android - Sygic Maps Android:我无法更新我的自定义位置
- python - E: 包'python-pip'没有安装候选错误
- java - 从 2 个指定标签之间的 ArrayList 中删除字符串
- python - cdlib python包安装时出错
- php - 获取 Woocomerce 中的最后一个订阅续订订单并在 URL 中运行此数据
- python - 如何从数据类中动态删除字段?
- drop-down-menu - Plotly Dash Heatmap 未通过下拉选择更新
- latex - LaTeX - 使用 3x3 数据 \ DTLforeach 创建矩阵的数据工具