我尝试了.format在文件名中添加填充,但仍然没有得到所需的输出 最后一列每次都会溢出
def show_dirs():
filelist = os.listdir(os.getcwd())
filelist.sort()
scr_width = int(os.popen("stty size", "r").read().split()[1])
max_len = -1
for file_len in filelist:
if len(file_len) > max_len and scr_width > max_len*2:
max_len = len(file_len)
mlen = max_len #+ 1
print(color["cyan"] + "Files in the current directory")
if scr_width < mlen:
mlen = scr_width
line = ""
for count, _file in enumerate(filelist):
if os.path.isdir(_file):
_file = _file + os.sep
st = "[{0:>2}] {1:<{mlen}}".format(str(count + 1), _file, mlen=mlen)
if len(line) % scr_width > len(st):
line = line + color["green"] + st
else:
line = line + "\n" + color["green"] + st
else:
st = "[{0:>2}] {1:<{mlen}}".format(str(count + 1), _file, mlen=mlen)
if len(line) % scr_width > len(st):
line = line + color["cyan"] + st
else:
line = line + "\n" + color["cyan"] + st
print(line)
我得到这个输出:
因此,结果是任意字符串列表的列输出是由the Linux column command完成的。一种选择是假设您的系统上存在此命令(它存在于我的环境中),并将其用作进程外输出过滤器
另一个选择是深入挖掘
columns
的源代码,并在Python中重新实现它,可能作为生成器函数。我找到了一个指针in GitHub。注意,这是超过800行的C代码您还可以为该C代码的核心功能创建Python绑定,这将生成性能更好的代码。遗憾的是,我没有将C代码集成到Python中的经验
如果您决定选择第二种选择,您可以在这里发布您的实现作为答案
我改进了我的算法,现在当终端大小固定时,它可以正常工作
输出:
相关问题 更多 >
编程相关推荐