How to determine if Python script was run via command line?
Question: ## 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?


Answer: 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.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](http://code.google.com/p/procpy/) 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`)?

