Python 命令行下多行刷新(终于解决)

2020-07-16 17:55:17 +08:00
 lswang

前言

之前看到很多软件都能在命令行下多行刷新,可在python 的默认打印中只能支持单行刷新。 网上搜了很多文章都没有解决这个问题。后来看到ANSI ESCAPE CODES`相关的概念,终于看到了曙光。 参考文档 wiki

python 代码示例

注: 在命令行下执行 python 文件才可以

# -*- coding:utf8 -*-
import time,sys
def progressbar():
    print 'Loading...'
    print "[+] start to build...."
    height = 4
    for i in range(0, 100):
        if i > 0:
            sys.stdout.write(u'\u001b[1A')
        time.sleep(0.1)
        width = (i + 1) / 4
        bar = '[' + '#' * width + ' ' * (25 - width) + ']'
        sys.stdout.write(u'\u001b[1000D\u001b[2K' + ' | -> ' + bar + '\n')
        sys.stdout.write(u'\u001b[1000D\u001b[2K' + ' | -> ' + bar)
        sys.stdout.flush()


    sys.stdout.write(u'\u001b[1A')
    sys.stdout.write(u'\u001b[1A')
    sys.stdout.write(u'\u001b[1000D')
    sys.stdout.write(u'\u001b[J')
    sys.stdout.write('[-] Finish build')
    sys.stdout.flush()
    print
progressbar()

3185 次点击
所在节点    程序员
13 条回复
w9ay
2020-07-16 18:14:26 +08:00
谢谢分享,正好需要
xJogger
2020-07-16 18:21:57 +08:00
deorth
2020-07-16 20:33:10 +08:00
妙啊
a719114136
2020-07-16 20:38:15 +08:00
你要的是这个吧 https://www.v2ex.com/t/680258
a719114136
2020-07-16 20:41:52 +08:00
@w9ay
@xJogger
@deorth

有个现成的库可以用 -> https://github.com/gojuukaze/terminal_layout ,图片加载不出来的话可以看 4 楼的链接
Yinz
2020-07-16 20:42:58 +08:00
很久以前也解决过这个问题,做成了一个小库,不过因为工作忙没太维护,windows 会有问题,mac 和 linux 的应该是好的。
https://github.com/Yinzo/reprint
欢迎 PR
nanfangzai
2020-07-16 21:22:47 +08:00
哈哈哈 我也做过这个东西
KentY
2020-07-16 21:59:01 +08:00
好多年前写了一个. 你可以看下:
https://github.com/sk1418/progressbar
用起来就是这样的:
https://github.com/sk1418/zhuaxia#screenshots
Akkuman
2020-07-16 23:41:13 +08:00
哈哈,我也做过这个,这个好像 windows 上面是需要调用特定的 api,和其他的不太一样
CallMeReznov
2020-07-16 23:55:16 +08:00
进度条? 我记得 python 是有个进度条的库的
lswang
2020-07-17 10:41:40 +08:00
@xJogger 你用的 terminal 有问题吧,你的代码我可以运行
xJogger
2020-07-17 11:23:33 +08:00
@lswang 我在 Windows 上用 cmd 运行的,你用的啥呀。
lswang
2020-07-17 13:50:19 +08:00
@xJogger windows 的 cmd 估计是不行,你用 git 的那个 cmd 试试呢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/690665

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX