Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Linux program, e.g. bash or python script, know how it was started: from command line or interactive GUI?

I want to do the following:

If the bash/python script is launched from a terminal, it shall do something such as printing an error message text. If the script is launched from GUI session like double-clicking from a file browser, it shall do something else, e.g. display a GUI message box.

like image 616
Michael Avatar asked Dec 01 '22 20:12

Michael


2 Answers

You can check to see whether stdin and stdout are connected to a terminal or not. When run from a GUI, generally stdin is not connected at all, and stdout is connected to a log file. When run from a terminal, both stdin and stdout will be connected to a terminal.

In Python:

import os
import sys

if os.isatty(sys.stdout.fileno()):
    # print error message text
else:
    # display GUI message

You should check that this will work for you, though, since it doesn't do precisely what you asked for. But it's the best thing that I can think of that doesn't depend on too much magic.

You should check that the DISPLAY environment variable is set before going with GUI code too, since it won't work without that.

Note that terminal users can still redirect stdin or stdout to /dev/null (for example) and this might cause your program to go with the GUI behaviour. So it's far from perfect.

Finally, even though I've given you an answer, please don't do this! It is confusing to users for a program's behaviour to change depending on how it was called.

like image 109
Robie Basak Avatar answered Dec 24 '22 00:12

Robie Basak


It can check the value of $DISPLAY to see whether or not it's running under X11, and $(tty) to see whether it's running on an interactive terminal. if [[ $DISPLAY ]] && ! tty; then chances are good you'd want to display a GUI popup.

like image 37
that other guy Avatar answered Dec 24 '22 00:12

that other guy