xzpjerry731
V2EX  ›  问与答

PY 在 Windows 下 Fork 之后在子进程执行一些操作要怎么做?

  •  
  •   xzpjerry731 · Oct 15, 2020 · 1805 views
    This topic created in 2233 days ago, the information mentioned may be changed or developed.

    下面这段代码在 Unix 平台可以输出

    (<function hook at 0x7fb4700730e0>,)
    func
    

    但是在 Windows 上就只打印 func 了,搜了一圈下来没有看到解决方法,故来求助。

    import multiprocessing.util
    
    
    def hook(*args):
        print (args)
    
    
    def func():
        print ('func')
    
    
    
    multiprocessing.util.register_after_fork(hook, hook)
    p = multiprocessing.Process(target=func)
    p.start()
    
    2 replies  •  2020-10-15 13:29:38 +08:00
    iConnect
    iConnect
    Oct 15, 2020 via Android
    1
    Windows 没有这个机制,所以和 Linux 表现出差异。
    xzpjerry731
    xzpjerry731
    OP
    Oct 15, 2020
    2
    我试了下,这样就可以了

    ···
    import multiprocessing.util


    def hook(*args):
    print (args)


    def func():
    print ('func')

    multiprocessing.util.register_after_fork(hook, hook)
    if __name__ == '__main__':
    p = multiprocessing.Process(target=func)
    p.start()
    ···
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2769 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 04:26 · PVG 12:26 · LAX 20:26 · JFK 23:26
    ♥ Do have faith in what you're doing.