我在计算机“A”上运行我的脚本。然后我通过我的脚本从计算机“B”连接到计算机“A”。我将消息发送到计算机“A”,我的脚本使用 exec()
指令运行它。
我想通过计算机“B”上的套接字查看在计算机“A”上执行我的消息的结果。
我尝试更改 sys.stdout = socket_response
但出现错误:“Socket 对象没有属性 write()”
那么,如何通过套接字连接将标准输出(用于 print
或 exec()
)从计算机“A”重定向到计算机“B”?
它将成为我脚本中的某种“python 解释器”。
抱歉,没有声誉我无法回答我自己的问题
感谢大家!
我使用一种简单的方法,@Torxed 建议我这样做。这是我的伪代码(这只是一个例子,不是我的真实脚本)
#-*-coding:utf-8-*-
import socket
import sys
class stdout_():
def __init__(self, sock_resp):
self.sock_resp = sock_resp
def write(self, mes):
self.sock_resp.send(mes)
MY_IP = 'localhost'
MY_PORT = 31337
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Start server")
old_out = sys.stdout
srv.bind((MY_IP, MY_PORT))
srv.listen(0)
sock_resp, addr_resp = srv.accept()
new_out = stdout_(sock_resp)
sys.stdout = new_out
#sys.stdout = sock_resp ### sock_object has no attribute 'write'
while 1:
try:
a = sock_resp.recv(1024)
exec(a)
except socket.timeout:
#print('server timeout!!' + '\n')
continue
我用 Putty 连接到脚本并发送“打印‘abc’”,然后我收到了答案‘abc’。
最佳答案
有 makefile
Python 套接字类中的函数:
socket.makefile(mode='r', buffering=None, *, encoding=None, errors=None, newline=None)
Return a file object associated with the socket. The exact returned type depends on the arguments given to makefile(). These arguments are interpreted the same way as by the built-in open() function.
Closing the file object won’t close the socket unless there are no remaining references to the socket. The socket must be in blocking mode; it can have a timeout, but the file object’s internal buffer may end up in a inconsistent state if a timeout occurs.
您可以在 Mark Lutz 的书 (chapter 12, "Making Sockets Look Like Files and Streams") 中阅读如何使用它。
书中的一个示例(想法很简单:使用 socket.makefile
从套接字创建一个文件对象,并将 sys.stdout
与之链接):
def redirectOut(port=port, host=host):
"""
connect caller's standard output stream to a socket for GUI to listen
start caller after listener started, else connect fails before accept
"""
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port)) # caller operates in client mode
file = sock.makefile('w') # file interface: text, buffered
sys.stdout = file # make prints go to sock.send
return sock # if caller needs to access it raw
关于Python。将标准输出重定向到套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21430245/