Interactive scripts (back on topic for once) [was Re: The "loop and a half"]

Marko Rauhamaa marko at pacujo.net
Fri Oct 6 05:14:48 EDT 2017


Chris Angelico <rosuav at gmail.com>:

> On Fri, Oct 6, 2017 at 7:09 PM, Steve D'Aprano
> <steve+python at pearwood.info> wrote:
>> What are the right ways for a Python script to detect these sorts of
>> situations?
>>
>> (1) Standard input is coming from a pipe;
>> (2) Stdin is being read from a file;
>> (3) Stdin is coming from a human at a terminal;
>>
>> I get these. How did I do?
>>
>> # 3 detect a terminal, hopefully with a human typing at it
>> if os.isatty(0):
>>     print("Oy noddy, wake up and type something, I'm waiting for you!")
>
> This ought to be the only one that matters. It's the closest thing you
> have to "we're working in interactive mode". Generally speaking, you
> shouldn't care about the difference between a pipe and a file; and
> remember, you can have stdin be anything else, too (eg a Unix or TCP
> socket).

Generally, you shouldn't condition the program too much on such
environmental details, although it is done. For example, the "ls"
command outputs the directory listing in a (colorful) multi-column
format when stdout is a terminal and in a (b/w) one-file-per-line format
otherwise.

Since such guesswork often goes wrong, the program should provide
command-line options to specify the operating mode explicitly. The "ls"
command has "--color" and "--format". The "ssh" command has "-o
BatchMode=yes" and so on.

Again, the Unix way is to preferably stay silent by default. If you want
the program to chat, there is "--verbose".


Marko



More information about the Python-list mailing list