如何读取(并放入新变量)存储在特定内存地址的数据?
例如我知道:
<nfqueue.queue; proxy of <Swig Object of type 'queue *' at 0xabd2b00> >
我想将数据存储在新变量中的 0xabd2b00 处,以便我可以工作并使用该对象的所有功能。假设我无权访问创建此对象的原始变量。
更新: 上面的问题已经回答了,所以我更新我的问题。 假设我有两个 python 文件:file1.py 和 file2.py
文件 1.py:
.... rest of the code ....
class new_thread(threading.Thread):
def __init__(self, obj):
self.obj = obj
threading.Thread.__init__(self)
def run(self):
str = 'python file2.py'
args = shlex.split(str3)
tmp = subprocess.Popen(args, stdout=open('/dev/null','w'), stderr=open('/dev/null', 'w'))
.... rest of the code ....
在某个时候线程 new_thread 被调用。
文件2.py:
kolejka = nfqueue.queue()
此处创建、绑定(bind)和打开队列。然后执行监听的无限循环。结束它的唯一方法是解除绑定(bind)并关闭 kolejka,但我希望 file1.py 这样做,因为它是一个“主”程序。如何在 new_thread 完成后从文件中检索初始化的 kolejka 以正确关闭队列?
当我尝试时:
from file2 import kolejka
脚本从头开始执行创建队列的所有过程(没有写成函数)。
最佳答案
你不能 - 没有办法从特定地址读取数据。如果您没有(或无法检索到)对您感兴趣的对象的引用,那您就不走运了。
此外,即使您可以从给定地址读取数据,那也无济于事,因为除非您有对原始对象。这样一来,您就不需要从内存中读取原始数据。
更新——如何彻底终止子进程
有多种方法可以在 Python 中的进程之间共享内存(例如 multiprocessing 模块)。但是,这对您的问题来说似乎有点矫枉过正。由于您是从 new_thread
中启动 file2
进程,最简单的解决方案可能是使用 signal模块让 new_thread
在主程序退出时告诉 file2
进程退出。
这允许 file2.py
在关闭之前执行任何需要的清理,这也是一个干净的解决方案,因为 file1.py
不需要知道关于如何关闭 file2.py
,使您的代码更加模块化且更易于维护。
文件1.py
def run(self):
...
child_process = subprocess.Popen(args, ...)
...
# time to quit - tell file2 to terminate
child_process.terminate()
文件2.py
import signal
import sys
...
kolejka = nfqueue.queue()
...
def sigterm_handler(signum, frame):
# close kolejka and do any other cleanup needed, then do:
sys.exit()
# Make sure sigterm_handler() is run when file1.py tells us
# to quit using child_process.terminate()
signal.signal(signal.SIGTERM, sigterm_handler)
关于python - 从特定内存地址/对象引用读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4507496/