Python - 如何将全局变量传递给multiprocessing.Process? [英] Python - How to pass global variable to multiprocessing.Process?
问题描述
我需要在一段时间后终止一些进程,所以我已经使用了另一个进程来等待。但是,我认为新进程无法访问主进程中的全局变量。
代码:
import os
from subprocess import Popen,PIPE
import time
import multiprocessing
log_file = open('stdout.log','a')
log_file.flush()
err_file = open('stderr.log','a')
err_file.flush()
processes = []
$ b $ def处理():
printprocessing
全局进程
全局log_file
全局err_file
为范围内的我(0,5):
p = Popen(['java','-jar','C:\\ Users \\two\\Documents\\ test.jar'],stdout = log_file,stderr = err_file)#长时间运行
processes.append(p)
print len(进程)#返回5
def waiting_service ():
name = multiprocessing.current_process()。name
打印名称,'Starting'
全局进程
print len(进程)#返回0
time.sleep(2)
在范围内(0,5):
processes [i] .terminate()
打印名称,'Exiting'
if __name__ =='__main__':
processing()
service = multiprocessing.Process(name ='waiting_service',target = waiting_service )
service.start()
整个问题出现在Windows的Python中。 Windows for Python阻止了在函数中看到的全局变量。我已经切换到Linux,我的脚本工作正常。
特别感谢 @rchang 对他的评论:
当我测试它时,在两种情况下print语句都是5。有某种版本的版本不匹配?我在Linux内核3.13.0(Mint发行版)上用Python 2.7.6测试了它。
I need to terminate some processes after a while, so I've used sleeping another process for the waiting. But the new process doesn't have access to global variables from the main process I guess. How could I solve it please?
Code:
import os
from subprocess import Popen, PIPE
import time
import multiprocessing
log_file = open('stdout.log', 'a')
log_file.flush()
err_file = open('stderr.log', 'a')
err_file.flush()
processes = []
def processing():
print "processing"
global processes
global log_file
global err_file
for i in range(0, 5):
p = Popen(['java', '-jar', 'C:\\Users\\two\\Documents\\test.jar'], stdout=log_file, stderr=err_file) # something long running
processes.append(p)
print len(processes) # returns 5
def waiting_service():
name = multiprocessing.current_process().name
print name, 'Starting'
global processes
print len(processes) # returns 0
time.sleep(2)
for i in range(0, 5):
processes[i].terminate()
print name, 'Exiting'
if __name__ == '__main__':
processing()
service = multiprocessing.Process(name='waiting_service', target=waiting_service)
service.start()
The whole problem was in Windows' Python. Python for Windows is blocking global variables to be seen in functions. I've switched to linux and my script works OK.
Special thanks to @rchang for his comment:
When I tested it, in both cases the print statement came up with 5. Perhaps we have a version mismatch in some way? I tested it with Python 2.7.6 on Linux kernel 3.13.0 (Mint distribution).
这篇关于Python - 如何将全局变量传递给multiprocessing.Process?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!