如何使用Python在shell中对段落进行右对齐



我正在开发一个交互式shell,用户在其中输入一些文本,并以一种看起来像对话的方式获取文本。在最近android和iphone上的短信界面上,你可以看到你写的短信文本向左对齐,收到的短信文本向右对齐。

这是我想要达到的效果,但是在Linux shell中(没有花哨的图形,只有输入和输出流)。

我很清楚format()rjust()方法,但他们需要知道你想要填充值的字符数,我不知道当前shell的宽度。

我不局限于我可以安装或使用的库,我主要针对Linux平台,认为有一些跨平台的东西总是好的。

使用诅咒。

window.getmaxyx()计算端子尺寸

另一个选择:

import os
rows, cols = os.popen('stty size', 'r').read().split()

如前所述,使用诅咒。对于简单的情况,如果您不想使用诅咒,您可以使用COLUMNS环境变量(更多信息在这里)。

如果多行输出需要右对齐,则使用以下组合:

  1. 获取窗口宽度:如何在Python中获取Linux控制台窗口宽度
  2. textwrap.wrap
  3. 使用rjust

类似:

import textwrap
screen_width = <width of screen>
txt = <text to right justify>
# Right-justifies a single line
f = lambda x : x.rjust(screen_width)
# wrap returns a list of strings of max length 'screen_width'
# 'map' then applies 'f' to each to right-justify them.
# 'n'.join() then combines them into a single string with newlines.
print 'n'.join(map(f, textwrap.wrap(txt, screen_width)))

最新更新