简体   繁体   中英

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

I'm trying to make this simple keylogger in python, it works just fine when i run in IDLE, but in console it doesn't write the log to the file.

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()

To be helpful to others, the problem in the question needs explanation. An 'open(filepath)' with a relative path, such as 'something.txt', will open the file relative to the 'current working directory'. For a simple filename, this means in that current working directory (CWD).

When IDLE runs code in the editor, it makes the current working directory of the new process where it runs the code to be the directory of the code. (The CWD of the IDLE process is ignored.) So if you were editing r'C:\\Users\\henrique\\Documents\\Programas\\Python\\Keylogger\\teste27.py', then opening 'teste27.txt' will indeed open r'C:\\Users\\henrique\\Documents\\Programas\\Python\\Keylogger\\teste27.txt'.

A console is a running program with a CWD. For most consoles, the default prompt includes the CWD. When you run a program from the console, it inherits that CWD amd runs with that CWD unless and until the program changes it. It must be that you did not make r'C:\\Users\\henrique\\Documents\\Programas\\Python\\Keylogger\\' the console's CWD, but instead ran your program somewhere else by giving a path to the program: "python somepath/teste27.py". You should find a stray 'teste27.txt' in whatever CWD you started the program in.

You can avoid having to add 'r' to paths by using forward slashes. 'C:/Users/henrique/Documents/Programas/Python/Keylogger/teste27.txt'. The only time you must use backslashes on Windows is in the console when you give a path for the program to be run.

An alternate solution, useful when you open multiple files within a directory, is to make that directory the CWD. For instance,

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

Then 'open(texte27.txt)' would have worked as you wanted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM