Making python output print and disappear? - python

Hey i wanted to know that if there is a way to make a python output print and disappear like in the case of comparing a user entered word with a world in a list,while quickly printing all the words it has traversed ,quite like a animation?

One thing you could try to do is clear the console. There are multiple resources on how to do it so I won't explain it here, but it's easy to find on the internet. If you have a bunch of text in the console and there's a specific piece of text that you want to delete, then you can get all of the text in the console as a string and filter out the part that you want to delete, so that way, when you clear the console, you can re-print that back into the console, so that way it disappears but all of the other text elements do not. If that makes sense lol.

Adding to Amirul Akmal I believe this code might Help you understand it better
from os import system
# 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('test\n'*10)
# sleep for 2 seconds after printing output
sleep(2)
# now call function we defined above
clear()

Related

Clear current line in STDOUT in python

So I made a program in python that asks a user for input repetitively. After a while, the previous commands start to build up, as so.
> Ping
Pong!
> Hello
Hey there!
>say whats up?
Whats up?
I made the commands up just to show examples
I want to add an animation that adds a ... to the end of a word, such as
i choose.
then clear the line then
i choose..
then clear the line then
i choose...
and so on, but I need to clear the screen in order for this to work and I want the history of the users commands and responses to sill be there. Is there any way using python or importing os to only remove one line instead of the entire screen? Thanks!
You are looking for the carriage return character, \r. When you print that character, the previous line will be cleared. For example:
import time
print('I choose',end='',flush=True)
time.sleep(1)
print('\rI choose.',end='',flush=True)
time.sleep(1)
print('\rI choose..',end='',flush=True)
time.sleep(1)
print('\rI choose...',end='',flush=True)
This is actually how people make the progress bar in command line.
You should be able to do this using normal ‘print’, just appending a comma to the end of the print statement:
from time import sleep
print ‘I choose.’,
sleep(0.5)
print ‘.’,
sleep(0.5)
print ‘.’
Edit: Added in sleeps to make the animation work more as expected.

Python: detect specific key press and prompt the user

I need to print out sentence "Hello World" every 10 seconds. However, if the user either 'c' or 'Enter', the program should stop printing the sentence and prompt the user to provide with the another sentence. The user-provided sentence is checked and if the sentence contains any digits, a message shows up: "cannot contain digits". Otherwise a message shows up: "correct sentence". After displaying either of the messages, the program continues printing "Hello World".
Here is the code I have strated with. Any hints on how to continue further would be greatly appreciated.
Thanks!
import threading
def looping():
threading.Timer(10.0, looping).start()
print("Hello World!")
looping()
From my understanding of your assignment's instructions, it looks like you're on the right track with using a timer to print "Hello World"! I'd like to upvote Irmen de Jong's comment on your question with regard to the statement "threads and console input/output don't work nicely together", since I've experienced this myself in C programming.
Once you have the timer going, the text it prints to the screen shouldn't have an effect on responding to keyboard input. If it's really required to respond directly to a keypress of 'c' (not followed by 'Enter', as one would normally have to do when reading input from the keyboard with input()), I recommend following one of the solutions in Python method for reading keypress? to figure out how you would like to implement that.
EDIT: Implementing a solution using a thread-based timer is a bit more tricky than I thought.
As you may have found in your research on this problem, the threading.Timer object has both start() and stop() methods that you can use to control the execution of individual thread timers if you've saved a reference to the timer in a variable (e.g. doing my_timer = threading.Timer(10.0, looping) then calling my_timer.start() to start the timer). If you do this, you may be able to call my_timer.stop() to pause the looping, provided you've kept a proper reference to the current timer instance that you need to stop at that point in time.
To make things a bit easier, I chose to create a global variable PAUSE_LOOPING that, when set to False, will stop a new timer instance from being started when looping is called, thereby halting all further repetitions of the function until PAUSE_LOOPING is set back to True and looping() is called again:
import threading
from msvcrt import getch
PAUSE_LOOPING = False
def looping():
global PAUSE_LOOPING
if not PAUSE_LOOPING:
threading.Timer(10.0, looping).start()
print("Hello World!")
looping()
while True:
# key = ord(getch())
# if key == 13: # Enter
# PAUSE_LOOPING = True
input_string = input()
if input_string == "":
PAUSE_LOOPING = True
else:
PAUSE_LOOPING = False
looping()
Commented out in the last code block is one way to grab a key press directly (without needing to press the 'Enter' key as is required by input()) taken from the stackoverflow question I linked to earlier in my answer. This should work as long as you're using Python for Windows (so you have the MS VC++ runtime library msvcrt installed), but to make the script stop when pressing 'Enter' you can use the standard input() function. In my example, typing any other string of characters before pressing 'Enter' will resume looping after it's been paused.
NOTE: Beware of using Python's IDLE to run this code. It won't work. Instead, you must run it from the command line.

How do you make program clear your console clean before it prints a list?

office_list = []
print("Type in your office supplies.\nEnter 'DONE' to print out your list.\n--------------------\n")
while True:
list = input("> ")
if list == 'DONE':
break
office_list.append(list)
print("Here is your list\n--------------------\n")
for ls in office_list:
print(ls)
I've been trying to find this online but seem to have trouble trying to find the correct vocabulary I believe.
What I am trying to make the program do is clear what I have written to make the list and then print the list. What happens in the program right now is it will have the words I typed on top of the list and print when I enter the word 'DONE'.
You can use the os module. Under *nix, you can use os.system('clear') or os.system('cls') under Windows.
Using the os module, you can run shell commands. To clear the console on Linux/macOS you can use the clear command, on Windows there's cls:
import os
import sys
def clear():
if sys.platform == 'windows':
os.system('cls')
else:
os.system('clear')
Just print enough newline characters like this:
print('\n' * 50)
It doesn't hurt to print out too many lines for a console application as this will all happen in a split second. This method is cross-platform and should work in nearly any environment.
The OS-level answers actually do the same thing, but the OS knows exactly how many lines to print. If you don't care about hiding the precise number of lines that are shown on the screen, just print out enough (within reason) to clear the console.

Present blank screen, wait for key press -- how?

'lo,
I am currently trying to code a simple routine for an experiment we are planning to run. The experiment starts by entering a subject number and creating a bunch of files. I got that part working. Next, we want the screen to go blank and display a message. Something like 'Please fill in questionnaire 1 and press [ENTER] when you are done.'
My question is, how do you recommend I present a blank screen with a message like that that waits for a certain key to be pressed?
I have quite some programming experience but haven't worked with Python before so any hints are greatly appreciated. Thanks a lot in advance for your time!
~~~~~~~~~~~~~~~~~~
Some extra info that might be relevant: We are running this on Windows XP (Service Pack 2) computers. The whole point of this is that the participant does not have access to the desktop or anything on the computer basically. We want the experiment to start and display a bunch of instructions on the screen that the subject has to follow without them being able to abort etc. Hope this makes sense.
If you're in python 2, use raw_input().
If you're using python 3, use input().
You can prompt the user for information and store the result as a string.
in python 2.x
response = raw_input("What would you like to do next?")
in python 3.x
response = input("What would you like to do next?")
On windows, you can use functions in the msvcrt module. For example, kbhit() waits until the user presses a key.
To print the blank screen before putting the prompt, I used the following
import os
import sys
VALIDINPUT = '0'
while VALIDINPUT == '0':
p = os.popen('clear')
for line1 in p.readlines():
print line1
<put the logic for reading user input here>
<put the logic to check for valid user input here and if the user input is valid, then
assign 1 to VALIDINPUT>
This will show a blank screen and the prompt until the user provides a valid input.
Hope this helps. I used this on Linux.
raw_input('Please fill in questionnaire 1 and press [ENTER] when you are done.') will wait for someone to hit [enter].
Clearing the screen may be OS/environment dependent, I am not sure.

Avoiding raw_input to take keys pressed while in a loop for windows

I am trying to make a program which has a raw_input in a loop, if anyone presses a key while the long loop is running the next raw_input takes that as input, how do I avoid that?
I don't know what else to add to this simple question. Do let me know if more is required.
EDIT
Some code
for i in range(1000):
var = raw_input("Enter the number")
#.... do some long magic and stuff here which takes afew seconds
print 'Output is'+str(output)
So if someone presses something inside the magic phase, that is take as the input for the next loop. That is where the problem begins. (And yes the loop has to run for 1000 times).
This works for me with Windows 7 64bit, python 2.7.
import msvcrt
def flush_input():
while msvcrt.kbhit():
msvcrt.getch()
I put the OS in the title, window 7 64 bit to be specific. I saw the
answers there. They do apply but by god they are so big. Aren't there
other n00b friendly and safer ways to take inputs?
Let me try to explain why you need to do such an elaborate process. When you press a key it is stored in a section of computer memory called keyboard buffer (not to be confused with stdin buffer). This buffer stores the key's pressed until it is processed by your program. Python doesn't provide any platform independent wrapper to do this task. You have to rely on OS specific system calls to access this buffer, and flush it, read it or query it. msvcrt is a MS VC++ Runtime Library and python msvcrt provides a wrapper over it. Unless you wan't a platform independent solution, it is quite straight forward.
Use msvcrt getch to read a character from console. msvcrt.kbhit() to test if a key press is present in the keyboard buffer and so on. So as MattH has shown, it just a couple of lines code. And if you think you are a noob take this opportunity to learn something new.
Just collect your input outside of the loop (before you enter the loop). Do you really want the user to enter 1000 numbers? well maybe you do. but just include a loop at the top and collect the 1000 numbers at the start, and store them in an array.
then on the bottom half change your loop so it just does all the work. then if someone enters something no the keyboard, it doesn't really matter anymore.
something like this:
def getvars(top=1000):
vars = []
for i in range(0,top):
anum = int(raw_input('%d) Please enter another number: ' % i))
vars.append(anum)
return vars
def doMagic(numbers):
top = len(numbers)
for number in numbers:
# do magic number stuff
print 'this was my raw number %s' % number
if __name__ == "__main__":
numbers = getvars(top=10)
doMagic(numbers)
presented in a different sort of way and less os dependent
There is another way to do it that should work. I don't have a windows box handy to test it out on but its a trick i used to use and its rather undocumented. Perhaps I'm giving away secrets... but its basically like this: trick the os into thinking your app is a screensaver by calling the api that turns on the screensaver function at the start of your magic calculations. at the end of your magic calculations or when you are ready to accept input again, call the api again and turn off the screensaver functionality.
That would work.
There is another way to do it as well. Since you are in windows this will work too. but its a fair amount of work but not really too much. In windows, the window that is foreground (at the top of the Z order) that window gets the 'raw input thread'. The raw input thread receives the mouse and keyboard input. So to capture all input all you need to do is create a function that stands up a transparent or (non transparent) window that sits at the top of the Z order setWindowPos would do the trick , have it cover the entire screen and perhaps display a message such as Even Geduld or Please wait
when you are ready to prompt the user for more input, you use showwindow() to hide the window, show the previous results, get the input and then reshow the window and capture the keys/mouse all over again.
Of course all these solutions tie you to a particular OS unless you implement some sort of try/except handling and/or wrapping of the low level windows SDK calls.

Categories