所以我刚开始使用Tkinter在Linux上乱搞Python.我试图通过使用KeyboardInterrupt异常使Cntrl + C停止执行,但是当我按下它时,暂时没有任何反应.最终它"需要"并退出.一点点阅读表明这可能与线程或其他东西有关,但我对这些东西很新,我真的不知道从哪里开始.
#! /usr/bin/python
import sys
from Tkinter import *
try:
root = Tk()
root.mainloop()
except:
print "you pressed control c"
sys.exit(0)
Run Code Online (Sandbox Code Playgroud)
我不想成为只需要快速修复的菜鸟,所以如果你的答案就像指向正确的文档一样简单,那就太棒了.
所以我要做的是:
def interrupted(signum, stackframe):
log.warning('interrupted > Got signal: %s', signum)
menu.quitMenu = True # to stop my code
signal.signal(signal.SIGINT, interrupted) # Handle KeyboardInterrupt
Run Code Online (Sandbox Code Playgroud)
问题是,虽然菜单被通知它必须停止,并且很快就会这样做,但它现在无法做到,因为它被困在raw_input:
def askUser(self):
current_date = datetime.now().isoformat(' ')
choice = raw_input('%s > ' % current_date)
return choice
Run Code Online (Sandbox Code Playgroud)
因此,由于twisted正在删除默认的中断处理程序,raw_input因此不会停止.我仍然需要按enter后^C它停止.
如何强制raw_input停止,而不安装默认的中断处理程序,这是扭曲上下文中的问题来源(因为扭曲本身不会被期望中断)
我猜这个问题与之无关raw_input:任何采取无限时间(或超过预设限制)的函数都应该以某种方式中断.
这有可接受的扭曲模式吗?
这是完整的测试代码:
from datetime import datetime
class Menu:
def __init__(self):
self.quitMenu = False
def showMenu(self):
print '''
A) Do A …Run Code Online (Sandbox Code Playgroud) 我的代码使用raspberry pi时遇到问题.我刚开始使用python,所以我需要一些帮助.
这是代码:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
led1=22
led2=17
GPIO.setup(led1, GPIO.OUT)
GPIO.setup(led2, GPIO.OUT)
def blink():
GPIO.output(led1, 1)
time.sleep(1)
GPIO.output(led1, 0)
GPIO.output(led2, 1)
time.sleep(1)
GPIO.output(led2, 0)
while(blink):
blink()
try:
main()
except KeyboardInterrupt:
GPIO.cleanup()
Run Code Online (Sandbox Code Playgroud)
当我运行此错误时出现在控制台中:
RuntimeWarning:此频道已在使用中,无论如何都在继续.使用GPIO.setwarnings(False)禁用警告.GPIO.setup(led1,GPIO.OUT)和:
RuntimeWarning:此频道已在使用中,无论如何都在继续.使用GPIO.setwarnings(False)禁用警告.GPIO.setup(led2,GPIO.OUT)
如果我理解正确,该命令GPIO.cleanup()应重置GPIO端口的所有引脚并关闭LED.
但事实并非如此,其中一位领导仍然存在.
如何更改我的代码来解决此问题?
在pycharm中调试代码时,按Ctrl + C时,我的python try / except循环似乎不会触发键盘中断。我的代码如下所示:
numbers = []
loop = True
try:
# ===========SUBROUTINES==================
def help():
print("To view the list type 'view'"
"\n To add an item type 'add'"
"\n To remove an item type 'remove'"
"\n To exit type exit or Ctrl + c can be used at any time")
# =========SUBROUTENES END===============
while loop:
task = input("What do you want to do? Type \"help\" for help:- ")
if task == 'help':
help()
else:
print("Invalid return please try …Run Code Online (Sandbox Code Playgroud) 假设我要编写一个捕获KeyboardInterrupt异常的Python脚本,以便用户能够安全地使用Ctrl+ 终止C
但是,我无法将所有关键操作(如文件写入)放入catch块中,因为它依赖于局部变量并确保后续Ctrl+ C无论如何都不会破坏它.
使用带有empty(pass)try部分的try-catch块以及部件中的所有代码finally将这个片段定义为"原子,中断安全代码"并且可能不会在中途中断时,它是否有效并且是一种好习惯?
例:
try:
with open("file.txt", "w") as f:
for i in range(1000000):
# imagine something useful that takes very long instead
data = str(data ** (data ** data))
try:
pass
finally:
# ensure that this code is not interrupted to prevent file corruption:
f.write(data)
except KeyboardInterrupt:
print("User aborted, data created so far saved in file.txt")
exit(0)
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我不关心当前生成的数据字符串,即可以中断创建并且不会触发写入.但是一旦写入开始,就必须完成,这就是我想要确保的.此外,如果在finally子句中执行写入时发生异常(或KeyboardInterrupt)会发生什么?
python try-catch try-catch-finally keyboardinterrupt try-finally
我有一个用 PyO3 用 Rust 编写的 Python 库,它涉及一些昂贵的计算(单个函数调用最多 10 分钟)。从 Python 调用时如何中止执行?
Ctrl+C 好像只有在执行结束后才会处理,所以本质上是没有用的。
最小可重现示例:
# Cargo.toml
[package]
name = "wait"
version = "0.0.0"
authors = []
edition = "2018"
[lib]
name = "wait"
crate-type = ["cdylib"]
[dependencies.pyo3]
version = "0.10.1"
features = ["extension-module"]
Run Code Online (Sandbox Code Playgroud)
# Cargo.toml
[package]
name = "wait"
version = "0.0.0"
authors = []
edition = "2018"
[lib]
name = "wait"
crate-type = ["cdylib"]
[dependencies.pyo3]
version = "0.10.1"
features = ["extension-module"]
Run Code Online (Sandbox Code Playgroud)
// src/lib.rs
use pyo3::wrap_pyfunction;
#[pyfunction]
pub fn sleep() …Run Code Online (Sandbox Code Playgroud) 我想创建一个程序,该程序可以通过单击 PyCharm 中的停止按钮来终止脚本。我试过
from sys import exit
def handler(signal_received, frame):
# Handle any cleanup here
print('SIGINT or CTRL-C detected. Exiting gracefully')
exit(0)
if __name__ == '__main__':
signal(SIGINT, handler)
print('Running. Press CTRL-C to exit.')
while True:
# Do nothing and hog CPU forever until SIGINT received.
pass
Run Code Online (Sandbox Code Playgroud)
来自https://www.devdungeon.com/content/python-catch-sigint-ctrl-c。
我在 Mac 和 Windows 上都尝试过。在 Mac 上,PyCharm 的行为符合预期,当我单击停止按钮时,它会捕获 SIGINT。但在 Windows 上,我做了完全相同的事情,但它只是直接返回给我一个
Process finished with exit code -1. 我可以做些什么来改变以使 Windows 的行为与 Mac 上的行为相似吗?
任何帮助表示赞赏!
按下Ctrl + C时,我的while循环不会退出.它似乎忽略了我的KeyboardInterrupt异常.循环部分如下所示:
while True:
try:
if subprocess_cnt <= max_subprocess:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
notifier.stop()
break
else:
pass
except (KeyboardInterrupt, SystemExit):
print '\nkeyboardinterrupt found!'
print '\n...Program Stopped Manually!'
raise
Run Code Online (Sandbox Code Playgroud)
同样,我不确定问题是什么,但我的终端甚至从未打印过我的异常中的两个打印警报.有人能帮我解决这个问题吗?
python systemexit infinite-loop keyboardinterrupt try-except
请不要在阅读之前认为它是重复的,有很多关于multithreading和的问题keyboard interrupt,但我没有发现任何考虑os.system,它看起来很重要.
我有一个python脚本,它在工作线程中进行一些外部调用.我希望它退出,如果我按,ctrl+c但看起来主线程忽略它.
像这样的东西:
from threading import Thread
import sys
import os
def run(i):
while True:
os.system("sleep 10")
print i
def main():
threads=[]
try:
for i in range(0, 3):
threads.append(Thread(target=run, args=(i,)))
threads[i].daemon=True
threads[i].start()
for i in range(0, 3):
while True:
threads[i].join(10)
if not threads[i].isAlive():
break
except(KeyboardInterrupt, SystemExit):
sys.exit("Interrupted by ctrl+c\n")
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
出人意料的是,如果我改变它工作正常os.system("sleep 10")来time.sleep(10).
我解决了很多 Project Euler 编码问题,Python 是我的首选语言。许多程序通常需要很长时间才能完成,因此我正在努力实现一些有助于提供有关程序状态的诊断信息的东西:当发生时,KeyboardInterrupt我希望能够打印程序运行了多长时间以及一些信息帮助我弄清楚还需要多长时间。
问题是——KeyboardInterrupt当你击中时抓住Ctrl-C仍然为我退出程序......我认为这与这段代码的结构有很大关系,或者希望与Python中我还没有找到的东西有很大关系。
KeyboardInterrupt我希望我的代码在被捕获后立即在同一行恢复。
下面是此代码的示例:
try:
...
...
... #I interrupt code here and hopefully keep going!
...
...
except KeyboardInterrupt:
...
finally:
...
Run Code Online (Sandbox Code Playgroud)
我希望有人理解这样做的目的,并可以帮助我找到一种方法来做到这一点,或者解决这种从运行代码中调用中断的丑陋方法。
python ×10
pycharm ×2
try-except ×2
continue ×1
exception ×1
interrupt ×1
os.system ×1
pyo3 ×1
raspberry-pi ×1
rust ×1
signals ×1
systemexit ×1
tkinter ×1
try-catch ×1
try-finally ×1
twisted ×1