Skip to content

Instantly share code, notes, and snippets.

@zed
Last active March 30, 2023 18:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zed/7454768 to your computer and use it in GitHub Desktop.
Save zed/7454768 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""Demo: use a socket as subprocesses stdin/stdout.
http://stackoverflow.com/a/19961290
"""
import socket
from contextlib import closing
from subprocess import Popen, PIPE
host = "stackoverflow.com"
with closing(socket.create_connection((host, 80))) as s:
# send request
Popen("cat", stdin=PIPE, stdout=s).communicate(
b"GET /questions/19961052 HTTP/1.1\r\n" +
"Host: {}\r\n".format(host).encode('ascii', 'strict') +
b"Connection: close\r\n\r\n")
# receive response
Popen("cat", stdin=s).wait()
s.shutdown(socket.SHUT_RDWR) # no more sends/receives
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment