1

我在 python 中有两个文件,proc1.py 和 proc2.py,两者都是一个生产者,多个消费者场景的实现。proc1 主要创建子进程。在每个子进程中,它调用 proc2。proc2 在其代码中也创建了子进程。从命令行执行时,proc2.py 可以正常工作。但是当从 proc1 调用时,我得到了错误

Traceback (most recent call last):
  File "./proc2.py", line 20, in proc2WorkerFunc
    elem = q.get(block = False)
  File "/usr/lib64/python2.6/multiprocessing/queues.py", line 103, in get
    if not self._poll(block and (deadline-time.time()) or 0.0):
IOError: [Errno 9] Bad file descriptor

我曾尝试在网上搜索,但到目前为止还没有任何线索。关于我做错了什么的任何想法?Proc1.py 是

def workerFunc(q):                                                                   
  while True:                                                                        
    try:
      elem = q.get(block = False)                                                    
      print elem
      subprocess.call(["./proc2.py"])                                                
      time.sleep(0.5)
    except Queue.Empty:
      print "Queue is empty"                                                         
      return                                                                         
    except:
      print "Exception happened"
      tb = traceback.format_exc()                                                    
      print tb                                                                       
      return                                                                         




if __name__ == '__main__':
  q = multiprocessing.Queue()                                                        
  for i  in range(1):                                                                
    q.put('Hello')                                                                   

  num_workers = 1                                                                    
  workers = []
  for i in range(num_workers):
    qWorker = multiprocessing.Process(target=workerFunc, args=(q,))                  
    qWorker.start()
    workers.append(qWorker)                                                          

  for worker in workers:                                                             
    worker.join()
  print "proc 1 has finished"

proc2.py:

def proc2WorkerFunc(q):
  while True:
    try:
      print q.qsize()
      elem = q.get(block = False)
      print elem
      time.sleep(0.5)
    except Queue.Empty:
      print "Queue is empty"
      return
    except:
      print "Exception happened"
      tb = traceback.format_exc()
      print tb
      return




if __name__ == '__main__':
  proc2Q = multiprocessing.Queue()
  for i  in range(100):
    proc2Q.put('World')

  num_workers = 10
  workers = []
  for i in range(num_workers):
    qWorker = multiprocessing.Process(target=proc2WorkerFunc, args=(proc2Q,))
    qWorker.start()
    workers.append(qWorker)

  for worker in workers:
    worker.join()
4

1 回答 1

0

不确定,但是由于您似乎在 linux 机器上运行 Python 2.6,并且代码对我有用(使用 Windows 机器和 Python 2.7.3),因此您可能会遇到这个错误

顺便说一句,您使用的是哪个 python 版本?

于 2012-06-11T11:25:28.480 回答