On Tue, 3 May 2022 at 11:14, Steven D'Aprano <st...@pearwood.info> wrote: > > On Mon, May 02, 2022 at 07:55:16PM -0000, sam.z.e...@gmail.com wrote: > > > Using the prospective redirect_stdin context manager, the following code > > > > ``` > > with open("/dev/tty", 'r+') as file: > > with contextlib.redirect_stdin(file), contextlib.redirect_stdout(file): > > name = input('Name: ') > > > > print(name) > > ``` > > > > Could be rewritten like this > > > > ``` > > with open('/dev/tty', 'r+') as file: > > name = input('Name: ', infile=file, outfile=file) > > > > print(name) > > ``` > > Thanks for the example, but that doesn't explain the why. Why are we > redirecting IO to a tty? Assume your audience is not made up of expert > Linux sys admins who even know what a tty is :-) > > (I know what a tty is, kinda, but I still don't know what the above > does.)
I can explain a bit of the why, although the most common use case is already covered by the getpass module. If your stdio streams are redirected, and you need to get some information from the user, opening the tty explicitly lets you do that. For example, let's say you run a command like "spam | ssh user@host | ham", and the ssh command needs to get credentials from you; it'll open /dev/tty, write a prompt to it, read a password from it, and then close it. But as mentioned, the obvious case of querying the user for credentials is much better handled by simply calling getpass (which has different handling on Windows, for instance). I'm sure there are other use cases for "write one prompt to tty, then read one line", but honestly, I would be fine with leaving input() as it is, and just using the context manager, since it would allow you to print multiple lines as well as reading a command. ChrisA _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/33TWW2VM2NRLZTXGWRSSVNET45CPXYW5/ Code of Conduct: http://python.org/psf/codeofconduct/