让Python在'for'循环中等待/暂停

16 投票
7 回答
115110 浏览
提问于 2025-04-18 11:01

我有一个Python程序,它可以带我去一个网站,这个网站上有我定义的一个函数叫做nav(a, b)。在这个网站上,我会下载一些pyfits数据,以便在另一个脚本中使用。这个网站为我手头的一个目录中的每一组(a, b)都有不同的pyfits文件。

我在想,能不能用一个for循环来遍历这个目录,每次调用nav(a, b)函数的时候,让Python暂停一下,等我下载完文件后再继续执行。我之前在IDL中做过类似的事情,但不知道在Python中怎么做。

否则的话,我想我就得把程序跑200遍,每次都替换(a, b)的值,这样会花费很长时间。

7 个回答

1

关于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)
3

好的,这里有两种在Python中暂停的方法。

  1. 你可以使用输入函数。

     # Python 2
     raw_input("Downloading....")
    
     # Python 3
     input("Downloading....")
    

这样程序会暂停,直到用户按下 Enter 键等。

  1. 你可以使用 time.sleep() 函数。

     import time
     time.sleep(number of seconds)
    

这个方法会让Python脚本暂停你想要的秒数。

10

使用一个 while 循环,等待你的下载完成:

for ... :
    nav(a,b)
    while downloading_not_finished:
         time.sleep(X)

这就是说,每隔一段时间就会检查一次条件,直到下载的部分完成为止。

13

你可以使用 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
20

如果你想等着手动信号再继续,可以等用户按下 Enter 键:

Python 2 的写法:

raw_input("Press Enter to continue...")

Python 3 的写法:

input("Press Enter to continue...")

如果你能在 Python 代码中下载文件,那就直接用代码来下载,而不是每个文件都手动去做。

撰写回答