Date Wed 24 October 2012 Category geeky. Tags python network

Update 18. Nov 2012: Cleaned up some comments about cores. To make it clear, this will only run on 1 core!

Threading in Python can be confusing in the beginning. Many examples out there are overly complicated so here is another example that I have tried to keep simple.

Here, I want a fast way to ping every host/ip in a list. As fast as we can, threaded, and then at last return a dict with two items. A list of dead nodes, and a list of nodes who answers on ping.

Example:

In [ 1 ]: from pinger import Pinger In [ 2 ]: ping = Pinger () In [ 3 ]: ping . thread_count = 8 In [ 4 ]: ping . hosts = [ '10.0.0.1' , '10.0.0.255' , '10.0.0.100' , 'google.com' , 'nonexisting' , '*not able to ping!*' , '8.8.8.8' ] In [ 5 ]: ping . start () Out [ 5 ]: { 'alive' : [ '10.0.0.255' , '10.0.0.1' , 'google.com' , '8.8.8.8' ], 'dead' : [ '*not able to ping!*' , 'nonexisting' , '10.0.0.100' ]}

The example above will ping 8 hosts at the time and saving the results to the end. We are using 8 thread_count in this example. Which means that python will have 8 ping command running at the same time.

The whole source of the Pinger class looks like this, read the comments and you will see how it works: