简体   繁体   中英

Can I get access to the code of an already executable Python script?

I run script test.py, for example, and accidentally change the executable file, but the script from this file continues to work. In the top I can see what executes "python3 test.py" but it is not quite right. Can I get access to the code that is executed after I changed it?

A possible way of recover the source code is using the tools pyrasite and inspect

Pyrasite is used to inject code into Python processes and inspect is used to retrieve the source code of modules, classes, methods, functions, tracebacks, frame objects, and code objects.

Eg Initial file: foobar.py

import time

def test1():
    print "test1"

if __name__ == "__main__":
    while (1):
        time.sleep(1)
        test1()

Run and modify the file (I changed the printed string by "test2"):

$ python foobar.py 
test1
test1
...

It still printing test1 and if you use pyrasite and inspect you can see the source code of the function that it is running.

$ pyrasite-shell 6243
Pyrasite Shell 2.0
Connected to 'python foobar.py'
Python 2.7.9 (default, Jun 29 2016, 13:08:31) 
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(DistantInteractiveConsole)

>>> import inspect
>>> inspect.getsource(test1)
'def test1():\n\tprint "test1"\n'

Also, It works if you deleted the file too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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