简体   繁体   中英

How to end a python program while it is running?

I study python by myself. And i got a problem here.."The human player may also end the game by pressing the Control-D sequence at any time." How can i do this.what kind of function should i use? Thanks.

You could try sys.exit() :

import sys
...
sys.exit()

There is also a more standard exit() function (for which you don't need to import anything). However there is one notable difference between this and sys.exit() as noted in the documentation:

Since exit() ultimately "only" raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.

The basic logic here is to handle SIGQUIT keyboard interrupt. There are many kind of interrupts, Ctrl+C (SIGINT), Ctrl+D (SIGQUIT), etc. This SOF thread discusses catching Ctrl+C signal in python. Based on the same lines, its not hard to catch Ctrl+D. This python documentation provides more insights.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM