我正在使用gevent
及其Backdoor
功能。
这是我的代码的简化版本:
from gevent import backdoor, event
class App(object):
def __init__(self):
self.stop_event = event.Event()
self.servers = []
self.servers.append(backdoor.BackdoorServer((localhost, 6666))
# There is a tcp stream server using gevent configured too
def start(self):
for server in self.servers:
if not server.started:
server.start()
self.stop_event.wait()
for server in self.servers:
if server.started:
server.stop()
def run(*args, **kw):
app = App()
app.start()
在我run
console_scripts
创建的entry_points
中调用setup.py
方法
我想使用我的后门检查app
函数中的run
变量本地。
我连接到后门,并运行命令inspect.stack()
。这就是我得到的:
[
(<frame object at 0x7fa49ea0b3a0>, '<console>', 1, '<module>', None, None),
(<frame object at 0x7fa49ce727f0>, '/usr/lib/python2.7/code.py', 103, 'runcode', [' exec code in self.locals\n'], 0),
(<frame object at 0x7fa49ce70250>, '/usr/lib/python2.7/code.py', 87, 'runsource', [' self.runcode(code)\n'], 0),
(<frame object at 0x7fa49ced7d38>, '/usr/lib/python2.7/code.py', 265, 'push', [' more = self.runsource(source, self.filename)\n'], 0),
(<frame object at 0x3569a40>, '/usr/lib/python2.7/code.py', 243, 'interact', [' more = self.push(line)\n'], 0),
(<frame object at 0x7fa49ced39b0>, 'path_to_project/venv/local/lib/python2.7/site-packages/gevent-1.0.2-py2.7-linux-x86_64.egg/gevent/backdoor.py', 75, '_run', [' console.interact(banner=self.banner)\n'], 0),
(<frame object at 0x7fa49ced3b90>, 'path_to_project/venv/local/lib/python2.7/site-packages/gevent-1.0.2-py2.7-linux-x86_64.egg/gevent/greenlet.py', 327, 'run', [' result = self._run(*self.args, **self.kwargs)\n'], 0)
]
正如您所看到的,似乎gevent正在重写堆栈。我的模块中启动程序的run
函数不在其中。它停止在执行后门的greenlet的run方法。
有没有办法访问已启动程序的正在运行的run
方法,以便检查它并访问其本地app
变量?
答案 0 :(得分:1)
好的,我找到了解决方案。 greenlet
对象具有parent
属性,用于查找哪个对象生成了您当前正在查看的对象。然后greenlet有一个属性gr_frame
来存储堆栈跟踪。
所以在我的情况下,一旦我连接到后门服务器,它就会是这样的:
>>> import greenlet, inspect
>>> greenlet.getcurrent()
<SocketConsole at 0x7fca7122d190>
>>> greenlet.getcurrent().parent
<Hub at 0x7fca71560050 epoll default pending=0 ref=4 fileno=3 resolver=<gevent.resolver_thread.Resolver at 0x7fca7126a510 pool=<ThreadPool at 0x7fca7127fe10 0/1/10>> threadpool=<ThreadPool at 0x7fca7127fe10 0/1/10>>
>>> greenlet.getcurrent().parent.parent
<greenlet.greenlet object at 0x7fca7d9be690>
>>> inspect.getouterframes(greenlet.getcurrent().parent.parent.gr_frame)
[
...
(<frame object at 0x174ac40>, 'path_to_project/endpoints/app.py', 238, 'run', [' app.start()\n'], 0),
...
]
>>> inspect.getouterframes(greenlet.getcurrent().parent.parent.gr_frame)[4][0]
<frame object at 0x174ac40>
>>> inspect.getargvalues(inspect.getouterframes(greenlet.getcurrent().parent.parent.gr_frame)[4][0]).locals
{'args': [], 'app': <endpoints.app.App object at 0x7fca71360190>, 'kw': {}}
>>> inspect.getargvalues(inspect.getouterframes(greenlet.getcurrent().parent.parent.gr_frame)[4][0]).locals['app']
<endpoints.app.App object at 0x7fca71360190>
我有权访问正在运行的函数app
中的本地对象run
,以检查其他属性的值并调试我的实时gevent应用程序。