简体   繁体   English

在python进程之间共享资源

[英]Sharing resources between python processes

I am wanting to share multiple resources between multiple python scripts. 我想在多个python脚本之间共享多个资源。 Ideally what I am trying to do is run my main program. 理想情况下,我要做的是运行我的主程序。 It contains some script wide variables. 它包含一些脚本范围的变量。 I then want to fork off the exact same program into a new shell and give it access to my script wide variables. 然后我想将完全相同的程序分离到一个新的shell中,并让它访问我的脚本范围的变量。

I am looking into multiprocessing but I am not sure if another way would be better such as using pipes? 我正在研究多处理,但我不确定另一种方式是否会更好,例如使用管道?

You can use Value and Array from multiprocessing for shared memory across processes. 您可以使用multiprocessing ValueArray来跨进程共享内存。

Example from multiprocessing 's documentation : multiprocessing 文档的示例:

from multiprocessing import Process, Value, Array

def f(n, a):
    n.value = 3.1415927
    for i in range(len(a)):
        a[i] = -a[i]

if __name__ == '__main__':
    num = Value('d', 0.0)
    arr = Array('i', range(10))

    p = Process(target=f, args=(num, arr))
    p.start()
    p.join()

    print(num.value)
    print(arr[:])

will output: 将输出:

3.1415927
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM