Reputation: 1255
I was writing a wrapper class for sockets so I could use it as a file-like object for piping into the stdin
and stdout
of a process created with subprocess.Popen()
.
def do_task():
global s #The socket
class sockIO():
def __init__(self, s):self.s=s
def write(self, m): self.s.send(m)
def read(self, n=None): return self.s.read() if n is None else self.s.read(n)
def fileno(self): return self.s.fileno()
#stdio=s.makefile('rw')
stdio=sockIO(s)
cmd = subprocess.Popen('cmd', shell=True,
stdout=stdio, stderr=stdio,
stdin=stdio)
I didn't use socket.makefile()
as it gives a io.UnsupportedOperation: fileno
error, but with my present code I'm getting the following error on Windows (works fine on Linux):
Traceback (most recent call last):
File "C:\Users\admin\Desktop\Projects\Python3\client.py", line 65, in <module>
main()
File "C:\Users\admin\Desktop\Projects\Python3\client.py", line 62, in main
receive_commands2()
File "C:\Users\admin\Desktop\Projects\Python3\client.py", line 57, in receive_commands2
stdin=stdio)
File "C:\Python3\lib\subprocess.py", line 914, in __init__
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
File "C:\Python3\lib\subprocess.py", line 1127, in _get_handles
p2cread = msvcrt.get_osfhandle(stdin.fileno())
OSError: [Errno 9] Bad file descriptor
Upvotes: 1
Views: 2044
Reputation: 1255
According to the Python documentation about socket.fileno()
, it is stated that this won't work in Windows. Quoting from Python Documentation:
socket.fileno()
Return the socket’s file descriptor (a small integer). This is useful with select.select().
Under Windows the small integer returned by this method cannot be used where a file descriptor can be used (such as
os.fdopen()
). Unix does not have this limitation.
Note:
The above code will work in Linux and other *nix systems.
Upvotes: 1