[英]print doesn't work while in while loop with try/except (Windows!!!)
Not sure what's wrong here, function's not printing anything (tried '1' as argument i).不知道这里出了什么问题,函数没有打印任何东西(尝试 '1' 作为参数 i)。 I've seen an answer suggesting adding flush=True to print, but that doesn't solve the issue.
我看到了一个建议添加 flush=True 来打印的答案,但这并不能解决问题。 Any hints appreciated, More broadly - should I even be using the try/except framework if I want the function to be keyboard-controled?
任何提示表示赞赏,更广泛地说 - 如果我希望 function 由键盘控制,我什至应该使用 try/except 框架吗? or is there a better way?
或者,还有更好的方法?
def i_printer(i):
while True:
try:
if keyboard.is_pressed('q'):
break
except:
print(i)
time.sleep(3)
EDIT: using Windows, apparently keyboard doens't work with it, looking for different solution.编辑:使用 Windows,显然键盘无法使用它,正在寻找不同的解决方案。
Try and except blocks are used to handle exception. Try 和 except 块用于处理异常。 Since you are not going to face any error when clicking 'q', I don't think the usage of them is any good here.
由于单击“q”时不会遇到任何错误,因此我认为它们的使用在这里没有任何好处。 Just simple if statement would do the job.
只需简单的 if 语句就可以完成这项工作。
def i_printer(i):
while True:
if keyboard.is_pressed('q'):
break
print(i)
time.sleep(3)
EDIT: In case you wanna record keyboard press try this out.编辑:如果你想记录键盘按下试试这个。 The following code will record all the keys except 'q' and print recorded keys.
以下代码将记录除“q”之外的所有键并打印记录的键。
import keyboard
def i_printer():
rk = keyboard.record(until ='q')
return keyboard.play(rk, speed_factor = 1)
i_printer()
Got the ball rolling this way, with a generator function and an iterator (using windows, not linux):以这种方式滚动,使用生成器 function 和迭代器(使用 windows,而不是 linux):
import keyboard
import time
def printer():
while True:
yield '1'
time.sleep(1)
def iterator():
for i in aaa():
if keyboard.is_pressed('q'):
break
else:
print(i)
iterator()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.