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

前端 未结 11 1692
心在旅途
心在旅途 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:29

    If you run python IDLE then "pythonw.exe" is being used to run coding while when you run the command line "python.exe" is used to run coding. The python folder path can vary so you have to revert the path to the python folder. m = '\\' and m = m[0] is to get m to be '\' because of escaping.

    import sys
    a = sys.executable
    m = '\\'
    m = m[0]
    while True:
        b = len(a)
        c = a[(b - 1)]
        if c == m:
            break
        a = a[:(b - 1)]
    if sys.executable == a + 'pythonw.exe':
        print('Running in Python IDLE')
    else:
        print('Running in Command line')
    
    0 讨论(0)
  • 2020-12-15 04:30

    I don't think there's any reliable way to detect this (especially in a cross-platform manner). For example on OS X, when you double-click a .py file and it tuns with "Python Launcher", it runs in a terminal, identically to if you execute it manually.

    Although it may have other issues, you could package the script up with something like py2exe or Platypus, then you can have the double-clickable icon run a specific bit of code to differentiate (import mycode; mycode.main(gui = True) for example)

    0 讨论(0)
  • 2020-12-15 04:30

    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())
    
    0 讨论(0)
  • 2020-12-15 04:30

    My solution was to create command line scripts using setuptools. Here are a the relevant parts of myScript.py:

    def main(pause_on_error=False):
        if run():
            print("we're good!")
        else:
            print("an error occurred!")
            if pause_on_error:
                raw_input("\nPress Enter to close.")
            sys.exit(1)
    
    def run():
        pass  # run the program here
        return False  # or True if program runs successfully
    
    if __name__ == '__main__':
        main(pause_on_error=True)
    

    And the relevant parts of setup.py:

    setup(
    entry_points={
            'console_scripts': [
                'myScript = main:main',
            ]
        },
    )
    

    Now if I open myScript.py with the Python interpreter (on Windows), the console window waits for the user to press enter if an error occurs. On the command line, if I run 'myScript', the program will never wait for user input before closing.

    0 讨论(0)
  • 2020-12-15 04:34

    This is typically done manually/, I don't think there is an automatic way to do it that works for every case.

    You should add a --pause argument to your script that does the prompt for a key at the end.

    When the script is invoked from a command line by hand, then the user can add --pause if desired, but by default there won't be any wait.

    When the script is launched from an icon, the arguments in the icon should include the --pause, so that there is a wait. Unfortunately you will need to either document the use of this option so that the user knows that it needs to be added when creating an icon, or else, provide an icon creation function in your script that works for your target OS.

    0 讨论(0)
  • 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)?

    0 讨论(0)
提交回复
热议问题