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.
You can check to see whether
stdinandstdoutare connected to a terminal or not. When run from a GUI, generallystdinis not connected at all, andstdoutis connected to a log file. When run from a terminal, bothstdinandstdoutwill be connected to a terminal.In Python:
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
DISPLAYenvironment variable is set before going with GUI code too, since it won’t work without that.Note that terminal users can still redirect
stdinorstdoutto/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.