Determine if Program is Run from terminal or from file explorer [duplicate]

Background

I would like my Python script to pause before exiting using something similar to:

raw_input("Press enter to close.")

but only if it is NOT run via command line. Command line programs shouldn't behave this way.

Question

Is there a way to determine if my Python script was invoked from the command line:

$ python myscript.py

verses double-clicking myscript.py to open it with the default interpreter in the OS?


If you're running it without a terminal, as when you click on "Run" in Nautilus, you can just check if it's attached to a tty:

import sys
if sys.stdin and sys.stdin.isatty():
    # running interactively
    print("running interactively")
else:
    with open('output','w') as f:
        f.write("running in the background!\n")

But, as ThomasK points out, you seem to be referring to running it in a terminal that closes just after the program finishes. I think there's no way to do what you want without a workaround; the program is running in a regular shell and attached to a terminal. The decision of exiting immediately is done just after it finishes with information it doesn't have readily available (the parameters passed to the executing shell or terminal).

You could go about examining the parent process information and detecting differences between the two kinds of invocations, but it's probably not worth it in most cases. Have you considered adding a command line parameter to your script (think --interactive)?


What I wanted was answered here: Determine if the program is called from a script in Python

You can just determine between "python" and "bash". This was already answered I think, but you can keep it short as well.

#!/usr/bin/python
# -*- coding: utf-8 -*-
import psutil
import os

ppid = os.getppid() # Get parent process id
print(psutil.Process(ppid).name())