How to Rewrite Output in Terminal

How to rewrite output in terminal

Printing a carriage return (\r) without a newline resets the cursor to the beginning of the line, making the next print overwriting what's already printed:

import time
import sys
for i in range(100):
print i,
sys.stdout.flush()
time.sleep(1)
print "\r",

This doesn't clear the line, so if you try to, say, print decreasing numbers using this methods, you'll see leftover text from previous prints. You can work around this by padding out your output with spaces, or using some of the control codes in the other answers.

How to overwrite stdout in C

It's not manipulating stdout -- it's overwriting the characters which have already been displayed by the terminal.

Try this:

#include <stdio.h>
#include <unistd.h>
static char bar[] = "======================================="
"======================================>";
int main() {
int i;
for (i = 77; i >= 0; i--) {
printf("[%s]\r", &bar[i]);
fflush(stdout);
sleep(1);
}
printf("\n");
return 0;
}

That's pretty close to wget's output, right? \r is a carriage-return, which the terminal interprets as "move the cursor back to the start of the current line".

Your shell, if it's bash, uses the GNU Readline library, which provides much more general functionality, including detecting terminal types, history management, programmable key bindings, etc.

One more thing -- when in doubt, the source for your wget, your shell, etc. are all available.

How can I rewrite the terminal output of a program

Yes, sed as a stream editor should be the right tool for the job. Just redirect the output of your application to it:

myapp | sed -e 's/^.* //'

You might encounter problems, though:

  1. If the application writes to a standard error rahter than standard output, you have to redirect the stream with

    myapp 2>&1 | sed -e ...

  2. It is possible that the application would buffer its output if it is not connected to a terminal. Unless there is a specific option to change the behaviour, you are out of luck in this case.

How to rewrite on several terminal lines in Python

It'll depend on the terminal emulator you use, but you probably want the ANSI 'cursor up' codes to be output, which will move the cursor up ready for the next iteration. The code you want is "ESCAPE [ A"

import time

for n in range(1, 10):
print(n)
print(n*2)
time.sleep(1)
print("\033[A\033[A", end="")

An ESCAPE is character 27, which is 033 in octal.
Note the end="" to stop the cursor moving down again...

Is there a way to make the console or terminal output change by just changing a variale in the python script

Since a,b,c are variables they are stored in memory that is allocated to the script during run time.

you can't change those values without re-running the script, which will freeup the old memory, reallocate new memory, and run your code.

I suspect your need for implementing such a solution, changing vars like this; will be way more work than you'll be comfortable implementing (the solution to this can be intermediate project on its own)

you are better of reading values into these vars from a file or db.

with open('filefora.txt', 'r') as f:
a = int(f.readline())
with open('fileforb.txt', 'r') as f:
b = int(f.readline())
while True:
if a and b:
print(True)
else:
print(False)
with open('filefora.txt', 'r') as f:
a = int(f.readline())
with open('fileforb.txt', 'r') as f:
b = int(f.readline())

Now every time you change the value in the file for the respective var, the code will use that new value without having to rerun the script.

Even better would be to just rerun the file.

output string overwrite last string on terminal in Linux with c++

Have you tried carriage returns \r? This should do what you want.

Overwrite last line on terminal

In your example you delete the text at the same line. When you want to return to the previous line use \e[1A, and to clear that line, use \e[K:

echo 'Old line'
echo -e '\e[1A\e[Knew line'

When you want to go N lines up, use \e[<N>A

Command output redirect to file and terminal

Yes, if you redirect the output, it won't appear on the console. Use tee.

ls 2>&1 | tee /tmp/ls.txt

Output to the same line overwriting previous output?

Here's code for Python 3.x:

print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!', end='\r')

The end= keyword is what does the work here -- by default, print() ends in a newline (\n) character, but this can be replaced with a different string. In this case, ending the line with a carriage return instead returns the cursor to the start of the current line. Thus, there's no need to import the sys module for this sort of simple usage. print() actually has a number of keyword arguments which can be used to greatly simplify code.

To use the same code on Python 2.6+, put the following line at the top of the file:

from __future__ import print_function

How do I overwrite console output?

Consoles are usually controlled by printing out "control characters", but what they are depends on the platform and terminal type. You probably don't want to reinvent the wheel to do this.

You can use the crossterm crate to get this kind of console control. A simple example is:

use std::{thread, time};
use std::io::{Write, stdout};
use crossterm::{QueueableCommand, cursor, terminal, ExecutableCommand};

fn main() {
let mut stdout = stdout();

stdout.execute(cursor::Hide).unwrap();
for i in (1..30).rev() {
stdout.queue(cursor::SavePosition).unwrap();
stdout.write_all(format!("{}: FOOBAR ", i).as_bytes()).unwrap();
stdout.queue(cursor::RestorePosition).unwrap();
stdout.flush().unwrap();
thread::sleep(time::Duration::from_millis(100));

stdout.queue(cursor::RestorePosition).unwrap();
stdout.queue(terminal::Clear(terminal::ClearType::FromCursorDown)).unwrap();
}
stdout.execute(cursor::Show).unwrap();

println!("Done!");
}


Related Topics



Leave a reply



Submit