pythonpython-2.7cookielib

Trying to eval back repr(CookieJar)


I am trying to deserialize a cookielib.CookieJar.__repr__() output back to a CookieJar object. I did:

cjs = repr(myCJ)
cj = eval(cjs)

It gave a SyntaxError: invalid syntax. The cjs string is more than 3,000 characters long, The second statement above gave the following actual output:

>>> cjx=eval(cjs)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    <cookielib.CookieJar[Cookie(version=0, name='AMAuthCookie', value=' ....
...........lots deleted....and next is the actual last line...
comment=None, comment_url=None, rest={}, rfc2109=False)]>
    ^
SyntaxError: invalid syntax

I suspect that the ^ character is pointing to the very first character of the repr string, where the first few characters are:

>>> cjs[:50]
"<cookielib.CookieJar[Cookie(version=0, name='AMAut"

May I know whether there is something fundamentally wrong with what I am doing before I investigate if the repr function is giving issues.


Solution

  • repr is not guaranteed to be evalable. You should serialize the object via pickle instead, which is designed for object serialization and deserialization. Like so:

    import cPickle
    cjs = cPickle.dumps(myCJ)
    cj = cPickle.loads(cjs)
    

    In this case, the representation that CookieJar gives back is not remotely valid Python syntax. If you absolutely have to deal with this syntax, you may try

    cookielist = eval(cjs[ len('<cookielib.CookieJar') : -len('>') ])
    

    to extract out the list of cookies, then create a CookieJar from it. But I cannot guarantee that this would work.