【问题标题】:Executing different functions in a single for loop in python在python的一个for循环中执行不同的函数
【发布时间】:2014-04-08 08:00:28
【问题描述】:

例如,我在 python 中有三个函数和一个 for 循环,我想按顺序执行所有这些函数,例如在第一次迭代函数 1 应该执行,在第二次迭代函数 2 等等

三个功能分别是:

    from scapy.all import *
from random import randint
import threading
import time
from datetime import datetime
import multiprocessing
from itertools import count

#pktList = []
#pktsInt = 0

#def Packets():
# Generate packet
    #for run_no in range(0,1)
p = raw_input('Enter PACKETs to send: ')
pktsInt = int(p)
pkts = IP(src="10.0.0.1",dst="10.0.0.2")/TCP()/"GET /HTTP/1.0\r\n\r\n"/Raw(RandString(size=120))
#print pkts
pkts[TCP].flags = "UFP"
pktList = []    
for pktNum in range(0,pktsInt):
    pktList.extend(pkts)
    pktList[pktNum][TCP].dport = 80 
    #randint(1,65535) # Pkt has Ran PortNo.
    print pktList[pktNum].summary()
    #print len(pktList[pktNum])
    #wrpcap('tcp-packets.pcap',pktList[pktNum])
    #queue.put((run_no, pktsInt, pktsList))
# Send the list of packets send(pktList)
def send_http(queue): 
    for run_number in range(0,1): # this will run indefinitely, same as while True, must be killed to stop.
        start=datetime.now()
        print "\nStart Time: ", start
        start_time=time.time()
        send(pktList)
        end = datetime.now()
        print "\nEnd Time: ", end
        totalTime = time.time()-start_time
        totalBytes=(pktsInt*120)/totalTime
        #print totalBytes,"Seconds"
        queue.put((run_number, totalTime, totalBytes))

# Generate packet
pkts1 = IP(dst="10.0.0.2")/fuzz(UDP()/NTP(version=4))/Raw(RandString(size=120))
#print pkts
pkts1[UDP].flags = "UFP"

pktList1 = []
for pktNum1 in range(0,10):
    pktList1.extend(pkts1)
    pktList1[pktNum1][UDP].dport = randint(1,65535) # Pkt has Ran PortNo.
    print pktList1[pktNum1].summary()
    #print len(pktList1[pktNum1])
    #wrpcap('udp-packets.pcap',pktList1[pktNum1])

# Send the list of packets send(pktList)
def send_ntp(queue):
    for run_number in range(1,2): # this will run indefinitely, same as while True, must be killed to stop.
        start1 = datetime.now()
        print "\nStart Time: ", start1
        start_time1=time.time()
        send(pktList1)
        end1 = datetime.now()
        print "\nEnd Time: ", end1
        totalTime = time.time()-start_time1
        totalBytes=(10*120)/totalTime
        #print totalBytes,"Seconds"
        queue.put((run_number, totalTime, totalBytes))

# Generate packet
pkts2 = IP(src="10.0.0.1",dst="10.0.0.2")/TCP()/Raw(RandString(size=120))
#print pkts
pkts2[TCP].flags = "UFP"

pktList2 = []
for pktNum2 in range(0,5):
    pktList2.extend(pkts2)
    pktList2[pktNum2][TCP].dport = 25 # Pkt has Ran PortNo.
    print pktList2[pktNum2].summary()
    #print len(pktList2[pktNum2])
    #wrpcap('tcp-packets.pcap',pktList[pktNum])

def send_smtp(queue):
# Send the list of packets send(pktList)
    for run_number in range(2,3): # this will run indefinitely, same as while True, must be killed to stop.
        start2 = datetime.now()
        print "\n Start Time: ", start2
        start_time2=time.time()
        send(pktList2)
        totalTime = time.time()-start_time2
        end2 = datetime.now()
        print "\nEnd Time: ", end2
        totalBytes=(5*120)/totalTime
        #print totalBytes,"Seconds"
        queue.put((run_number, totalTime, totalBytes))
    #print pktList[0].summary()
    #start_time=time.time()
    #send(pktList2)
    #print pktList2[0].show()
    #print pktList2[0].show2()



q = multiprocessing.Queue()
#t1 = multiprocessing.Process(target=Packets)
t = multiprocessing.Process(target=send_http, args=(q, ))
p = multiprocessing.Process(target=send_ntp, args=(q, ))
r = multiprocessing.Process(target=send_smtp, args=(q, ))

#t1.start()
t.start()
time.sleep(12) # "Some interval of time"
p.start()
time.sleep(16)
r.start()


time.sleep(29)
if t.is_alive():
    t.terminate()
if p.is_alive():
    p.terminate()
if r.is_alive():
    r.terminate()


rates = []
while True: # This loop will pull all items out of the queue and display them.
    run = q.get()
    if not run: # When we reach the end of the queue, exit
        break
    run_number, total_time, total_bytes = run
    print "Run {run_number} took a total of {total_time}\
at an average rate of {total_bytes:.1f} B/s".format(run_number=run_number,
                                                    total_time=total_time,
                                                    total_bytes=total_bytes)
    rates.append(total_bytes)

print "Average rate of {0:.1f} B/s".format(sum(rates)/float(len(rates)))

还有一个for循环

# Make a function iterable, by repeatedly calling it.
def make_iterable(func, *args):
    try:
        while 1:
            yield func(*args)
    except:
        pass

uni_rand = make_iterable(random.uniform, 0, 1)

# A generator for inter-arrival times.
inter_arrival = ( -(1./a)*math.log(u) for u in uni_rand)

# Generate inter-arrival times, then sleep for that long.
inter_arrival_iter = iter(inter_arrival)
for i in xrange(count):
    inter_arrival_seconds = inter_arrival_iter.next() * 3600.
    print "Sleeping for %f seconds." % inter_arrival_seconds
    time.sleep(inter_arrival_seconds)
    #func1()
#Sequential Function Calling Here except for the executed one

现在的问题是我正在使用具有上述所有功能的多处理,我现在如何调用它们以生成不同的到达时间

【问题讨论】:

  • Python 已经有类似于你的make_iterable 函数的东西:iter 可以接受两个参数,在这种情况下,它期望第一个是函数,第二个是哨兵值。它为您提供了一个迭代器,用于重复调用该函数,该函数在它返回哨兵时结束。你可以通过给它一个函数永远不会返回的标记值来适应你的情况(一个无限迭代器):iter(lambda: random.uniform(0, 1), None)
  • @AlexThornton,请再次查看问题。

标签: python python-2.7 python-3.x scapy traffic


【解决方案1】:

只需将函数放在一个可迭代对象中,然后在 for 循环中一次调用它们:

for afunc in (func1, func2, func3, func4):
    afunc()

【讨论】:

  • afunc() 在这里会做什么?它如何按顺序调用它们,即一次调用一个?
  • @M.HarisAzfar 对于每次迭代,它代表您的四个函数之一,添加括号会相应地调用它。
  • Thorton,我需要别的东西 [link] stackoverflow.com/questions/22936330/… 请看这个并回答
  • @M.HarisAzfar 很不清楚你在问什么。例如,当您提出问题时,请提供一个最小的示例输入和输出示例。
  • Thorton,在第一个代码中,我提到了我想要执行的所有函数以及它们的执行以及使用多处理队列。但是我不想再在第一个代码中调用它们的地方调用它们,但现在我希望从我提到的第二个代码中调用它们(#Sequential Function Calling Here,除了执行的代码)但使用相同多处理队列
【解决方案2】:

你可以把函数放在一个列表中:

functions = [func1, func2, func3, func4]
for i in range(20):
    function = functions[i%4]

编辑

它会做什么?

>>> def func1():
        print('I am the first function!')
>>> def func2():
        print('I am the second function!')
>>> def func3():
        print('I am the third function!')
>>> def func4():
        print('I am the fourth function!')
>>> functions = [func1, func2, func3, func4]
>>> for i in range(10):
        function = functions[i%4]
        function()
I am the first function!
I am the second function!
I am the third function!
I am the fourth function!
I am the first function!
I am the second function!
I am the third function!
I am the fourth function!
I am the first function!
I am the second function!

编辑 2

除了 3 个功能之外,您只是想要相同的东西吗?

functions = [func1, func2, func3]
for i in xrange(count):
    functions[i%3]()
    #do the rest of your stuff here

【讨论】:

  • 它会做什么?没听懂?
  • 我也编辑了这个问题,请看一下并指导我。谢谢
  • @M.HarisAzfar 你现在到底想要什么?问题不清楚。
  • 有 3 个函数使用多处理和队列生成不同类型的数据包。我想用相同的到达时间循环来执行它们。
  • @M.HarisAzfar 你想要第一次迭代的第一个函数,第二次迭代的第二个函数,第三次迭代的第三个函数吗?并再次环绕,以便将第一个函数用于第四次迭代?
猜你喜欢
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-27
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多