Skip to content
Advertisement

Python. Redirect stdout to a socket

I run my script on computer “A”. Then I connect to computer “A” from computer “B” through my script. I send my message to computer “A” and my script runs it with an exec() instruction.

I want to see the result of executing my message on computer “A”, through a socket on computer “B”.

I tried to change sys.stdout = socket_response but had a error: “Socket object has no attribute write()”

So, how can I redirect standard output (for print or exec()) from computer “A” to computer “B” through socket connection?

It will be some kind of ‘python interpreter’ into my script.

SORRY, I CAN’T ANSWER MY OWN QUESTION WITHOUT REPUTATION

Thanks to all!

I use a simple way, which @Torxed advised me of. Here’s my pseudo-code (it’s just an example, not my real script)

JavaScript

I connected to script with Putty and sent “print ‘abc'” and then I received the answer ‘abc’.

Advertisement

Answer

There is the makefile function in Python’s socket class:

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.

You can read how to use it in Mark Lutz’s book (chapter 12, “Making Sockets Look Like Files and Streams”).

An example from the book (the idea is simple: make a file object from a socket with socket.makefile and link sys.stdout with it):

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement