Tell Python to wait/pause a 'for' loop - python

I have a Python program that navigates me to a website with a function that I have defined as nav(a, b), and on this site I will be downloading some pyfits data for use on another script. This site has a different pyfits file for every set of (a,b) in a catalog I have.
I was wondering if I could iterate through this catalog using a for loop, and each time the nav(a, b) function is used, tell python to pause while I download the file, then resume again when I tell it to. I've done something like this in IDL before, but don’t know how with Python.
Otherwise I guess I'm stuck running the program 200 times, replacing the (a, b) values each time, which will take for ever.

If you want to wait for a manual signal to continue, wait for the user to press Enter:
Python 2:
raw_input("Press Enter to continue...")
Python 3:
input("Press Enter to continue...")
If you can download the file in the python code, do that instead of doing the manual task for each of the files.

You can use time.sleep() to pause the execution for t seconds:
import time
time.sleep(1.3) # Seconds
Demo:
import time
print "Start Time: %s" % time.ctime()
time.sleep(5)
print "End Time: %s" % time.ctime()
Output
Start Time: Tue Feb 17 10:19:18 2009
End Time: Tue Feb 17 10:19:23 2009

Use a while loop, waiting for your download to finish:
for ... :
nav(a,b)
while downloading_not_finished:
time.sleep(X)
So, every X period of time a condition is tested, and is tested again until the downloading part is finished.

Okay, here are two ways to pause in Python.
You can use the input function.
# Python 2
raw_input("Downloading....")
# Python 3
input("Downloading....")
This will pause the program until the user presses Enter, etc.
You can use the time.sleep() function.
import time
time.sleep(number of seconds)
This will pause the Python script for however many seconds you want.

For Python shell in design:
import sys
from time import sleep
try:
shell = sys.stdout.shell
except:
print('Run It In Shell')
dots = '........';
shell.write('Downloading')
sleep(0.5)
for dot in dots:
shell.write(dot)
sleep(0.1)
shell.write('\n')
sleep(0.4)
shell.write('Saving Files')
sleep(0.5)
for doot in dots:
shell.write(dot)
sleep(0.1)
shell.write('\n')
sleep(0.4)
For Python in a console:
from time import sleep
print('Downloading')
sleep(1)
print('Saving Files')
sleep(1)

Use the input function. It will pause the program until the prompt has been closed/filled in.

The best solution is to put another while loop inside the existing while loop:
while True:
#do something
asleep = True
while (asleep):
if cv2.waitKey(1) == 32: #Wait for space key
asleep = False

Related

How to Display Time (not static) in python?

Alright,the problem is i'm trying to build a personal assistant with my amateur skills.
I want to display the time which should be running and not be static.
This is what you wanted ? create a endless loop (Since you didn't mention in what situation the loop will end, I assume it will run infinitely until you manually end it) and print() with end='\r' (replace prev print) and pause and refresh every second
import time
import datetime
while True:
now = datetime.datetime.now()
print(f"Current Date and Time: {now} ", end='\r')
time.sleep(1)

Reading a file every 30 minutes in Python

As you see in the below code, it is possible to open a file in a directory and read it. now i want live_token read the file every 30 minutes and print it. Can anyone help me in this regard?
I found below code as scheduling to do a job but i don't know how to do needful modifications.
schedule.every(30).minutes.do()
Sorry if this question is so basic, I am so new with Python.
def read_key():
live_key_file_loc = r'C:\key.txt'
live_key_file = open(live_key_file_loc , 'r')
global key_token
time.sleep(6)
live_token=live_key_file.read()
print(live_token)
import time
sleep_time = 30 * 60 # Converting 30 minutes to seconds
def read_key():
live_key_file_loc = r'C:\key.txt'
live_key_file = open(live_key_file_loc, 'r')
global key_token
time.sleep(6)
live_token = live_key_file.read()
print(live_token)
while(True): # This loop runs forever! Feel free to add some conditions if you want!
# If you want to read first then wait for 30 minutes then use this-
read_key()
time.sleep(sleep_time)
# If you want to wait first then read use this-
time.sleep(sleep_time)
read_key()
#jonrsharpe is right. Refer to schedule usage. You should have a script which should keep running always to fetch the token every 30 minutes from the file. I have put below a script which should work for you. If you dont want to run this file in python always, look for implementing a scheduled job.
import schedule
import time
def read_key():
with open('C:\\key.txt' , 'r') as live_key_file_loc
live_token = live_key_file_loc.read()
print(live_token)
schedule.every(30).minutes.do(read_key)
while True:
schedule.run_pending()
time.sleep(1)
There are a few steps in this process.
Search for “Task Scheduler” and open Windows Task Scheduler GUI.
Go to Actions > Create Task…
Name your action.
Under the Actions tab, click New
Find your Python Path by entering where python in the command line. Copy the result and put it in the Program/Script input.
In the "Add arguments (optional)" box, put the name of your script. Ex. - in "C:\user\your_python_project_path\yourFile.py", put "yourFile.py".
In the "Start in (optional)" box, put the path to your script. Ex. - in "C:\user\your_python_project_path\yourFile.py", put "C:\user\your_python_project_path".
Click “OK”.
Go to “Triggers” > New and choose the repetition that you want.
For more details check this site -
https://www.jcchouinard.com/python-automation-using-task-scheduler/

Python: display dynamic information on user input

I would like to be able to receive command line input from user in a python script, and at the same time display to the user some dynamic information.
The user should be able to enter text, but this should not block the displaying of information.
My goal is to create a game, where I show users a countdown while they still have time to enter an answer.
Is this achievable?
Yeah. To create a countdown in the console, you could do something like this:
from time import sleep
for num in reversed(range(0,11)):
print(num)
sleep(1.0)
or
from time import sleep
time = 10
while time != 0:
print(time)
time = time - 1
sleep(1.0)
Either will countdown from 10 to 0 with a second in between each number. Since you might want the user to be able to enter answers as quickly or slowly as like before reaching 0... you might want to look into running two loops concurrently. this thread might be helpful for that. You'll want to figure out how to break out of both loops if the user gets the right answer (and have something come up that says they got the right answer) or if the user runs out of time.
Well sounded like an interesting thing to look into so I did, ran into a few problems pretty soon.
First, I was able to make a running counter but the problem is, since it is a loop, the next layer the counter loop will reset everything you've answered on the previous layer unless you've pressed enter to input answer(answer + enter , during that 1 second period).
if you are making reflex based thing that you only need to press single keys you might be able to succeed with my code by using module getch.
There were few modules that I could use for making the timer and program run at the same time, threading and multiprocessing(better results with threading).
It's basically a working thing if you just remove the counter function which adds the loop, but you won't see the timer.
Pygame might be a good thing to do this with, haven't used it myself but I'd presume so.
here is my code
import time
import threading
import os
timel = 5
def question():
q = input("",)
print(q)
if q == "2":
print("\nCorrect")
else:
exit("\nFalse, You lose!!")
def counter():
timel = 5
for i in range(0, timel):
print("How much is 1+1?", timel)
timel -= 1
time.sleep(1)
os.system("cls")
def timer(seconds):
time.sleep(seconds)
exit("\nTIMES UP, You lose!!")
def exit(msg):
print(msg)
os._exit(1)
def main():
thread = threading.Thread(target=timer, args=(int("{}".format(timel)),))
thread2 = threading.Thread(target=counter)
thread.start()
thread2.start()
question()
if __name__ == "__main__":
main()

How to pause and wait for command input in a Python script

Is it possible to have a script like the following in Python?
...
Pause
->
Wait for the user to execute some commands in the terminal (e.g.
to print the value of a variable, to import a library, or whatever).
The script will keep waiting if the user does not input anything.
->
Continue execution of the remaining part of the script
Essentially the script gives the control to the Python command line interpreter temporarily, and resume after the user somehow finishes that part.
What I come up with (inspired by the answer) is something like the following:
x = 1
i_cmd = 1
while True:
s = raw_input('Input [{0:d}] '.format(i_cmd))
i_cmd += 1
n = len(s)
if n > 0 and s.lower() == 'break'[0:n]:
break
exec(s)
print 'x = ', x
print 'I am out of the loop.'
if you are using Python 2.x: raw_input()
Python 3.x: input()
Example:
# Do some stuff in script
variable = raw_input('input something!: ')
# Do stuff with variable
The best way I know to do this is to use the pdb debugger. So put
import pdb
at the top of your program, and then use
pdb.set_trace()
for your "pause".
At the (Pdb) prompt you can enter commands such as
(Pdb) print 'x = ', x
and you can also step through code, though that's not your goal here. When you are done simply type
(Pdb) c
or any subset of the word 'continue', and the code will resume execution.
A nice easy introduction to the debugger as of Nov 2015 is at Debugging in Python, but there are of course many such sources if you google 'python debugger' or 'python pdb'.
Waiting for user input to 'proceed':
The input function will indeed stop execution of the script until a user does something. Here's an example showing how execution may be manually continued after reviewing pre-determined variables of interest:
var1 = "Interesting value to see"
print("My variable of interest is {}".format(var1))
key_pressed = input('Press ENTER to continue: ')
Proceed after waiting pre-defined time:
Another case I find to be helpful is to put in a delay, so that I can read previous outputs and decide to Ctrl + C if I want the script to terminate at a nice point, but continue if I do nothing.
import time.sleep
var2 = "Some value I want to see"
print("My variable of interest is {}".format(var2))
print("Sleeping for 5 seconds")
time.sleep(5) # Delay for 5 seconds
Actual Debugger for executable Command Line:
Please see answers above on using pdb for stepping through code
Reference: Python’s time.sleep() – Pause, Stop, Wait or Sleep your Python Code
I think you are looking for something like this:
import re
# Get user's name
name = raw_input("Please enter name: ")
# While name has incorrect characters
while re.search('[^a-zA-Z\n]',name):
# Print out an error
print("illegal name - Please use only letters")
# Ask for the name again (if it's incorrect, while loop starts again)
name = raw_input("Please enter name: ")
Simply use the input() function as follows:
# Code to be run before pause
input() # Waits for user to type any character and
# press Enter or just press Enter twice
# Code to be run after pause

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