Python 脚本循环为输入文件中的每一行分配时间段

Python script loop to assign timeslot to each line in input file

我有一个 Python 脚本,它 运行 通过 for 循环将 urls 的列表作为输入。我希望能够在 1 小时内 stagger/randomise urls 和 运行 它们的顺序。

是否可以读取文件,为它们中的每一个分配一个以秒为单位的值,然后启动一个计数器,一旦计数器到达时间段,它就会触发文件中特定行的脚本?


更新:

根据下面的帮助,我创建了这个脚本来测试 num.txt 中有一个字母列表,我在 60 秒而不是 1 小时内测试了脚本。

f = open('num.txt')
url = f.readlines()
x=random.sample(xrange(60), 60)
i=0
for u in url:
time.sleep(x[i])
print time.strftime("%H:%M:%S"), u
i+=1
time.sleep(x[i])

输出为18:25:19 a 18:26:00 b 18:26:35 c 18:27:01 d 18:27:43 e 18:27:56 f

我想要做的是为每个字母分配一个时隙 运行domly 例如 a = 44 b = 57 c = 12 d = 30 e = 22 f = 48

因此,当脚本启动时,计数器开始以秒为单位计时,一旦满足分配给每个字母的时间,它们就会 运行 通过循环,因此例如 c 将 运行 在 12 秒时通过循环,e 在 22 秒时等等,这有意义吗?

来自你的

"I want to sleep all of them within a random period of 1 hour and run when that time is reached"

编辑#1:

我想你的意思是这样的,使用 time.sleep():

import time,random

x=random.sample(xrange(3600), 3600) #create randomly ordered list of size 3600 

i=0

for url in urls:
    time.sleep(x[i])   #sleep for a random value between (0 to 3600)
    i+=1               #increment 'i' by 1

time.sleep(sum(x[i:]))  #sum the rest of the values

解释:

基本上,random.sample() 创建一个 随机排序的 列表,其中包含 0-3600 之间的所有数字。然后,在 for 循环中,time.sleep() 为每次迭代获取列表的唯一值。所以对于第一次迭代,使用列表的第一个元素,对于第二次迭代,使用第二个元素等。

然后,执行for循环后,可以使用sum()和切片符号x[i:]来添加列表的其余值,然后使用[=14= 】 剩下的时间睡觉。


编辑#2:

对于更新后的示例,试试这个:

import random
import time

x=random.sample(xrange(60), 60) #create randomly ordered list of 1s with size 60  

d={}  #create empty dictionary                         
i=0

with open('data.txt') as f:
    for letter in f:
        letter=letter.rstrip()
        d[letter]=x[i]    #assign timeslots to letters
        i+=1

print d    #print dictionary 

j=1
with open('data.txt') as f:
    while j<=60:
        time.sleep(1)     #sleep for one second
        for key, value in d.items():  #check if the timeslots are reached
            if value == j:
                print key, j
        j+=1

如果你的num.txt文件是这样的:

a 
b 
c 
d 
e 
f

此代码将输出:

>>> 
{'a': 55, 'c': 37, 'b': 18, 'e': 23, 'd': 50, 'f': 33}
b 18
e 23
f 33
c 37
d 50
a 55

我不确定我是否理解问题, 为什么不首先将文件加载到列表中:

with open(fname) as f:
    content = f.readlines()