Reputation: 157
How can I read (and put into new variable) data stored at specific memory address?
For instance I know that:
<nfqueue.queue; proxy of <Swig Object of type 'queue *' at 0xabd2b00> >
And I want to have data stored at 0xabd2b00 in new variable so that I can work and use all functionalities of the object. Let's assume that I don't have access to the original variable that created this object.
UPDATE: Above question has been answered so I update my question. Let's assume I have two python files: file1.py and file2.py
File1.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 ....
At some point thread new_thread is called.
File2.py:
kolejka = nfqueue.queue()
Here the queue is created, binded and opened. Then endless loop for listening is executed. The only way to end it is to unbind and close kolejka, but I want file1.py to do that as it is a "master" programme. How can I retrieve initialized kolejka from file to close queue properly after new_thread is done?
When I try:
from file2 import kolejka
The script executes all procedure of creating queue from the beginning (it hasn't been written as a function).
Upvotes: 3
Views: 3614
Reputation: 28934
You can't - there is no way to read data from a specific address. If you don't have (or can't retrieve) a reference to the object you're interested in, you're out of luck.
Besides, even if you could read data from a given address, that wouldn't help, since there would be no way for you to know which address to read from unless you have a reference to the original object. And then you wouldn't need to read raw data from memory in the first place.
There are ways to share memory between processes in Python (for example the multiprocessing module). However, this seems a bit overkill for your problem. Since you're starting the file2
process from within new_thread
, the easiest solution is probably to use the signal module to let new_thread
tell the file2
process to exit when the main program exits.
This allows file2.py
to perform any cleanup needed before shutting down, and it's also a clean solution since file1.py
doesn't need to know the details about how to shut down file2.py
, making your code more modular and easier to maintain.
def run(self):
...
child_process = subprocess.Popen(args, ...)
...
# time to quit - tell file2 to terminate
child_process.terminate()
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)
Upvotes: 4