Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for interactive shell in a Python script

I need to determine whether the shell which invoked my Python script was in interactive mode or not. If it was in interactive mode, the program should pipe output to less(1) for easy reading. If not, it should simply print its output to stdout, to allow it to be piped away to a printer, file, or a different pager.

In a shell script, I would have checked if the prompt variable $PS1 was defined, or looked for the -i option among the flags stored in the $- variable.

What is the preferred method for testing interactivity from within Python?

like image 467
jforberg Avatar asked May 24 '11 09:05

jforberg


People also ask

How do I know if I have an interactive shell?

If a script needs to test whether it is running in an interactive shell, it is simply a matter of finding whether the prompt variable, $PS1 is set. (If the user is being prompted for input, then the script needs to display a prompt.) Alternatively, the script can test for the presence of option "i" in the $- flag.

How do I get interactive shell in Python?

It is also known as REPL (Read, Evaluate, Print, Loop), where it reads the command, evaluates the command, prints the result, and loop it back to read the command again. To run the Python Shell, open the command prompt or power shell on Windows and terminal window on mac, write python and press enter.

What is interactive Python shell in Python?

The Python interactive console (also called the Python interpreter or Python shell) provides programmers with a quick way to execute commands and try out or test code without creating a file.

How do I run interactive mode in Python?

A widely used way to run Python code is through an interactive session. To start a Python interactive session, just open a command-line or terminal and then type in python , or python3 depending on your Python installation, and then hit Enter .


2 Answers

This is often works well enough

import os, sys if os.isatty(sys.stdout.fileno()):     ... 
like image 126
John La Rooy Avatar answered Sep 21 '22 13:09

John La Rooy


From this link you can use the same way and test if stdin is associated to a terminate(tty), you can do this using os.isatty(), example:

>>> os.isatty(0) True 

N.B: From the same link this will fails when you invoke the command remotely via ssh, the solution given is to test if stdin is associated to a pipe.

like image 22
mouad Avatar answered Sep 23 '22 13:09

mouad