简体   繁体   中英

Replace multple lines in a console in Python without Curses

So I have a script that that sends requests to a website and then displays the status codes for the response packets. Something like:

METHOD | COUNT

  200  | 2 results
  404  | 987 results
  500  | 1 results
  ...

It takes a while to complete, so I've left it running on a box that I ssh into using the Linux tool Screen. The problem with this is screen doesn't work with Python's curses module, since to detach from the screen terminal (so I can log out and leave it running) it requires me to press ctrl+a+d which is captured and then ignored by curses .

I know you can overwrite single lines outputted to the console in Python like this:

    out = "200 | {} results\r".format(num)
    sys.stdout.write(out)
    sys.stdout.flush()

But is there a way to extend that to multiple lines so I can do something more like:

    # Updates approx once a second
    out = ""
    for code, num in STATUS_CODES:
        out += "{} | {}\r\n".format(code, num)

    sys.stdout.write(out)
    sys.stdout.flush()

The answer for me was to clear the entire screen with:

sys.stdout.write("\x1b[2J\x1b[H")

and then rewrite all my data at each update. Note that this is not ideal, since it apparently only works in ANSI supported terminals, and seems kinda hacky. Since my script is just for me though, it suited my purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM