[英]How can I close a Python program properly when in an IDE?
From what I understand, using sys.exit is not compatible with PyCharm and other IDEs, yet other exit methods that don't do garbage collection are not recommended.据我了解,使用 sys.exit 与 PyCharm 和其他 IDE 不兼容,但不建议使用其他不进行垃圾回收的退出方法。 If I'm developing in PyCharm how can I properly shut down the program?如果我在 PyCharm 中开发,我该如何正确关闭程序?
In the below example I am attempting to use a hot key to exit the program, yet the test statement is never reached.在下面的示例中,我尝试使用热键退出程序,但从未到达测试语句。 Is this an incorrect syntax or related to using the wrong exit command?这是不正确的语法还是与使用错误的退出命令有关?
#Import modules
from tkinter import * #For images
from PIL import Image, ImageTk #For images
import os #For working directory
from pynput import keyboard #For hotkeys
#Set default directory
os.chdir('C:\\Users\\UserName\\Desktop\\Python\\SomeFolderName')
#Display Menu
root = Tk()
image = Image.open('menu.png')
display = ImageTk.PhotoImage(image)
root.overrideredirect(True) #Remove toolbar
label = Label(root, image=display)
label.pack()
root.mainloop()
#Functions
def ExitProgram():
print('test')
sys.exit(0)
#Define hotkeys
with keyboard.GlobalHotKeys({
'<ctrl>+w': ExitProgram,
'<ctrl>+0': ExitProgram}) as h:
h.join()
Use the quit()
function to exit the program.使用quit()
function 退出程序。 This is a built-in function from Python in order to exit the program.这是来自 Python 的内置 function 以退出程序。
Happy Coding!快乐编码!
This answer from a similar question might be a useful answer for you. This answer from a similar question可能对您有用。
Python exit commands - why so many and when should each be used? Python 退出命令 - 为什么要使用这么多以及何时使用?
I actually use VS code and sys.exit(0)
is fine, but can also use quit()
which is also fine.我实际上使用 VS 代码和sys.exit(0)
很好,但也可以使用quit()
也很好。
Use quit()
or exit()
to terminate your program.使用quit()
或exit()
来终止您的程序。 quit()
and exit()
are synonymous and do the exact same thing. quit()
和exit()
是同义词,做的事情完全相同。
In addition to calling sys.exit()
, using quit()
does some other internal cleanup, such as closing input streams.除了调用sys.exit()
之外,使用quit()
还可以进行其他一些内部清理,例如关闭输入流。
They are briefly discussed in the official documentation here: https://docs.python.org/3/library/constants.html#quit它们在这里的官方文档中进行了简要讨论: https://docs.python.org/3/library/constants.html#quit
Nothing past root.mainloop()
will execute because it never returns. root.mainloop()
任何内容都不会执行,因为它永远不会返回。 Move the with keyboard
... code before root.mainloop()
.在root.mainloop()
之前移动with keyboard
... 代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.