0

I am trying to write the current window to a file. Problem with the code is that it must use an encoding (utf-8) otherwise if a window gets openened like outlook with windowname: Inbox - Outlook ‎- Mail it gives the following error:

UnicodeEncodeError: 'charmap' codec can't encode character '\u200e' in position 16: character maps to

But when using the utf-8 encoded file, it can not be encoded into base64, this gives the following error(of course):

ValueError: string argument should contain only ASCII characters

Is there a way to encode or encrypt this file(I've used rot-13 which worked and md5 but this didnt work well with reading and decrypting). Or to make the output of q = w.GetWindowText (w.GetForegroundWindow()) not in 'utf-8'. code:

import win32gui
import time
import psutil
import win32process
i = 0
    while i <= 1:
        time.sleep(2)
        w=win32gui
        q = w.GetWindowText (w.GetForegroundWindow())
        q =str(q)
        print(q)
        pid = win32process.GetWindowThreadProcessId(w.GetForegroundWindow())
        print(psutil.Process(pid[-1]).name())
        with open("lolp.txt",'w',encoding='utf-8')as f:
            f.write(q)
  • Your code runs smoothly for me even if a window title contains character `'\u200e'` (_Left-To-Right Mark_). Please share `print(os.environ.get('PYTHONIOENCODING'))` and `print(','.join([os.device_encoding(x) for x in range(0,3)]))` in your [mcve] (I get `utf-8` and `cp65001,cp65001,cp65001`). – JosefZ May 24 '21 at 19:44

1 Answers1

0

As far as I can tell you need to remove non-ascii symols from q. It can be done in many ways. For example:

import win32gui

q = win32gui.GetWindowText(win32gui.GetForegroundWindow())

def remove_non_ascii(char):
    return 32 <= ord(char) <= 126

q = filter(remove_non_ascii, q)

print("".join(list(q)))

Here are another solutions: How can I remove non-ASCII characters but leave periods and spaces?

Yuri Khristich
  • 13,448
  • 2
  • 8
  • 23