在python中的单个for循环中执行不同的函数

2024-06-28 11:28:20 发布

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

例如,我在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循环

^{pr2}$

现在的问题是,我正在对上述所有函数使用多处理,我现在如何调用它们来生成不同的到达时间


Tags: ofrunsendnumberfordatetimetimequeue
2条回答

您可以将函数放入列表中:

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

编辑

What will it do?

^{pr2}$

编辑2

除了3个函数,你是否只想要相同的东西?在

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

只需将函数放入iterable中,然后在for循环中一次调用一个:

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

相关问题 更多 >