0

There is something I want to do, but unfortunately I have absolutely no idea on how to do it, and I doubt someone else has asked. So, basically, what I want is the program to output text in an previous area. I'll try to explain.

Let's say I outputted the following text to the screen:

===========================================================================================



===========================================================================================

My question is, is there a way, without using pygame, to replace the blank lines between the lines with a certain text WITHOUT printing the lines again? Is this possible using for example Python IDLE or directly in the terminal, or is it only possible using pygame or something "like" that?

It would look like this, for example:

===========================================================================================

Hello World!

===========================================================================================
teolicht
  • 245
  • 2
  • 6
  • 13
  • While on the same line, you can use carriage return `\r`. Spanning multiple lines, you should have a look at [`curses`](https://docs.python.org/3/howto/curses.html). See e.g. [here](https://stackoverflow.com/a/26584483/1639625) for an example. – tobias_k Jul 31 '17 at 19:05

3 Answers3

3

You can use the curses library for this kind of text-only UI. Here's a simple example, first printing the horizontal lines, and then, after some time, adding a string on a previous line.

import time, curses

scr = curses.initscr()

scr.addstr(0, 0, "#" * 80)
scr.addstr(2, 0, "#" * 80)
scr.refresh()

time.sleep(1)

scr.addstr(1, 35, "Hello World")
scr.refresh()
tobias_k
  • 81,265
  • 12
  • 120
  • 179
2

While there should be multiple libraries to handle this task, you should check out curses and colorama. I'm unsure about curses but this is definitely possible with colorama (install it via pip).

Here's an example:

from colorama import *

def pos(x, y):
    return '\x1b['+str(y)+';'+str(x)+'H'

def display():
    init() #just for safety here; needed in Windows
    print(Fore.RED+pos(30, 10)+ 'This string is a different place!')

display()
Sam Chats
  • 2,271
  • 1
  • 12
  • 34
2

Given your output, say, for example that is in a file test.dat:

===========================================================================================



===========================================================================================

a 1 simple line in vim would produce your desired output:

:3s/^$/Hello World!

If you want to automate this in a script: hello.sh

#!/bin/bash
ex test.dat <<-EOF
  :3s/^$/Hello World!
  wq " Update changes and quit.
EOF

Output:

===========================================================================================

Hello World!

===========================================================================================
DavidC.
  • 669
  • 8
  • 26