gpt4 book ai didi

python - 如何在远程 shell 的上下文中对 pdb 进行 stdin/stdout 重定向?

转载 作者:行者123 更新时间:2023-12-04 13:27:31 27 4
gpt4 key购买 nike

我正在编写一个 web shell,在服务器端使用 ptpython、gevent 和 Flask,在客户端使用 xtermjs 和 websockets。
我要正常breakpoint() Python 工作的函数,使用 pdb .
我很高兴知道 Pdb类需要自定义stdinstdout ,但是我无法使事情正常工作:(
在 web shell 中,用户输入的内容通过 websocket 进入服务器进程:有一个监听 greenlet,它写入一个由 ptpython 读取的管道。
然后,ptpython 输出通过 websocket 发送。到目前为止一切顺利,效果很好。
现在与 pdb : 感谢 sys.breakpointhook我创建了一个自定义 Pdb实例,stdin 是一个管道,stdout 是另一个管道。我用心用gevent.fileobject.FileObjectPosix具有非阻塞的协作 I/O 流。我负责让用户输入写入
输入管道,我希望输出到另一个管道,因此我可以将其重定向到代码中适当的“标准输出”处理例程。
但是,在收到与 pdb 对应的第一条消息后提示,我被卡住了一切似乎都被阻止了。
我用以下代码重现了我的行为,任何帮助将不胜感激:

from pdb import Pdb as _Pdb
import gevent
from gevent.fileobject import FileObjectPosix as File
import io
import os
import sys
import socket

debugger = None


class GeventPdb(_Pdb):
def __init__(self, own_stdout):
self._stdout = own_stdout
r1, w1 = os.pipe()
r2, w2 = os.pipe()
self.r = File(r1)
self.w = File(w1, "w")
self.r2 = File(r2)
self.w2 = File(w2, "w")
super().__init__(stdin=self.r, stdout=self.w2)
self.stdout_handling = gevent.spawn(self.handle_stdout)

def send_text(self, txt):
# this should write to the 'stdin' pipe,
# thus provoking input reading from Pdb
print("WRITING TO PDB's STDIN")
self.w.write(txt.decode())

def handle_stdout(self):
# this should read what is written by Pdb
# to Pdb's stdout, to redirect it to our
# own stdout
while True:
print("BEFORE READING PDB's STDOUT")
char = self.r2.read(1)
print(f"WRITING TO CUSTOM STDOUT, stdout len is {len(self._stdout.getvalue())}")
self._stdout.write(char)

def test_func():
debugger.set_trace()

if __name__ == '__main__':
custom_stdout = io.StringIO() # this simulates a custom stdout pipe
debugger = GeventPdb(custom_stdout)

# the next socket is the server socket,
# for 'remote' operation
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', 4444))
s.listen(1)

print("Connect client to continue... The client is used to send commands to the debugger")
client, client_addr = s.accept()

def handle_client(client):
while True:
cmd = client.recv(1024)
if not cmd:
break
print("SENDING TEXT TO DEBUGGER...")
debugger.send_text(cmd)

gevent.spawn(handle_client, client)

print("now start a function which starts the debugger...")
print("we should see the pdb prompt")
test_func()
我运行了以下代码,然后通过 telnet localhost 4444 连接然后我可以看到我收到 pdb提示,然后我可以输入命令并按 [enter]: pdb的输入管道。它阻塞。
任何帮助,将不胜感激 !

最佳答案

你必须刷新你的写(除了猴子补丁):

    def send_text(self, txt):
# this should write to the 'stdin' pipe,
# thus provoking input reading from Pdb
print("WRITING TO PDB's STDIN")
self.w.write(txt.decode())
self.w.flush() # !!!

关于python - 如何在远程 shell 的上下文中对 pdb 进行 stdin/stdout 重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67269463/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com