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

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

提交回复
热议问题