subprocess.call(' pyro-ns')与threading.Lock同步

时间:2014-05-04 22:14:01

标签: python multithreading locking python-multithreading

我想通过函数subprocess.call()启动一个子进程,我希望主循环等到子进程启动

我想使用threading.Lock

  • 在subprocess.call()之前获取
  • 然后 尝试重新获取 (等等)
  • 在subprocess.call() (主循环解锁)后释放它

子进程必须作为守护进程运行,所以我把subprocess.call()放在一个线程中。

但它在subprocess.call()之后停止,我认为它只是在等待,因为pyro-ns是一个监听端口的守护进程。我怎么能这样做?

查看代码,它更容易:

self.__wait_pyroNS_lock=threading.Lock()
self.__logger.debug('i get wait_pyroNS_lock')
self.__wait_pyroNS_lock.acquire()

pyro_ns = threading.Thread(name='Pyro Name Server', target=self.__Pyro_NameServer, args=(self.__wait_pyroNS_lock,))
pyro_ns.setDaemon(True)

self.__logger.debug('starting thread def self.__Pyro_NameServer')
pyro_ns.start()

self.__wait_pyroNS_lock.acquire() # <--- MAIN LOOP WAITING HERE
self.__wait_pyroNS_lock.release()



def __Pyro_NameServer(self, wait_pyroNS_lock):

    try:
        self.__logger.debug('def __Pyro_NameServer')

        self.__logger.debug('starting pyro-ns')
        retcode = subprocess.call("pyro-ns", shell=True) # <--- THREAD STOPS HERE, it doesn't return, so i don't get any code and it's all locked.

        if retcode != 0:
            self.__logger.debug('command pyro-ns: fail, error code %d' % retcode)
            else:
                self.__logger.debug('pyro-ns has started')

            self.__logger.debug('releasing wait_pyroNS_lock')
            wait_pyroNS_lock.release() # <--- IT NEVER RUNS, it releases the lock, the main loop is unlocked

        except Exception as e:
            self.__logger.error('%s' % str(e))

1 个答案:

答案 0 :(得分:0)

我决定使用PyRO提供的API。

pyro_ns_object = Pyro.naming.NameServerStarter()
pyro_ns = threading.Thread(name='Pyro Name Server', target=self.__Pyro_NameServer, args=(pyro_ns_object,))
pyro_ns.setDaemon(True)
self.__logger.debug('start thread def self.__Pyro_NameServer')
pyro_ns.start()

while True:
    if pyro_ns_object.waitUntilStarted(timeout=0.1):
        break
    else:
        self.__logger.debug('waiting pyro-ns')


def __Pyro_NameServer(self, pyro_ns_object):

    try:
        self.__logger.debug('def __Pyro_NameServer')

        self.__logger.debug('starting pyro-ns')
        pyro_ns_object.start()

    except Exception as e:
        self.__logger.error('%s' % str(e))
        raise e