osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

if STREAM.isatty():


On 8/29/2019 10:16 AM, Eryk Sun wrote:
> On 8/29/19, Rhodri James <rhodri at kynesim.co.uk> wrote:
>>
>> "isatty()" is a method of the io.IOBase class that checks to see
>> if the stream is connected to a tty, or to use less jargon, if it is
>> interactive.  "tty" was I think originally an abbreviation for
>> "teletype", but nowadays it refers to any terminal, anywhere you
>> get a command line prompt.
> 
> In Windows, isatty() is true for any character-type file.

Does that mean one that can either send or receive data a character at a 
time, as opposed to a block at a time?

> This does
> not necessarily mean an interactive stream. In particular, NUL is a
> character device:
> 
>      C:\>python -c "import  sys;print(sys.stderr.isatty())" 2>NUL
>      True

Aha.  So this is why
https://pubs.opengroup.org/onlinepubs/009695399/functions/isatty.html
follows the doc for isatty, which says 'associated with a terminal 
device', with an information section that contradicts that with
"The isatty() function does not necessarily indicate that a human being 
is available for interaction via fildes. It is quite possible that 
non-terminal devices are connected to the communications line."

> But a pipe is not:
> 
>      C:\>python -c "import  sys;print(sys.stderr.isatty())" 2>&1 | more
>      False

What makes a pipe on Windows not a character file?  Is data sent between 
processes a block at a time?  Are posix pipes different?

https://stackoverflow.com/questions/1312922/detect-if-stdin-is-a-terminal-or-pipe

notes that 'cat | python' does not launch the REPL' and asks how to 
detect if connected to a pipe (or not a terminal).  I presume the system 
in not Windows. The answers include both isatty and a stat call.  For 
CPython, the answer is in the code.  On Windows, I got the following 
with one 'Enter' after 'NUL'
---
C:\Users\Terry>python 0<NUL
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 
64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>>
---
It appears that Python sees NUL as a tty, as you said, and the first 
read indicated EndOfFile, nearly the same as entering ^Z<enter>.

I don't understand the following.
---
C:\Users\Terry>python -c "print('hello\n') | python
hello

Traceback (most recent call last):
   File "<string>", line 1, in <module>
NameError: name 'python' is not defined
---
This illustrates that pipe input is not seen as a tty as python exits 
without a prompt.
---
C:\Users\Terry>py -c "print('''print('alpha')''')" | py
alpha

C:\Users\Terry>
---

-- 
Terry Jan Reedy