简体   繁体   中英

Quit function in python program

I have a program that runs in Python, without the console present (which is to say, I've compiled it using py2exe). I want people to be able to quit from the main menu, or by a particular key-press in-game (say, Shift+Q). I'm running it, for now, in Windows, though I am working on compiling Linux/Mac versions. Pressing the X button works if there's no 'while' loop running, it seems, and that closes it correctly, otherwise it seems to 'store' the close command wait until the current loop is closed.

As for menu options, I've looked thoroughly through documentation and Stackoverflow and tried quit(), exit(), sys.exit() and every combination I can find, but every time I get:

Traceback (most recent call last):
  File "alphatime.pyw", line 61177, in <module>
  File "alphatime.pyw", line 53970, in place_menu
NameError: global name 'sys' is not defined

if I try sys.exit, and then:

Traceback (most recent call last):
  File "alphatime.pyw", line 61177, in <module>
  File "alphatime.pyw", line 53970, in place_menu
NameError: global name 'quit' is not defined

if I try just "quit()". I've heard about 'Raising' things like a need to close the program, but I'm not clear what that means (I'm new to Python) and how I would go about doing that.

So, my question is two-fold.

Firstly, is there something I can put in loops for recognizing keypresses something that will recognize the 'X' being clicked, and close?

Secondly, is there an appropriate command that will just close the program? I cannot figure out why these commands don't work, and I've had quite a few complaints from people using the program that it crashes, or they have to ctrl-alt-del it, or whatever. I believe

import os
try:
  os._exit(return_code)
except:
  pass

would work, but at this point, I'm not sure I'm competent enough at python to deploy it appropriately. Thanks in advance!

did you by any chance

import sys

because that should work!

NameError: global name 'sys' is not defined

Before you can use sys.exit() , you must import sys .

That's the best way to exit the program. Function names that begin with _ are considered internal, and should not be used unless you are really trying to do something weird.

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