shijie xu
shijie xu

Reputation: 2097

Python hang on first import

I copied a partial Python script from a benchmark scripts and tried to execute it after making modifications. The problem is, it is hanging once it is started.

The Python script is:

# !/usr/bin/python

# =============================
# initialize & configure
# =============================
#import shlex
#import fnmatch
import os
import subprocess
import resource
import os, sys, cPickle, time, threading, signal

from errno import EEXIST
from os.path import join
from subprocess import Popen
#from domain import Record
from threading import Timer



def measure(commandline):

#   r,w = os.pipe()
   forkedPid = os.fork()

   if forkedPid: # read pickled measurements from the pipe

      print "Parent proc start and the child pid: ", forkedPid
 #     os.close(w); rPipe = os.fdopen(r); r = cPickle.Unpickler(rPipe)
 #     measurements = r.load()
 #     rPipe.close()
      os.waitpid(forkedPid,0)
      print "Parent proc end"
      return "------------"

   else: 
      # Sample thread will be destroyed when the forked process _exits
      class Sample(threading.Thread):

         def __init__(self,program):
            threading.Thread.__init__(self)
            self.setDaemon(1)
            self.timedout = False 
            self.p = program
            self.maxMem = 0
            self.childpids = None   
            self.start() 

         def run(self):
            try:              
               remaining = maxtime
               delay=0.01
               print "Start run deman thread: ", remaining, "delay", delay
               while remaining > 0:                                   
                  res = resource.getrusage(resource.RUSAGE_CHILDREN)

                  time.sleep(delay)                    
                  remaining -= delay
                  print "\n res: ",res, " and remaining is: ", remaining

               else:
                  self.timedout = True
                  os.kill(self.p, signal.SIGKILL) 
            except OSError, (e,err):
                print "Error ", err


      try:

         print "Child proc ", commandline

         # only write pickles to the pipe
       #  os.close(r); wPipe = os.fdopen(w, 'w'); w = cPickle.Pickler(wPipe)

         start = time.time()

         # print "commandLine: ", commandline, " remaining: ",remaining
         # spawn the program in a separate process
         p = Popen(commandline,stdout=outFile,stderr=errFile,stdin=inFile, shell=True)


         # start a thread to sample the program's resident memory use
         t = Sample( program = p.pid )
         print "Child ......"
         # wait for program exit status and resource usage
         rusage = os.wait3(0)
         print 'rusage: ', rusage
         elapsed = time.time() - start

       #  m.userSysTime = rusage[2][0] + rusage[2][1]
       #  m.maxMem = t.rusage
       #  m.cpuLoad = "%"
       #  m.elapsed = elapsed
         print "Child proc end"

      except KeyboardInterrupt:
          print "keyBordInterrupt..."
          os.kill(p.pid, signal.SIGKILL)

      except ZeroDivisionError, (e,err): 
          print " error ZeroDiv: "

      except (OSError,ValueError), (e,err):
          print " error ", e
      finally:
          print "Here is finally section. "
         #w.dump(m)
         # wPipe.close()

         # Sample thread will be destroyed when the forked process _exits
          os._exit(0)

if __name__ == '__main__':
    print "Start now...."
#measure("jruby  \/tmp/test.rb")

When I use ps -ef | grep MyAccount, I find the interpreter will hang on the first `import instruction:

  MyAccount    16934 16933  0 12:08 pts/19   00:00:00 import os

/tmp/test.rb is a one-line Ruby script (puts "hello"), and it should not caused any problem as it has been commented out.

I ran ps -ef | grep MyAccount for three mintues, and this one is ALWAYS there. Also, there is not any output in the console, where I expected to see Start now.....

Upvotes: 0

Views: 712

Answers (1)

running.t
running.t

Reputation: 5709

It's because your code is not interpreted as a Python script but as a Bash script.

The first line should be

#!/usr/bin/python

instead of

# !/usr/bin/python  

You can skip this line and simply run your program using

python <your_script.py>

instead of

./<your_script.py>

I also think you read the ps results incorrectly.

The last column of ps -ef is the name of the command, definatelly not a line of the script, and the first one, MyAccount, is the name of the user.

So this ps output means that process import os is hanging. There is an application called import in some Linux distributions, see man import. If you try to execute it from the shell:

$import os

it simply waits for input forever (until interupted), and that is what happened to you.

Upvotes: 3

Related Questions