python 两个脚本同时执行,并且 互相通信

有一个脚本必须主线程,因为调用singal

import sys, thread()ing, queue

if sys.version_info.major == 3:
    def execfile(filename, globals=None, locals=None):
        g = globals if globals is not None else __builtins__.globals()
        l = locals if locals is not None else __builtins__.locals()
        with open(filename) as f:
            code = compile(f.read(), filename, 'exec')
            exec(code, g, l)
            
            
if __name__ == '__main__':
    f1 = '/path/to/file1.py' # MainThread
    f2 = '/path/to/file2.py'
    
    # 将需要共享的变量放入全局变量字典,在f1和f2中可以直接使用q1和q2两个队列
    # f1向f2发送消息:
    #     f1: q1.put(something) 
    #     f2: q1.get()
    # f2向f1发送消息:
    #     f2: q2.put(something) 
    #     f1: q2.get()
    g = {'q1': queue.Queue(), 'q2': queue.Queue()}
    g.update(globals())
    
    thread = threading.Thread(target=execfile, args=(f2, ), kwargs={'globals':g})
    thread.start()
    execfile(f1, globals=g)
    thread.join()

追问

这个,python2.7中是怎么处理呢,我看需要version3

温馨提示:答案为网友推荐,仅供参考
相似回答