Home > Net >  Saving list of objects to and loading from a file in py? I'm not sure where to even start
Saving list of objects to and loading from a file in py? I'm not sure where to even start

Time:11-05

I have developed a code that compiles a list of objects produced from boppreh's keyboard and mouse .hook functionality with the intention of generating and saving basic task automation files. Recording and replaying actions was easy to implement albeit still occasionally buggy, but saving a file containing a list of object appears impossible to even approach. Pickling the data seems possible but I haven't found documentation that dumbs it down enough for me to troubleshoot the errors thrown.

Here is my entire Code:

import keyboard, mouse, time, pickle, sys
from optparse import OptionParser
    
events = []

def OnKeyboardEvent(event):
    global events

    events.append(event)

def onm ouseEvent(event):
    global events

    # intended extra functionality here later
    events.append(event)

def record():
    global events

    print("Hooking now...")
    keyboard.hook(callback=OnKeyboardEvent)
    mouse.hook(callback=OnMouseEvent)
    print("Hooked.")
    keyboard.wait(hotkey='escape')
    keyboard.unhook_all()
    mouse.unhook_all()
    print("Exporting...")

    # File IO here

    print("Complete.\n")

def play(speed_factor):
    global events

    # File IO here

    print('Playing recorded events...')

    # Code below works fine, would love pointers if you have any tho
    last_time = None
    for event in events:
        if speed_factor > 0 and last_time is not None:
            time.sleep((event.time - last_time) / speed_factor)
        last_time = event.time

        if isinstance(event, mouse.ButtonEvent):
            if event.event_type == 'up':
                mouse.release(event.button)
            else:
                mouse.press(event.button)
        elif isinstance(event, mouse.MoveEvent):
            mouse.move(event.x, event.y)
        elif isinstance(event, mouse.WheelEvent):
            mouse.wheel(event.delta)
        else:
            key = event.scan_code
            if event.event_type == 'down':
                keyboard.press(key)
            else:
                keyboard.release(key)

    print('Complete.\n')

def main():
    record()
    play(2)

if __name__ == "__main__":
    main()

I attempted to use the pickle API but ran into an error simply stating

line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)\[0\]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 65: character maps to \<undefined\>

I tried this

    with open('bin.dat', 'wb') as f:
        pickle.dump(events, f)

    with open('bin.dat', 'r') as f:
        evening = pickle.load(f)

Is there a file-io method I've completely missed or should I continue to bash my head against the wall with pickle? And go easy on me I'm a bit of a newbie :)) Thank you in advance.

CodePudding user response:

When using pickle to save and load objects, make sure you open the file in binary mode for both reading and writing:

with open('bin.dat', 'rb') as f:
events = pickle.load(f)

Make sure to use 'rb' mode instead of 'r' when reading the pickle file to avoid decoding errors. This should fix the UnicodeDecodeError you're having.

Source: https://ioflood.com/blog/python-exception/

  • Related