使用字符串格式设置python的列

2024-06-09 05:11:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在bash中用如下列复制ls函数: enter image description here

我尝试了.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)

我得到这个输出:

enter image description here


Tags: informatlenifoslinewidthmax
2条回答

因此,结果是任意字符串列表的列输出是由the Linux column command完成的。一种选择是假设您的系统上存在此命令(它存在于我的环境中),并将其用作进程外输出过滤器

另一个选择是深入挖掘columns的源代码,并在Python中重新实现它,可能作为生成器函数。我找到了一个指针in GitHub。注意,这是超过800行的C代码

您还可以为该C代码的核心功能创建Python绑定,这将生成性能更好的代码。遗憾的是,我没有将C代码集成到Python中的经验

如果您决定选择第二种选择,您可以在这里发布您的实现作为答案

我改进了我的算法,现在当终端大小固定时,它可以正常工作

color = {
    "red": "\033[31m",
    "green": "\033[32m",
    "orange": "\033[33m",
    "purple": "\033[35m",
    "cyan": "\033[36m",
    "yellow": "\033[93m",
}


def show_dirs(path=os.getcwd()):
    print(color["cyan"] + "Files in the current directory")
    filelist = os.listdir(path)
    filelist.sort()

    #index padding
    ind = len(filelist)
    if ind >= 1000:
        ind = 4
    elif ind >= 100:
        ind = 3
    elif ind >= 10:
        ind = 2
    else:
        ind = 1

    scr_width = int(os.get_terminal_size()[0]) #terminal width
    mlen = max(len(word) for word in filelist) + 1 #column width
    cols = scr_width // mlen #possible columns

    if scr_width < mlen:
        mlen = scr_width

    line = ""
    lst = []
    for count, _file in enumerate(filelist, start=1):
        if os.path.isdir(_file):
            _file = _file + os.sep
            st = "[{0:>{ind}}] {1:<{mlen}}".format(
                str(count), _file, mlen=mlen, ind=ind
            )
            if scr_width - ((len(line) - cols * 5) % scr_width) > len(st): # - cols * 5 to compensate the length of color codes
                line = line + color["cyan"] + st
            else:
                lst.append(line)
                line = color["cyan"] + st

        else:
            st = "[{0:>{ind}}] {1:<{mlen}}".format(
                str(count), _file, mlen=mlen, ind=ind
            )
            if scr_width - ((len(line) - cols * 5) % scr_width) > len(st): # - cols * 5 to compensate the length of color codes
                line = line + color["green"] + st
            else:
                lst.append(line)
                line = color["green"] + st
    if lst == []:
        lst.append(line)
    print("\n".join(lst))

输出: enter image description here

相关问题 更多 >