Python Hello World keeps closing itself - python

I'm new to programming. I''ve successfully wrote everybody's first program , however , it executes right before closing itself. How can I add a pause to the program?

Modify the code to be like this, you will learn about the below function soon enough:
print('Hello world!')
input()
Now at the end of the program it won't exit until you press Return.
Or better still, run the code in a shell like IDLE so you don't have to worry about all that.

You need to put a call to input at the bottom of your script:
print("Hello World!")
input("Press 'Enter' to exit.") # Use raw_input in Python 2.x
Doing so will keep the output window open until you press Enter.

If you literally want to add a fixed pause, use the sleep function in the time module. The is discussed in detail in the answer to How can I make a time delay in Python? . Your program then becomes:
import time
print("Hello world")
time.sleep(1)
The first line tells python that time means the module time, while the last line says to wait for 1 second. (If you wanted to wait for 2.5 seconds, then change the last line to time.sleep(2.5), etc...)

Related

How to have an updating prompt while waiting for input in python?

So the question is how to have an input function or stdin.readline function waiting for an input, while having an updating prompt i.e. The prompt contains the time in format HH:MM:SS and is refreshing every second like:
while 1:
sys.stdout.write('\r' + time.strftime(TIME_FORMAT) + ' :>')
time.sleep(1.0)
But as soon as you add an input there, of course the program waits until you write some input. The version of python I am using is 3.5.
I know I should use curses, but I am planing to write a cross-platform program and the only module I have found is clint, but it didn't have anything in the documentation on the updating prompt.
I have found something that got pretty close but has different problems:
def input_thread(L):
x = input()
L.append(x)
L = []
thread = threading.Thread(target=input_thread, args=(L,))
thread.start()
while 1:
sys.stdout.write('\r' + time.strftime(TIME_FORMAT) + '>:')
time.sleep(1.0)
sys.stdout.flush()
Now the problem remains is that when you type the input but do not press ENTER, the input on the next iteration remains but when you write something, the previous input gets replaced by the current one. Of course the previous inputs are still there in the argument L, so there is no lost input. I hope I didn't describe this to confusing.
If there is no easy way of doing this as it could be done with curses, I'm open to similar cross open tools. Thanks for your time and answers!
So, I figured out what I wanted, a few months ago but didn't answered my own quesiton.
To have a prompt with updating time, you need a separate threads that:
Updates the prompt with additional input
Catches your key strokes
The second thread handles every key-stroke and you can program it how to handle the pressed keys.
When pressing a key, the thread that updates the prompt adds the pressed keys. Also you have to configure some shortcuts for Return, Backspace, etc... to work as expected
I've got it to work and unfortunately... I don't like it. If anyone would like to see the code I will happily provide.

Python: Execute a line by user input?

I am currently working on a game and I was wondering if there was any way to execute commands like a text file by user input?
I would like to make it where the text doesn't pop up all at once, but where you could do something like "Press any key to continue" and when they do that, the next wall of text appears. Any help is appreciated. Thanks.
The easy way is:
input('Press Enter to continue')
(in Python 3; raw_input instead in Python 2) but that will indeed wait for an Enter, AKA return, before continuing.
If you're really adamant about the any-key part you'll have to get "down and dirty". In Microsoft Windows only,
import msvcrt
def wait():
msvcrt.getch()
print('Press any key to continue')
wait()
will work -- but it will fail on Linux or MacOSX; you'll need other approaches for those. So please let us know which platform(s) you need to support and we'll figure something out!-)
Try putting input("Press Enter to continue") between printing each wall of text.

Why is time.sleep pausing early?

I'm teaching myself python with the aid of Head First Programming.
I thought I might tweak their example more to my liking, but I think I'm missing something about time.sleep.
My code is
print("Welcome to SuperBeans!")
time.sleep(3)
answer = input("Do you need a price now? y/n: ")
But rather than pausing for three seconds after the welcome message, it waits 3 minutes, then displays both the message and the input request. What am I missing?
Additionally, the program seems to hang indefinitely when running the "poll" function I defined, without ever displaying the "polling..." notice. I know get_price() is working because it prints it in another section ...
def poll():
price = 99.99
print(price)
while price > 4.74:
print("Polling...")
price = get_price()
time.sleep(5)
print("Buy!")
So why is the welcome pausing before I think it should be, and why is the poll() function hanging?
As discussed in comments above, Python output is being buffered, so the programs run (and sleeps for the right time etc) but you don't see the output for a while.
If you're running Python from a nonstandard console, you need to pass the "-u" option to Python to disable the buffering. I.e.:
python -u foo.py
About why is poll() function hanging, this may be because it stays in the while loop.
So question: is get_price() ever returning something strictly greater than 4.74 ? (hint: print the value returned)

Python: how to modify/edit the string printed to screen and read it back?

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

Scanning Keypress in Python

I have paused a script for lets say 3500 seconds by using time module for ex time.sleep(3500).
Now, my aim is to scan for keypresses while the script is on sleep, i mean its on this line.
Its like I want to restart the script if a "keypress Ctrl+R" is pressed.
For ex.. consider
#!/usr/bin/python
import time
print "Hello.. again"
while True:
time.sleep(3500)
Now while the code is at last line, If i press Ctrl+R, i want to re-print "Hello.. again" line.
I am aware that this does not fully answer your question, but you could do the following:
Put the program logic code in a function, say perform_actions. Call it when the program starts.
After the code has been run, start listening for an interrupt.
That is, the user must press ctrl+c instead of ctrl+r.
On receiving an interrupt, wait half a second; if ctrl+c is pressed again, then exit.
Otherwise, restart the code.
Thus one interrupt behaves as you want ctrl+r to behave. Two quick interrupts quit the program.
import time
def perform_actions():
print("Hello.. again")
try:
while True:
perform_actions()
try:
while True: time.sleep(3600)
except KeyboardInterrupt:
time.sleep(0.5)
except KeyboardInterrupt:
pass
A nice side-effect of using a signal (in this case SIGINT) is that you also restart the script through other means, e.g. by running kill -int <pid>.
You may want to use Tkinter {needs X :(}
#!/usr/bin/env python
from Tkinter import * # needs python-tk
root = Tk()
def hello(*ignore):
print 'Hello World'
root.bind('<Control-r>', hello)
root.mainloop() # starts an X widget
This script prints Hello World to the console if you press ctrl+r
See also Tkinter keybindings. Another solution uses GTK can be found here
in a for loop sleep 3500 times for 1 second checking if a key was pressed each time
# sleep for 3500 seconds unless ctrl+r is pressed
for i in range(3500):
time.sleep(1)
# check if ctrl+r is pressed
# if pressed -> do something
# otherwise go back to sleep

Categories

Resources