简体   繁体   English

Python-从内存中检索变量?

[英]Python - retrieving a variable from memory?

I have two python scripts that need to communicate large variables to one another: python1.py and python2.py. 我有两个需要相互传递大变量的python脚本:python1.py和python2.py。

Let's say python1.py is running and has created a list variable 'x' which is very large. 假设python1.py正在运行,并创建了一个非常大的列表变量'x'。 At the moment, I am saving (pickling) 'x' to the hard drive and then using subprocess to run python2.py which then loads up 'x' from the hard drive (I need to have two different python files because I am trying to parallelize a computation). 此刻,我将“ x”保存(提取)到硬盘驱动器,然后使用子进程运行python2.py,然后从硬盘驱动器加载“ x”(我需要有两个不同的python文件,因为我正在尝试并行计算)。

Is there an alternative, where I can call python2.py with an argument which is a pointer to memory, and then have python2.py create 'x' based on directly looking it up in the memory? 有没有一种选择,我可以用一个指向内存的指针的参数调用python2.py,然后让python2.py根据直接在内存中查找来创建“ x”?

If you are looking into splitting computation across processes, I would strongly recommend giving the "multiprocessing" module a read which has concepts like process pools, managers and ability to share high-level data structures across process boundaries. 如果您正在考虑跨进程拆分计算,强烈建议您阅读“多处理”模块,其中包含诸如进程池,管理器以及跨进程边界共享高级数据结构等概念。 For eg take a look at "sharing state between two processes" section in the docs. 例如,看一下文档中的“两个进程之间的共享状态”部分。 From the docs: 从文档:

from multiprocessing import Process, Array

def f(a):
    for i in range(len(a)):
        a[i] = -a[i]

if __name__ == '__main__':
    arr = Array('i', range(10))

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

    print(arr[:])

#output: [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

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

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