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.
Python’s variable scope problem. The interpreter treats you
run_proc
里的gcc
as a new variable.On
print
前添加global 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.Your
gcc
variable is defined outside the function, but you call it inside the function, so you will get the following errorYou can change the code to this and try again.
I got the following running results: