import os
import sys
import os, select, sys, time
import string 
HUGE = 10000 
import INSTALLATION 

os.system("%s/bin/lamboot %s" % ( INSTALLATION.homedir,   sys.argv[2]))

# TOUT CA POUR CA DEBUT : LIRE COMBIEN DE LAMNODES ON A

rd, wr = os.pipe()   # Create the pipe
pid = os.fork()   # Create a new process
if pid:    # Parent code
 os.close(wr)   # The parent won't write the pipe
 fdlist=[rd]
 msgtot=""
 while fdlist <> []:
     (readable, writeable, oob) = select.select(fdlist, [], [])
     # writeable and oob will always be '[]' here, since we're
     # not waiting for them
     for f in readable:
      msg=os.read(f, HUGE)
      if msg <> '':
       if msg[-1:] == '\n': # This is always the case
        msg = msg[:-1] # Strip the newline
        msgtot=msgtot+msg
      else:   # Read zero bytes => child terminated
       os.close(f)
       fdlist.remove( f)
else:
    os.close(rd)   # The child won't read the pipe
    # Make sure the child won't read input intended for the parent:
    null = open('/dev/null')
    os.dup2(null.fileno(), sys.stdin.fileno())
    null.close()
    os.dup2(wr, sys.stdout.fileno())
    os.system("%s/bin/lamnodes" % INSTALLATION.homedir )
    sys.exit(0)   # Terminate the child process


print  msgtot
total_m=0
sl = string.split(msgtot,"\n")
for tok in sl:
  pos = string.rfind(tok,":")
  if(pos==-1):
    total_m=total_m+1
  else:
    nm = string.atoi(tok[pos+1:])
    total_m=total_m+nm
print " ON A  ", total_m , " MACHINES "

nm = total_m

# TOUT CA POUR CA FIN 



os.system("%s/mpirun -c %d %s/pyMPIppmxmlTens   %s/PACKAGES/%s/SOURCES/ppmxml/ppmxmlTens.py  %s" %(INSTALLATION.generic_wrappers_dir, nm, INSTALLATION.generic_wrappers_dir,  INSTALLATION.homedir,  INSTALLATION.version ,   sys.argv[1] ) )
os.system("%s/bin/lamhalt"%INSTALLATION.homedir )























