Python脚本循环将时间段分配给输入fi中的每一行

2024-05-14 00:18:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python脚本,它以urls列表作为输入,通过for循环运行。我想能够交错/随机排列urls的序列,并在1小时内运行它们。你知道吗

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


更新:

基于下面的帮助,我创建了这个脚本来测试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

我想做的是给每个字母随机分配一个时隙,例如a = 44 b = 57 c = 12 d = 30 e = 22 f = 48

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


Tags: 文件txt脚本url列表fortime字母
2条回答

从你的comment

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

编辑#1:

我想你的意思是这样的,用^{}

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:]来添加列表的其余值,然后使用time.sleep()来休眠剩余的时间。你知道吗


编辑#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()

相关问题 更多 >