Is there a way to replace a previously outputted text in Python? - python

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!
===========================================================================================

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()

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()

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!
===========================================================================================

Related

"Typewriter"-like printing not working in CMD or py.exe, but works in VS Code Terminal

I'm studying software development and we've started using python, and for an exercise I wanted to make a "fancy" printing style. With some help from the internet I managed to get this to work in the terminal of VS Code, which I've been using- but when running the .py file on its own or through CMD, the loop is ran as many times as it should, and only then prints the output all at once.
from time import *
from random import *
from numbers import *
# Slow printing function- prints 1 character at a time
def slowPrint(line):
for char in line: # For every character (char) in the string (line)
t = uniform(0.03, 0.3)
print(char,end="") # Print the character, end on nothing to ensure no spaces between characters
sleep(t) # Sleep for t amount of seconds
# Conversation
slowPrint("Message 1."), sleep(0.5), slowPrint(" Message 2.\n")
input("Press enter;")
What I believe it should do, and what it does in the VS Code Terminal, is that it prints every character on its own, with a random delay between each character. I can't figure out what is making this different between VS Code and CMD.
I hope someone here knows this :> thanks in advance!
Add flush=True to the print function:
print(char, end="", flush=True)
Basically flush well... flushes the data immediately instead of buffering it (w3schools reference to print function)
Also:
I strongly advise against using wildcard (*) when importing something, You should either import what You need, e.g. from module import Class1, func_1, var_2 and so on or import the whole module: import module then You can also use an alias: import module as md or sth like that, the point is that don't import everything unless You actually know what You are doing; name clashes are the issue.

Clearing Print in Python

So I'm pretty new to both coding and this website, so please bear with me if this is stupid:
I'm working on a personal project and would like to find a way to clear "print()" statements in python 3.6. For example:
print("The user would see this text.")
but if I continue
print("The user would see this text.")
print("They would also see this text.")
Is there a way to make it so a user would only see the second print statement?
I have seen "os.system('cls')" and "os.system('clear')" recommended, but I get these errors for each:
os.system('cls')
resulting in
sh: 1: cls: not found
and
os.system('clear')
resulting in
TERM environment variable not set.
Obviously I'm missing something, but if you know what it'd be much appreciated. If you know of another way to do what I'm thinking, that would also be awesome. Thank you for taking the time to read this, and thanks for any help.
Edit: I'm using Repl.it as my IDE. Could this be an issue with that site specifically?
Edit: Downloaded a new IDE to check, and the reply worked. If you are new and using Repl.it, be aware that some code does not function properly.
The method that I've used in the past to 'reprint' something on an existing line is to make use of the standard output directly, coupled with a carriage return to bring the printed statement's cursor back to the start of the line (\r = carriage return), instead of relying on the print function.
In pseudocode:
# Send what you want to print initially to standard output, with a carriage return appended to the front of it.
# Flush the contents of standard output.
# Send the second thing you want to print to standard output.
A working example in Python:
import sys
sys.stdout.write('\rThe user would see this text')
sys.stdout.flush()
sys.stdout.write('\rThe user would also see this text')
Edit
Figured I'd add an example where you can actually see the code working, since the working example above is going to execute so quickly that you'll never see the original line. The below code incorporates a sleep so that you can see it print the first line, wait, then reprint the line using the second string:
import sys
from time import sleep
sys.stdout.write('\rThe user would see this text')
sys.stdout.flush()
sleep(2)
sys.stdout.write('\rThe user would also see this text')

IPython 5.0: Remove spaces between input lines

(This question is essentially this question, but for IPython version 5.0)
I'd like to have a classic prompt with IPython 5.0.
This question helps customize my prompt. In fact, I discovered that IPython has a class definition for the ClassicPrompts already.
All I need to do is to put the following in a file called 00-classic-prompts.py or some such in ~/.ipython/profile_default/startup/:
from IPython.terminal.prompts import ClassicPrompts
ip = get_ipython()
ip.prompts = ClassicPrompts(ip)
But different prompt lines still render as:
>>> print('Hello world!')
Hello world!
>>>
With an extra new-line before every input prompt. How can I remove this?
Please append this line on the bottom of your existing startup script:
ip.separate_in = ''
This is a documented feature but currently has no description, making it hard-to-find.

What do the three arrow (">>>") signs mean?

I haven't been able to figure out what the >>> does, even though I often see it often in source code.
You won't see it in source code, it's probably documentation. It indicates an interactive session, and things typed into the 'interpreter' are marked with this. Output is shown without the arrows.
In fact, the python documentation often has a button >>>at the top right of example code to be able to hide the arrows (and output) so that you can copy and paste the code.
Shown:
Hidden:
'>>>' is the prompt of the interactive Python interpreter, meaning that the interpreter is ready to get Python statements typed in. It's occuring quite often in examples within the documentation of a Python program, in order to show which commands can be used and what will be the result of giving these commands to the interactive interpreter. For example, in a documentation of the print statement, one could give this example:
>>> print "Hello world."
Hello world.
This would be an actual snippet of a session with the interactive Python interpreter.
An interesting feature in IPython is that it ignores leading >>>, meaning that you can copy and paste code from such documentation without needing to remove the leading >>>:
In [1]: >>> print "Hello world."
Hello world.
(The prompt in IPython is In [n]:, where n is counting the interactive commands issued.)
Here are some of my findings on >>> and consequently ... complementing the previous answers.
You only see >>> when you are running Python in interactive mode prompting/asking the user for the "next command". Technical details here.
>>> and ... are not written in stone. These are stored in sys.ps1 and sys.ps2, and therefore can be changed. Further elaborated here.
>>> import sys
>>> sys.ps1 = "$ "
$
Every standard Python has this prompt unless you compile your own Python after changing >>> and ... to what you (sanely) wish to. Apart from that there seems to be a way to change it for all future interactive sessions by changing /usr/lib/python2.7/code.py but I couldn't find any success with it.
The >>> prompt is the Python interpreter’s way of asking you, “What do you want
me to do next?”, and it is called "chevron" prompt
In case you are trying to figure out how to exit a session, run this:
quit()
I found it to be called ' REPL'

Is it possible to print a string at a certain screen position inside IDLE?

EDIT: I just discovered that it's possible to obtain a similar behaviour by using the standard library "curses". There are some demonstrations about how it works here and there, for example on YouTube: http://www.youtube.com/watch?v=Bj-H9uPEa5U
It's a strange and silly question I know, but I'm curious because I don't know that much about python and how it works.
From the terminal or when you use IDLE, is there any way to print a string at a certain screen position?
I'll try to explain this better: Do you remember the old days when you used to make small programs in Basic, maybe on a Commodore 64, Apple II or ZX Spectrum?
During that days if you wanted to print a string at a certain position you used to write something like this:
10 LOCATE 30, 40 : PRINT "hello world"
I'm just curious to know if there's any way to tell python to print a string at a certain position, and if there's a way to know how many columns and how many rows can be actually displayed inside the IDLE window.
I've also made a mockup draw, to explain this concept.
I don't know if this works on IDLE, but it does in any normal terminal:
import sys
def print_there(x, y, text):
sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text))
sys.stdout.flush()
This uses Ansi-Escape Sequences
This question only has one real answer and it isn't a very good one. The method:
import sys
def print_there(x, y, text):
sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text))
sys.stdout.flush()
Isn't perfect. I'd recommend staying clear of doing things like this in the terminal. If you want to do Gui's and stuff use Pygame, Tkinter, or Django.
To avoid the issue raised by #user3431399, you first need to make win32 console recognize ANSI/VT100 escape sequences. I got the same problem as #user3431399 on my Windows 10 terminal and I solved it by following the solution recommended by #Daniel De Léon. That is, I logged in as administrator at the windows prompt (cmd command). Then I copied, pasted, and ran the command.
REG ADD HKCU\CONSOLE /f /v VirtualTerminalLevel /t REG_DWORD /d 1
Use Tkinter to make it perfect by select under frame and provide row and column number to display your output

Categories

Resources