This question already has answers here:
How to clear the interpreter console?
(31 answers)
Clear terminal in Python [duplicate]
(27 answers)
Closed 3 years ago.
I am running on Python 3.7.1 and I've been trying to find a way to clear a screen of any previously printed messages. The problem is that os.system("cls") does nothing, it only makes a small window pop up for a fraction of a second, then it closes. I've tried to add a \n at the end and multiplying it by how many letters there are, still not working.
Unfortunately, there’s no built-in keyword or function/method to clear the screen. So, we do it on our own.
We can use ANSI escape sequence but these are not portable and might not produce desired output.
# import only system from os
from os import system, name
# import sleep to show output for some time period
from time import sleep
# define our clear function
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
# print out some text
print('hello geeks\n'*10)
# sleep for 2 seconds after printing output
sleep(2)
# now call function we defined above
clear()
I don't think that there is a way, or at least have never seen one. However, there is a workaround which would look like
print "\n" * 100.
This will simply print 100 newlines, which will clear the screen for you.
You could also put it in a function
def cls(): print "\n" * 100
And then when you need it just call it with cls()
Related
This question already has answers here:
Python async: Waiting for stdin input while doing other stuff
(3 answers)
Closed 4 months ago.
I want it so that my code continuously replaces itself continuously, and while that executes, I want the input to just take what it is without needing to press enter. I'm an android user and I've already tried downloading non-built-in-modules, so I can't use the keyboard module or anything like that.
My code is basically:
while game == "on":
print("string")
inpu = input
time.sleep(1)
clear screen
Apologies for false text editing or bad "code grammar."
I'm new to coding and stack overflow.
NOT wait for user input while in a loop?
Solution
That is easy, using multi-thread or multi-process. i.e create another thread that handles the input separately.
Demo of full code
Here is a very simple demo of multi-thread to begin.
import _thread
args = None
# Define a function for the thread
def mythread(threadname):
global args
args = input("input anything: ")
# Create one threads as follows
try:
_thread.start_new_thread( mythread, ("UI",) )
while args==None: # mimic your work loop
pass;
print("main loops end demo end")
except:
print ("Error: unable to start thread")
To run
$ python3 demo.py
Output
input anything: hello
main loops end demo end
This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 3 years ago.
I am making a command line game engine in python. However, when I attempt to print a command, it newlines and creates a jittery frame.
Adding the end attribute bogs down my computer and nearly crashes the shell. The dupe uses sys.stdout.write('') newline sys.stdout.flush or print'', or print('',end=''). all bog down shell and crash it. print('') doesn't bog down though which is weird.
#this is enough code to demonstrate the problem
while true:
print(' = === ===== ======= ========= =========== ============= YYYYYYYYYYY ================================================================================')
#crash issue
import sys
while True:
sys.stdout.write('mooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo')
sys.stdout.flush()
I expect the screen to fill, instead it wobbles up and down.
I am not sure if I understood your question correctly, but I’m thinking you do not want to print a new line with each call to the print() function.
If so, the print function has an optional argument end, that is set by default as \n (this, creating a new line if not specified otherwise). If you don’t want this to happen, you can simply use the print function as:
print(your_argument, end=“”)
Replacing your_argument with whatever you want to print out.
This question already has answers here:
What is the best way to toggle python prints?
(6 answers)
Closed 7 years ago.
I have 10 or 15 very useful debugging print statements sprinkled throughout my program (in different functions and in main).
I won't always want or need the log file though. I have a config file in which I could add a parameter to toggle print statements on or off. But then, I'd have to add a guard check for the value of this parameter above every print statement.
What are some better approaches?
from __future__ import print_function
enable_print = 0
def print(*args, **kwargs):
if enable_print:
return __builtins__.print(*args, **kwargs)
print('foo') # doesn't get printed
enable_print = 1
print('bar') # gets printed
sadly you can't keep the py2 print syntax print 'foo'
This question already has answers here:
How to print one character at a time on one line?
(4 answers)
Closed 9 years ago.
I'm writing a Python app involving a database. For the hell of it, I'm including an easter egg. If the user decides to nuke his database, all this from a terminal, he'll be prompted to confirm with a simple (y/n). But if he types DLG2209TVX instead, the lines from that scene of WarGames will print. Doubt anybody will ever find it unless they look through my source, but that's okay.
The problem is that simply printing the lines plays the scene way too fast and really just ruins it. I implemented a timer between each character's lines to slow things down, and it's better, but it still seems unnatural. Is there a standardized way to slowly print each word or character out instead of doing it lines at a time? Or should I just start adding timers between words?
Standardized? Not that I know of. But try this:
import random
import sys
import time
def slowprint(s):
for c in s + '\n':
sys.stdout.write(c)
sys.stdout.flush() # defeat buffering
time.sleep(random.random() * 0.1)
slowprint('Hello, world.')
Adjust the 0.1 to change the maximum delay between characters, and add lengthy time.sleep()s between lines to add more dramatic effect.
import sys
import time
for c in gettysburg_address:
sys.stdout.write(c)
sys.stdout.flush()
# 110 baud:
time.sleep( 8./110 )
# 300 baud:
# time.sleep( 8./300 )
You can also try curses.delay_output():
In [48]: import curses
In [49]: for x in "foo bar":
sys.stdout.write(x) #prints each char with a delay of 100ms
curses.delay_output(100)
....:
foo bar
I'd like to print a string to command line / terminal in Windows and then edit / change the string and read it back. Anyone knows how to do it? Thanks
print "Hell"
Hello! <---Edit it on the screen
s = raw_input()
print s
Hello!
You could do some ANSI trickery to make it look like you are editing on screen. Check out this link (also similar to this SO post on colors).
This would only work on certain terminals and configurations. ymmv.
This python script worked in my Cygwin terminal on Win7:
print 'hell'
print '\033[1A\033[4CO!'
Ends up printing hellO! on one line. The 2nd print moves the cursor up one line (Esc[1A) then over 4 characters (Esc[4C]) and then prints the 'O!'.
It wouldn't let you read it back though... only a 1/2 answer.
I had this same use-case for a command-line application.
Finally found a hack to do this.
# pip install pyautogui gnureadline
import pyautogui
import readline
from threading import Thread
def editable_input(text):
Thread(target=pyautogui.write, args=(text,)).start()
modified_input = input()
return modified_input
a = editable_input("This is a random text")
print("Received input : ", a)
The trick here is use pyautogui to send the text from keyboard. But we want to do this immediately after the input(). Since input() is a blocking call, we can run the pyautogui command in a different thread. And have an input function immediately after that in the main thread.
gnureadline is for making sure we can press left and right arrow keys to move the cursor in a terminal without printing escape characters.
Tested this on Ubuntu 20, python 3.7
raw_input accepts a parameter for a "prompt message", so use that to output the message, and then prepend it to what you get back. However, this won't allow you to backspace into the prompt, because it's a prompt and not really part of the input.
s = "Hell" + raw_input("Hell")
print s
os.sys.stdout is write only, but you can erase some characters of the last line with \b or the whole line with \r, as long as you did not write a carriage return.
(however, see also my question about limitations to the standard python console/terminal)
I once made some output exercise (including a status bar) to write,erase or animate if you will, perhaps it is helpfull:
from __future__ import print_function
import sys, time
# status generator
def range_with_status(total):
n=0
while n<total:
done = '#'*(n+1)
todo = '-'*(total-n-1)
s = '<{0}>'.format(done+todo)
if not todo:
s+='\n'
if n>0:
s = '\r'+s
sys.stdout.write(s)
sys.stdout.flush()
yield n
n+=1
print ('doing something ...')
for i in range_with_status(10):
time.sleep(0.1)
print('ready')
time.sleep(0.4)
print ('And now for something completely different ...')
time.sleep(0.5)
msg = 'I am going to erase this line from the console window.'
sys.stdout.write(msg); sys.stdout.flush()
time.sleep(1)
sys.stdout.write('\r' + ' '*len(msg))
sys.stdout.flush()
time.sleep(0.5)
print('\rdid I succeed?')
time.sleep(4)
If it's for your own purposes, then here's a dirty wee hack using the clipboard without losing what was there before:
def edit_text_at_terminal(text_to_edit):
import pyperclip
# Save old clipboard contents so user doesn't lose them
old_clipboard_contents = pyperclip.paste()
#place text you want to edit in the clipboard
pyperclip.copy(text_to_edit)
# If you're on Windows, and ctrl+v works, you can do this:
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys("^v")
# Otherwise you should tell the user to type ctrl+v
msg = "Type ctrl+v (your old clipboard contents will be restored):\n"
# Get the new value, the old value will have been pasted
new_value= str(raw_input(msg))
# restore the old clipboard contents before returning new value
pyperclip.copy(old_clipboard_contents )
return new_value
Note that ctrl+v doesn't work in all terminals, notably the Windows default (there are ways to make it work, though I recommend using ConEmu instead).
Automating the keystrokes for other OSs will involve a different process.
Please remember this is a quick hack and not a "proper" solution. I will not be held responsible for loss of entire PhD dissertations momentarily stored on your clipboard.
For a proper solution there are better approaches such as curses for Linux, and on Windows it's worth looking into AutHotKey (perhaps throw up an input box, or do some keystrokes/clipboard wizardry).