search

Home  >  Q&A  >  body text

python2.7 - python【多进程】关于进程的变量的问题

PHPzPHPz2892 days ago319

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-04-18 09:30:25

    Python’s variable scope problem. The interpreter treats you run_proc里的 gcc as a new variable.

    On print 前添加 global gcc.

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    from multiprocessing import Process
    import os
    
    gcc='parent'
    
    # 子进程要执行的代码
    def run_proc(name):
        global gcc
    ####################################
        print 'Son Process:',gcc
    ####################################
        gcc='son'
        print 'Son Process:',gcc
    
    if __name__=='__main__':
        p = Process(target=run_proc, args=('test',))
        p.start()
        p.join()
        print 'Parent Process:',gcc
        

    You can get the desired results.

    By the way, remember to write the error message in the question next time you ask a question.

    Supplement: If you delete gcc='son'这句,不加 global 也能跑通,这是因为 gcc='son' 同时也被 Python 当作了对函数内局部变量的声明语句。
    原来的代码相当于你先用了 gcc this local variable and declare it later, an error will occur. If you remove this sentence, the Python interpreter will think that you are using global variables instead of local variables.

    reply
    0
  • 迷茫

    迷茫2017-04-18 09:30:25

    Your gcc variable is defined outside the function, but you call it inside the function, so you will get the following error

    UnboundLocalError: local variable 'gcc' referenced before assignment

    You can change the code to this and try again.

    import os
    from multiprocessing import Process
    
    gcc = 'parent'
    
    def run_proc(name):
            global gcc
            print 'Son Process:',gcc
            gcc = 'son'
            print 'Son Process:',gcc
    
    if __name__ == '__main__':
            p = Process(target=run_proc, args=('test',))
            p.start()
            p.join()
            print 'Parent Process:',gcc

    I got the following running results:

    python $python q.py 
    Son Process: parent
    Son Process: son
    Parent Process: parent

    reply
    0
  • Cancelreply