我正在用python编写程序,程序的一部分从文件中读取行并将其打印出来。但是,在打印时,如果我按一个随机键,则会出现KeyboardInterrupt错误。这是因为我尝试了一下,但没有例外,但是某些输出显示出我不想显示。这是我在主要功能内执行的代码:
for line in output.stdout:
line = str(line)
print(line)
这是我的代码,其中包含try和except。
if __name__ == '__main__':
try:
if os.path.exists('drop.json') == True:
drops()
except KeyboardInterrupt:
sys.stderr.close()
except (BrokenPipeError, IOError):
if os.path.exists('drop.txt') == True:
file = open("drop.txt","a+")
file.write('BrokenPipeError | IOError Exception occurred')
file.close()
except Exception as e:
if os.path.exists('drop.txt') == True:
file = open("drops.txt","a+")
file.write(' interrupted: {}'.format(str(e)))
file.close()
在打印文件时,如果我按一个随机键,它将停止程序并输出此错误消息,这不是我想要的。首选的行为是打印结束,程序停止,并且根本没有进一步的输出。这是我按随机键时出现的错误消息:
Traceback (most recent call last):
File "drop.py", line 100, in <module> drops()
File "drop.py", line 321, in drops print(line)
BrokenPipeError: [Err 56] Broken pipe
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "drop.py", line 756, in <module>file = open ("drop.txt","a+")
File "boot.py", line 68, in decoding
def decoding(do_setlocale=True):
KeyboardInterrupt
如果我在打印行时按下随机键,而不是显示所有这些错误消息,那么我将结束打印,停止程序,并且不显示任何错误消息。如果有人可以在这里帮助我,我将不胜感激。非常感谢:)