How can Linux program, e.g. bash or python script, know how it was started: from command line or interactive GUI?
Question: 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.


Answer: 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.

