How to keep a Python script output window open?

前端 未结 23 2583
挽巷
挽巷 2020-11-22 10:54

I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can an

相关标签:
23条回答
  • 2020-11-22 11:12

    Start the script from already open cmd window or at the end of script add something like this, in Python 2:

     raw_input("Press enter to exit ;)")
    

    Or, in Python 3:

    input("Press enter to exit ;)")
    
    0 讨论(0)
  • 2020-11-22 11:17
    1. Go here and download and install Notepad++
    2. Go here and download and install Python 2.7 not 3.
    3. Start, Run Powershell. Enter the following. [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
    4. Close Powershell and reopen it.
    5. Make a directory for your programs. mkdir scripts
    6. Open that directory cd scripts
    7. In Notepad++, in a new file type: print "hello world"
    8. Save the file as hello.py
    9. Go back to powershell and make sure you are in the right directory by typing dir. You should see your file hello.py there.
    10. At the Powershell prompt type: python hello.py
    0 讨论(0)
  • 2020-11-22 11:18

    If you want to stay cmd-window open AND be in running-file directory this works at Windows 10:

    cmd /k cd /d $(CURRENT_DIRECTORY) && python $(FULL_CURRENT_PATH)
    
    0 讨论(0)
  • 2020-11-22 11:21

    In python 2 you can do it with: raw_input()

    >>print("Hello World!")    
    >>raw_input('Waiting a key...')
    

    In python 3 you can do it with: input()

    >>print("Hello world!")    
    >>input('Waiting a key...')
    

    Also, you can do it with the time.sleep(time)

    >>import time
    >>print("The program will close in 5 seconds")
    >>time.sleep(5)
    
    0 讨论(0)
  • 2020-11-22 11:22

    Using atexit, you can pause the program right when it exits. If an error/exception is the reason for the exit, it will pause after printing the stacktrace.

    import atexit
    
    # Python 2 should use `raw_input` instead of `input`
    atexit.register(input, 'Press Enter to continue...')
    

    In my program, I put the call to atexit.register in the except clause, so that it will only pause if something went wrong.

    if __name__ == "__main__":
        try:
            something_that_may_fail()
    
        except:
            # Register the pause.
            import atexit
            atexit.register(input, 'Press Enter to continue...')
    
            raise # Reraise the exception.
    
    0 讨论(0)
提交回复
热议问题