0

For Instance I have three functions and a single for loop in python and I want to execute all these functions sequentially for example on first iteration function 1 should be executed and on 2nd iteration function 2 and so on

The three functions are:

    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)))

and a for-loop

# 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

Now The Issue is I am using multiprocessing with all the above mentioned functions, How would I call them now to generate different arrival time

Scorpion_God
  • 1,499
  • 10
  • 15
M. Haris Azfar
  • 598
  • 6
  • 16
  • Python already has something similar to your `make_iterable` function: `iter` can take two arguments, in which case, it expects the first one to be a function and the second to be a sentinel value. It gives you an iterator over repeated calls to that function that ends when it returns the sentinel. You can adapt it to your case (an infinite iterator) by giving it a sentinel value the function can never return: `iter(lambda: random.uniform(0, 1), None)`. – lvc Apr 08 '14 at 08:29
  • @AlexThornton, please Look into the problem again. – M. Haris Azfar Apr 08 '14 at 08:40

2 Answers2

10

Just put the functions in an iterable and call them one at a time in a for loop:

for afunc in (func1, func2, func3, func4):
    afunc()
anon582847382
  • 19,907
  • 5
  • 54
  • 57
  • what afunc() will do here ? How does it will call them sequentially i.e. one at a time? – M. Haris Azfar Apr 08 '14 at 08:14
  • @M.HarisAzfar For each iteration, it represents one of your four functions, adding the brackets calls it correspondingly. – anon582847382 Apr 08 '14 at 08:16
  • Thorton, I need something else [link] http://stackoverflow.com/questions/22936330/executing-functions-sequentially-on-each-iteration-from-a-for-loop-and-in-the-me Kindly See this and answer – M. Haris Azfar Apr 08 '14 at 21:25
  • @M.HarisAzfar It's very unclear what you are asking there. When you are asking a question, please include a minimal example of example input and output, for instance. – anon582847382 Apr 09 '14 at 07:38
  • Thorton, In the first code I have mentioned all the functions I want to execute and their execution as well using the multiprocessing queues. But I don't want to call them where it was called in the first code anymore but now I want them to be called from the second code where I have mentioned (#Sequential Function Calling Here except for the executed one) but using the same multiprocessing queues – M. Haris Azfar Apr 09 '14 at 19:53
  • @Thorton, And I cannot skip mutiprocessing queues. Now please tell me How would I execute them with the second code using the same multiprocessing queues (keeping in mind the older issue which is to call them sequentially i.e. one at a time and execution of a single function on a single iteration). – M. Haris Azfar Apr 09 '14 at 19:54
3

You could put the functions in a list:

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

EDIT

What will it do?

>>> 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!

EDIT 2

Do you simply want the same thing except with 3 functions?

functions = [func1, func2, func3]
for i in xrange(count):
    functions[i%3]()
    #do the rest of your stuff here
Scorpion_God
  • 1,499
  • 10
  • 15
  • What it will do ? I didn't get it ? – M. Haris Azfar Apr 08 '14 at 08:13
  • I have also edited the question, Please have a look at it and kindly guide me. Thank You – M. Haris Azfar Apr 08 '14 at 09:11
  • @M.HarisAzfar What is it exactly that you want now? It is unclear from the question. – Scorpion_God Apr 08 '14 at 09:16
  • there are 3 functions generating different kinds of packets executing using multiprocessing and queue. I want to execute them with the same for loop of inter arrival time. – M. Haris Azfar Apr 08 '14 at 09:43
  • @M.HarisAzfar do you want the first function for the first iteration, the second function for the second iteration, and the third function for the third iteration? And wrapping around again so that the first function will be used for the fourth iteration? – Scorpion_God Apr 08 '14 at 09:45
  • yes but at the same position like function call should be at the same loop where I was mentioning at the start to get the inter arrival time – M. Haris Azfar Apr 08 '14 at 09:54
  • I have called these functions using the multiprocessing queues but I don't want it anymore. I want it the way I have been mentioning above i.e. function should now be called in the for loop of the inter-arrival time. Please Look at the code above that I have shared – M. Haris Azfar Apr 08 '14 at 10:02
  • @M.HarisAzfar can you please edit your second code example to clearly state exactly what you want done and where? – Scorpion_God Apr 08 '14 at 10:06
  • In the first code I have mentioned all the functions I want to execute and their execution as well using the multiprocessing queues. But I don't want to call them where it was called in the first code anymore but now I want them to be called from the second code where I have mentioned (#Sequential Function Calling Here except for the executed one) but using the same multiprocessing queues – M. Haris Azfar Apr 08 '14 at 10:19
  • And I cannot skip mutiprocessing queues. Now please tell me How would I execute them with the second code using the same multiprocessing queues (keeping in mind the older issue which is to call them sequentially i.e. one at a time and execution of a single function on a single iteration). – M. Haris Azfar Apr 08 '14 at 10:20
  • @M.HarisAzfar "Sequential function calling here" - call which functions? "Except for the executed one" - executed what? – Scorpion_God Apr 08 '14 at 10:22
  • call those functions which I have mentioned in the first code. And except for the executed ones means call one function on a single iteration than the second function on the second iteration. Kindly check the first code of functions associated with queues. – M. Haris Azfar Apr 08 '14 at 10:26
  • @M.HarisAzfar _how_ do you want to call the three functions defined in the first code snippet? – Scorpion_God Apr 08 '14 at 10:29
  • The same way I have been asking from the start i.e. I want them to execute from the for-loop of the second code snippet but how would I call them using the multiprocessing queues. – M. Haris Azfar Apr 08 '14 at 10:50