title: Python. Redirect stdout to a socket
body: <p>I run my script on computer &quot;A&quot;. Then I connect to computer &quot;A&quot; from computer &quot;B&quot; through my script. I send my message to computer &quot;A&quot; and my script runs it with an <code>exec()</code> instruction.</p>
  <p>I want to see the result of executing my message on computer &quot;A&quot;, through a socket on computer &quot;B&quot;.</p>
  <p>I tried to change <code>sys.stdout = socket_response</code> but had a error: &quot;Socket object has no attribute write()&quot;</p>
  <p>So, how can I redirect standard output (for <code>print</code> or <code>exec()</code>) from computer &quot;A&quot; to computer &quot;B&quot; through socket connection?</p>
  <p>It will be some kind of 'python interpreter' into my script.</p>
  <p><strong>SORRY, I CAN'T ANSWER MY OWN QUESTION WITHOUT REPUTATION</strong></p>
  <p>Thanks to all!</p>
  <p>I use a simple way, which @Torxed advised me of. Here's my pseudo-code (it's just an example, not my real script)</p>
  <pre><code>    #-*-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(&quot;Start server&quot;)
  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
  </code></pre>
  <p>I connected to script with Putty and sent &quot;print 'abc'&quot; and then I received the answer 'abc'.</p>