Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and Write separately in python

I'm trying to create a very simple program in python that needs to read input from the user and write output accordingly. I need an output similar to this:

$./program.py
say something: Hello World
result: hello world

The thing is that i need to read input indefinitely, each time the user inputs data i would like that the printed data doesn't obstruct the input prompt. It will even better that no newlines be printed, keeping the output as above: a line for reading and another for writing.

I tried using curses but i don't want the hole screen to be used, just the two lines.

like image 824
Rolando Urquiza Avatar asked May 22 '26 14:05

Rolando Urquiza


2 Answers

I believe this is what you want:

import colorama
colorama.init()
no = 0
while True:
    user_input = str(raw_input('\033[2A'*no + '\033[KSay something: '))
    print '\033[KResult: ' + user_input
    no = 1

This how it looks after entering the string:

Working solution

This implementation works on windows, however, if you use Linux, if I am not mistaken these are not necessary:

import colorama
colorama.init() 

EDIT: Modified my code a bit so it does not overwrite the text that was printed before the execution of the code. Also added an image of working implementation.

like image 135
UN4 Avatar answered May 24 '26 04:05

UN4


You can do veeeery simple trick:

from os import system
while True:
    system('clear')  # or 'cls' if you are running windows
    user_input = input('say something:')
    print('result: ' + user_input)
    input()
like image 41
Laszlowaty Avatar answered May 24 '26 05:05

Laszlowaty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!