Subprocesses on Windows

Tim Golden mail at timgolden.me.uk
Wed Oct 3 11:24:02 CEST 2007


Nachiket Joshi wrote:
> Well before I explain my problem, let me tell you all that 
> I am not a professional programmer and new to python too.

Welcome to the world of Python, home to professional and
non-professional programmers alike!

> I just write some scripts as and when required 

Same could be said of many of us.

> The problem is something like this. 
> I am trying to run nmap scan on my network and for 
> that I want to start multiple nmap instances (256 at once)
> togather and wait till those 256 are over before I start 
> next lot of 256 instances. 

My number one query is whether it's a great idea to
have *256* nmap instances running simultaneously.
But this is not my area, so maybe it's something people
commonly do. Howbeit, it's clear from your description
below that the problem is running *some number* of
simultaneous processes.

 > Well to test I have put in two
> nmap scans in my program and I have succeeded to start 
> both of them simultaneously (in fact one after another) by using 
> "subprocess module and Popen".  But the problem is when I run a 
> loop to start both of these nmap instances, they do start BUT 
> the script then exits to command prompt completing all the executions. 
> But this is not what I want. I want to wait till both of these nmap 
> processes are finished and then only exit from script (in fact exit 
> from that function or loop). Then only I would be able to call next 
> lot of IP Ranges to scan. I did try os.waitpid() but it gives 
> following error while running the program:

I admit I'm a bit confused both by the description and by the
code (not least because the code you're posting isn't
self-contained; it's not clear what the all-important
clas_c function is doing).

Assuming I have a (fake) nmap.py which looks like this:

<nmap.py>
import sys
print sys.argv
</nmap.py>

then your code (if I understand it) wants to do this, in concept:

<code>
import os, sys
import subprocess

TEMPLATE = "192.168.%d.%d"
for network in range (256):
   raw_input ("Network: %s - Press enter..." % (TEMPLATE % (network, 0)))

   running_processes = []
   for machine in range (256):
     # start an nmap process which does whatever and returns
     running_processes.append (
       subprocess.Popen (["python", "nmap.py", TEMPLATE % (network, machine)])
     )

   # wait until all 256 nmap processes have finished
   # before starting the next network
   while True:
     for process in running_processes:
       if process.poll () is None:
         break
     else:
       break

</code>

Have I understood correctly? If you're not sure what my code
is doing, try saving it to two files and running it to see
if it gives the result you want.

TJG



More information about the Python-list mailing list