2

I have peiced together some code from the internet to capture pressed keys and the current active window title and am trying to write the output of the python script to a text file.

The script works fine in the IDLE console and prints pressed keys and logs any change in the current active window.

from pynput.keyboard import Key, Listener
import time
from win32gui import GetWindowText, GetForegroundWindow
import datetime
from threading import Thread

def on_press(key):
    print ('{0} pressed'.format(key))   

def on_release(key):
    ('{0} release'.format(key))
    if key == Key.esc:
        return False

def get_titles():
    current_title = None
    while True:
        moment2 = datetime.datetime.now().strftime("%d-%b-%Y [ %H:%M:%S ]")
        new_title = GetWindowText(GetForegroundWindow())
        if new_title != current_title:
            if len(new_title) > 0:
                #logging.info(" Moved to : " + new_title)
                current_title = new_title
                time.sleep(0.1)
                #print(new_title)
                ff= (moment2 + " : " +  "Moved T0 : "+ new_title)
                print (ff)

I am looking for a simple way to write the outputs i can see in the console to a text file. It is probably very simple but i am very much a beginner. Thanks

K.Meleo
  • 25
  • 1
  • 1
  • 8

3 Answers3

3

Python has a native open() function, no import needed, which allows you to handle files. This function "loads" the file into memory, and can be set into various modes:

  • open("filename.txt", "a"), appending the content to a new line;
  • open("filename.txt", "w"), overwriting the content; and
  • open("filename.txt", "r"), setting it to read-only.
  • open("filename.txt", "x"), to create a file.


You can add a "+" to each of this modes ("a+", "w+"), if you want the file to be created if it doesn't already exist.
You define the file in memory to a variable as such: a = open("filename.txt", "w"), and can then text = a.read() to load the content of the file to a string, or a.readlines() to load the strings into an array, split per \n.
Use a.write("Your desired output") to save the content to the file, if the file is in write or append modus.

Edit:

Try to only open files for as long as they are actually needed.

with open("filename.txt", "r") as f:
    file_contents = f.read()
    # file_contents = "This file contains\nvery important information"

    file_lines = f.readlines()
    # file_lines = ["This file contains", "very important information"]
    # Similar to file_lines = file_contents.split("\n")

in order to avoid blocking other parts of your program, and avoid corrupting your files if Python crashes unexpectedly.

mazunki
  • 682
  • 5
  • 17
  • Thanks mazunki, i can get some simple text strings to write to file, but im having trouble getting it to write my desired output. the ff= (moment2 + " : " + "Moved T0 : "+ new_title) and the def on_press(key): print ('{0} pressed'.format(key)) – K.Meleo Dec 21 '18 at 12:36
  • Try to `type(ff)` to check whether ff is a string, or not. If it isn't, cast it to one with `ff=str(ff)` before appending it to the file. Alternatively, make another function called save_to_file() which handles everything regarding files. – mazunki Dec 21 '18 at 13:51
2

Just add

with open('textfile.txt', 'a+') as f:
  f.write(ff)

a option is for appending to a file and + means that if the file is not there just create one with the specified name.

EDIT:

def on_press(key):
    print ('{0} pressed'.format(key))
    with open('textfile.txt', 'a+') as f:
      f.write(ff) 

EDIT 2:

def on_press(key):
    print ('{0} pressed'.format(key))
    k = key + '\n'
    with open('textfile.txt', 'a+') as f:
      f.write(key) 

# and in get_titles()
ff= (moment2 + " : " +  "Moved T0 : "+ new_title + '\n')
with open('textfile.txt', 'a+') as f:
      f.write(ff)
Novak
  • 2,143
  • 1
  • 12
  • 22
  • thanks for the help. when i add the code you mentioned i get an error "NameError: name 'ff' is not defined" , although i can see ff= (moment2 + " : " + "Moved T0 : "+ new_title) – K.Meleo Dec 21 '18 at 12:32
  • You have to do it in the loop instead of `print(ff)` – Novak Dec 21 '18 at 12:33
  • ahh ok, that has somewhat worked. now it is writing the active window to a text file, but not the key inputs. – K.Meleo Dec 21 '18 at 12:39
  • Well you have to somehow get the pressed key value to a variable and then you can append it to the `ff` string and save it the same way. Or just under the `f.write(ff)` write `f.write(pressedKey)` where `pressedKey` is the variable where you have saved the pressed key. – Novak Dec 21 '18 at 12:41
  • or you can set the function `on_press(key)` to save the output to the same file the same way I wrote in the answer. So now, the `on_press(key)` function would look like the one in the answer (I edited it so take a look) – Novak Dec 21 '18 at 12:43
  • ok thanks, adding the pressedkey variable, in the on_press loop, has worked so it now writes both the active window name and the pressed keys.. the last issue now is that the output is not looking very neat. how would i be able to make each entry go to a seperate line? would it be adding \n tothe end of the f.write – K.Meleo Dec 21 '18 at 12:58
  • You can add `\n` to the every line you save to the file (both the `ff` string and the `key`). Take a look at the edit in my answer :) – Novak Dec 21 '18 at 12:59
  • would i add the \n like so? with open('textfile.txt', 'a+') as f: f.write(ff \n) – K.Meleo Dec 21 '18 at 13:06
  • No, you have to add it as a string. what you can do is `f.write(ff + '\n')` – Novak Dec 21 '18 at 13:08
  • thats done it. its working how i would like now.. thank you so much for your help. – K.Meleo Dec 21 '18 at 13:17
  • Glad I could help you :) – Novak Dec 21 '18 at 13:18
0

try this when run program in console

python your_script.py > path_to_output_file/outpot.txt

in case '>' not work then try '>>'

  • Does this work for print() too? As far as I know, this only changes the default output stream. Doesn't affect the error stream, or other functions. – mazunki Dec 21 '18 at 12:27
  • Check this for different output modes: https://askubuntu.com/questions/420981/how-do-i-save-terminal-output-to-a-file – mazunki Dec 21 '18 at 12:28
  • thanks guys, i would rather have it save to a file from within the script instead of haveing to run a command when launching it. – K.Meleo Dec 21 '18 at 12:34
  • As a comment, `>` actually overwrites the file, while `>>` actually appends to text to the end of the file. They both work for standard output, not for error output. – mazunki Mar 20 '19 at 18:26