How to determine if Python script was run via command line?

前端 未结 11 1710
心在旅途
心在旅途 2020-12-15 03:58

Background

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

raw_input(\"Press enter to close.\")

but

11条回答
  •  臣服心动
    2020-12-15 04:35

    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 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)?

提交回复
热议问题