How to refresh/overwrite console output in python - python

I want to know how to refresh the console of my program as if it was just started. Let's say that my code consists of an infinite loop and it has multiple instances of the print() function within itself, I want, every time that loops returns to its start, all the new data whether there is some change or not to get outputted on the same place of the data that has been outputted the last time.
I have been reading about similar problems others have posted and the answers usually revolve around the idea of using \r, when I do that, however, it's always messy and the strings are either printed halfway or there are missing characters. On Replit there is a module called "replit" and there is a function there called clear() that basically performs what I need, but I don't seem to find it when I am using PyCharm, which means that it is perhaps something that works exclusively within the Replit environment. So I am asking, is there something similar in the standard python library that I can use? Thanks

You can use:
import os
command = 'cls' #for windows
os.system(command)
example:
print('hi')
os.system(command)
print('hi')
Output:
hi
For windows you need:
command = 'cls'
For all others it is:
command = 'clear'
To account for any OS you could use:
import os
def clearConsole():
command = 'clear'
if os.name in ('nt', 'dos'): # If computer is running windows use cls
command = 'cls'
os.system(command)
clearConsole()

There is nothing standard in Python to do it, because Python is not aware of whatever console you are using.
When you call print it is actually writing to a file called "standard output".
It can go to a console if you are running your program in a console (like windows cmd, Linux or Mac OS terminal app, or whatever PyCharm uses).
But it can also be redirected to a regular file by the user of your program.
So there is no standard way.
\r is "carriage return" character. On consoles that respect it, it will set your output position to the beginning of the current line, but will not erase any text already printed on that line (usually).
One way to print text in specific places on the screen is PyCurses.
It supports many consoles and figures out which one you are using automatically.
You can do something like this:
import curses
stdscr = curses.initscr()
stdscr.addstr(x, y, "my string")
By using the addstr isntead of print, you can choose the exact position the text will appear, with X and Y coordinates (first two parameters).
Read the documentation for more ways to manipulate text display with this library.

Related

How to execute commands from a command-line program one after another, if possible, using os or subprocess?

I wanted to ask if there is a way to run the commands of a command line program in python, but the codes must be executed repeatedly, namely, the solution I want is not this
os.system(f"xxx.exe {command}").
I tried subprocess.run function putting the name of the exe followed by the commands I want to execute inside the brackets and then these keyword args: stdout=subprocess.PIPE,text=True however, oddly it doesn't make data.stdout the whole output for some reason. Only the initial code's output is assigned to that. It is probably because the arguments inside the brackets don't represent different lines. Therefore, I guess the thing I've done using subprocess is the same as how I executed a single line of command via the os library.
Namely, my question is using subprocess or os, how can I execute codes that must be executed in different lines, or if not possible, how to execute commands from a command-line program one after another in python?
Edit: Should I make something like this?
os.system(f"xxx.exe {command1} \n {command2}")
It's kind of a shortcut but you could do something like this:
import os
import pyautogui
os.startfile('Path_to_command_prompt')
pyautogui.PAUSE = however long it takes to run each command
pyautogui.write('Command_1')
pyautogui.press('enter')
pyautogui.write('Command_2')
pyautogui.press('enter')

How do I call a function in vs code using python?

I'll want to know how to call a function in vs code. I read the answer to similar questions, but they don't work:
def userInput(n):
return n*n
userInput(5)
And appends nothing
def Input(n):
return n*n
And in the terminal:
from file import *
from: can't read /var/mail/file
Can somebody help me?
You are doing everything correctly in the first picture. In order to call a function in python on vs code you first have to define the function, which you did by typing def userInput(n):. If you want to see the result of your function, you should not use return, you should use print instead. Return is a keyword- so when your computer reaches the return keyword it attempts to send that value from one point in your code to another. If you want to see the result of your code, typing print (n) would work better.
Your code should look like this:
def userInput(n):
print (n * n)
userInput(5)
The code would print the result 25
Your terminal is your general way to access your operating system, so you have to tell it that you want it to interpret your Python code first.
If you want to run the file you're typing in, you have to first know the location of that file. When you type ls in your terminal, does the name of your Python file show up? If not, hover over the tab in VSCode (it's close to the top of the editor) and see what path appears. Then in your terminal type cd (short for "change directory") and then the path that you saw, minus the <your filename here>.py bit. Type ls again, and you should see your Python file. Now you can type python <your filename here>.py to run it (provided you have Python installed).
You could also run the IDLE by just typing python in your terminal. This will allow you to write your code line-by-line and immediately evaluate it, but it's easier to write in VSCode and then run it with the method I described before.

Anyway of clearing text in IDLE

Is there anyway of clearing text in IDLE, its really anoying when i run the script a couple of times and then there's a cluster of words which is really hard to read.
and yes I have looked on google, stack_overflow and a couple of more websites but i cant find anything useful.
I tried to do:
import os
def cls():
os.system("cls")
>>>cls()
If you mean using the actual IDLE shell, I don't think there's any way to do it. IDLE is not meant to run programs from, it's just supposed to be a development tool. If you want to run programs from terminal or cmd, you can clear the text easily.
Use this instead:
os.system("clear") # or "cls" on windows
or
subprocess.call('clear') # or "cls" on windows
To fake it in IDLE, you can use something like:
print("\n" * 50)
from subprocess import call as c
def cls():
c("cls",shell=True)
print([x for x in range(10000)])
cls()
Whenever you wish to clear console call the function cls, but note that this function will clear the screen in Windows only if you are running Python Script using cmd prompt, it will not clear the buffer if you running by IDLE.

Printing a line at the bottom of the console/terminal

Using Python, I would like to print a line that will appear on the last visible line on the console the script is being ran from. For example, something like this:
Would this be able to be done?
The easiest way is to use effbot.org's Console module:
import Console
c = Console.getconsole()
c.text(0, -1, 'And this is the string at the bottom of the console')
By specifying -1 for the second (line) argument you are addressing the last line of the console.
Because the Console module only works on Windows, to get this to work on UNIX terminals as well, you should take a look at the wcurses library, which provides a partial curses implementation that'll work on Windows. You'd drive it the same as the stdlib curses module; use the first on Windows, the latter on UNIX.
For a Windows terminal try the console module For unix the curses module would do.

How to update a number without changing lines or placement of output

I would like to update a number without changing its placement in the output of a program. How would i go about doing this using only what is included in the standard library for python 2.7.2 ?
For example i want output like:
working on: 9
and change to:
working on: 10
without changing the line that it is displayed on. How would i go about doing this? I would also prefer that you not use cls as to prevent "flashing".
How to do this depends on your terminal type (and possibly on your platform). An easy way that works on many platforms and terminals is to use a \r character to move the cursor back to the beginning of the line:
import time
import sys
for i in range(10):
print "\rworking on:", i,
sys.stdout.flush()
time.sleep(1)
To make the line actually appear, you might need the call to sys.stdout.flush().
There isn't any easy way to do this without resorting to a GUI of some type. The standard way to create a GUI using the terminal is python's curses module. For an explanation of how to use curses in your application see: Curses Programming with Python.

Categories