V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
commoccoom
V2EX  ›  问与答

请教一个 Python 问题

  •  
  •   commoccoom · Dec 4, 2020 · 1212 views
    This topic created in 1981 days ago, the information mentioned may be changed or developed.
    import threading
    
    def f(dicts):
    	for key in dicts:
    		print (key,dicts[key])
    		
    dict1 = {'a':'b','c':'d'}
    
    ta = threading.Thread(target=f,kwargs=dict1)
    
    ta.start()
    

    为什么这里的f函数内无法使用for循环呢?

    6 replies    2020-12-04 14:23:08 +08:00
    sean10
        1
    sean10  
       Dec 4, 2020 via Android
    加个 ta.join()吧,应该是你主进程结束把还没打印的子进程干掉了
    sean10
        2
    sean10  
       Dec 4, 2020 via Android
    子线程
    Sylv
        3
    Sylv  
       Dec 4, 2020   ❤️ 1
    写法 1:
    ta = threading.Thread(target=f, args=(dict1,))

    写法 2:
    ta = threading.Thread(target=f, kwargs={'dicts': dict1})

    了解下 args / kwargs / 解包等概念。
    commoccoom
        4
    commoccoom  
    OP
       Dec 4, 2020
    @Sylv 可以了,非常感谢啊😁
    sean10
        5
    sean10  
       Dec 4, 2020 via Android
    翻了下,我刚才说的错了,无关项
    commoccoom
        6
    commoccoom  
    OP
       Dec 4, 2020
    @sean10 已经用 3L 的方法解决了啊😁
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1166 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 23:16 · PVG 07:16 · LAX 16:16 · JFK 19:16
    ♥ Do have faith in what you're doing.