Luciana Pilloni
Luciana Pilloni

Reputation: 31

Python clean output console until specific line

I'm searching a way to delete part of the output generated by script in stdout. We suppose that the output is the following:

line 1: some text...
line 2: other text...
line 3: and so on...

At this point of the script I call os.system("ls") and this generate a list of files in current directory with an amount of output that I'm not able to know in advance. So, the stdout will update as

line 1: some text...
line 2: other text...
line 3: and so on...
line 4: file1
line 5: file 2
...
line n: file n

I would like to clean stdout by line 3 to line n but I don't know how to do it. I've already tried to save cursor position at line 3 using escape \033[s (and then delete line by line using \033[K escape) but this doesn't work (my system doesn't support \033[s). I'm able to return at line 3 using escape \033[<L>;<C>H but I don't understand how to remove text until the end (or remove lines backward until line 3). Someone have an idea how to do it? Any suggestion is appreciated. Thanks

Upvotes: 0

Views: 418

Answers (1)

user2722968
user2722968

Reputation: 16525

Instead of fiddling with the terminal, you could capture stdout from the called process, print the first three lines to your own stdout and then either ignore further output or just kill the process. If it is really just ls you are executing, you may find the glob-module handy.

Upvotes: 1

Related Questions