[英]Tell Python to wait/pause a 'for' loop
我有一个 Python 程序,它使用我定义为 nav(a, b) 的函数将我导航到一个网站,在这个网站上,我将下载一些 pyfits 数据以用于另一个脚本。 对于我拥有的目录中的每组 (a,b),该站点都有一个不同的 pyfits 文件。
我想知道我是否可以使用for
循环遍历这个目录,每次使用 nav(a, b) 函数时,告诉 python 在我下载文件时暂停,然后在我告诉它时再次恢复。 我以前在IDL 中做过类似的事情,但不知道如何使用 Python。
否则我想我会被困在运行程序 200 次,每次都替换 (a, b) 值,这将永远持续下去。
如果要等待手动信号继续,请等待用户按Enter :
蟒蛇2:
raw_input("Press Enter to continue...")
蟒蛇3:
input("Press Enter to continue...")
如果您可以下载 python 代码中的文件,请执行此操作,而不是为每个文件执行手动任务。
您可以使用time.sleep()暂停执行 t 秒:
import time
time.sleep(1.3) # Seconds
演示:
import time
print "Start Time: %s" % time.ctime()
time.sleep(5)
print "End Time: %s" % time.ctime()
Start Time: Tue Feb 17 10:19:18 2009
End Time: Tue Feb 17 10:19:23 2009
使用while
循环,等待下载完成:
for ... :
nav(a,b)
while downloading_not_finished:
time.sleep(X)
因此,每 X 时间段测试一个条件,并再次测试,直到下载部分完成。
好的,这里有两种在 Python 中暂停的方法。
您可以使用输入功能。
# Python 2 raw_input("Downloading....") # Python 3 input("Downloading....")
这将暂停程序,直到用户按下Enter等。
您可以使用 time.sleep() 函数。
import time time.sleep(number of seconds)
这将使 Python 脚本暂停您想要的任何秒数。
对于设计中的Python shell :
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)
对于控制台中的 Python:
from time import sleep
print('Downloading')
sleep(1)
print('Saving Files')
sleep(1)
使用输入功能。 它将暂停程序,直到提示已关闭/填写。
最好的解决方案是在现有的 while 循环中放置另一个 while 循环:
while True:
#do something
asleep = True
while (asleep):
if cv2.waitKey(1) == 32: #Wait for space key
asleep = False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.