Skip to main content
AI Assist is now on Stack Overflow. Start a chat to get instant answers from across the network. Sign up to save and share your chats.

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

10
  • Hmm. Your demo seems to show the opposite of the claim in the end. You're re-directing Python's stdout into the buffer but the subprocess stdout is still going to the console. How is that useful? Am I missing something? Commented Aug 24, 2013 at 21:15
  • @GuySirton: the demo shows that subprocess stdout (when not explicitly directed to sys.stdout) goes to Python's stdout, not the python program's (sys.) stdout. Which I admit is an ... odd distinction. Is there a better way to phrase this? Commented Aug 24, 2013 at 21:17
  • 2
    +1, good explanation but it lacks the concrete code examples. Here's asyncio-based code that implements the "hard part" (it handles multiple pipes concurrently) in a portable way. You could compare it to the code that uses multiple threads (teed_call()) to do the same. Commented Sep 30, 2014 at 17:26
  • 1
    @SamirAguiar: I don't know of any good short summary, but it's pretty simple: at the POSIX OS level, "stdout" is simply "file descriptor #1". When you open a file, you get the next available fd, starting normally from 3 (because 0, 1, and 2 are stdin, stdout, stderr). If you then set up Python's sys.stdout to write to that—e.g., to fd 5 from your most recent open operation—and then fork and exec, the thing you exec is going to write to its fd#1. Unless you make special arrangements, their fd1 is your fd1, which is no longer your sys.stdout. Commented Apr 14, 2021 at 20:38
  • 1
    @SamirAguiar I think if you read the sys module's documentation it may help clarify it. I think the choice of names is unfortunate (confusing), but, e.g., sys.stdout is pretty much nothing more than "where the output of print will go." So, when you reassign it, you're not actually re-binding file descriptor 1 (which is what the subprocess sees). The sys.__stdout__ is "Python's actual stdout." Commented Nov 14, 2022 at 0:33