代码之家  ›  专栏  ›  技术社区  ›  Ciantic

从PHP反序列化python的cpickle?

  •  6
  • Ciantic  · 技术社区  · 14 年前

    我必须 反序列化词典 在使用 cpickle在python中 .

    在这种情况下,我可能只是 regexp需要的信息 但是有更好的方法吗?PHP的任何扩展都允许我更自然地反序列化整个字典?

    显然,它在python中是这样序列化的:

    import cPickle as pickle
    
    data = { 'user_id' : 5 }
    pickled = pickle.dumps(data)
    print pickled
    

    这种序列化的内容不能轻易粘贴到这里,因为它包含二进制数据。


    解决方案

    因为python端是django,所以我最终创建了 own JSON SessionStore .

    4 回复  |  直到 14 年前
        1
  •  7
  •   mipadi    14 年前

    如果要在用不同语言编写的程序之间共享数据对象,可以使用类似的方法更容易序列化/反序列化 JSON 相反。大多数主要的编程语言都有一个JSON库。

        2
  •  5
  •   Eric Palakovich Carr    12 年前

    你能打个系统电话吗?您可以使用这样的python脚本将pickle数据转换为json:

    # pickle2json.py
    import sys, optparse, cPickle, os
    try:
        import json
    except:
        import simplejson as json
    
    # Setup the arguments this script can accept from the command line
    parser = optparse.OptionParser()
    parser.add_option('-p','--pickled_data_path',dest="pickled_data_path",type="string",help="Path to the file containing pickled data.")
    parser.add_option('-j','--json_data_path',dest="json_data_path",type="string",help="Path to where the json data should be saved.")
    opts,args=parser.parse_args()
    
    # Load in the pickled data from either a file or the standard input stream
    if opts.pickled_data_path:
        unpickled_data = cPickle.loads(open(opts.pickled_data_path).read())
    else:
        unpickled_data = cPickle.loads(sys.stdin.read())
    
    # Output the json version of the data either to another file or to the standard output
    if opts.json_data_path:
        open(opts.json_data_path, 'w').write(json.dumps(unpickled_data))
    else:
        print json.dumps(unpickled_data)
    

    这样,如果从文件中获取数据,您可以这样做:

    <?php
        exec("python pickle2json.py -p pickled_data.txt", $json_data = array());
    ?>
    

    或者,如果要将其保存到文件中,请执行以下操作:

    <?php
        system("python pickle2json.py -p pickled_data.txt -j p_to_j.json");
    ?>
    

    上面所有的代码可能都不完美(我不是一个PHP开发人员),但是像这样的代码对您有用吗?

        3
  •  1
  •   John Machin Santi    14 年前

    如果pickle是由您所显示的代码创建的,那么它将不包含二进制数据——除非您将换行称为“二进制数据”。见 the Python docs . 下面的代码由python 2.6运行。

    >>> import cPickle
    >>> data = {'user_id': 5}
    >>> for protocol in (0, 1, 2): # protocol 0 is the default
    ...     print protocol, repr(cPickle.dumps(data, protocol))
    ...
    0 "(dp1\nS'user_id'\np2\nI5\ns."
    1 '}q\x01U\x07user_idq\x02K\x05s.'
    2 '\x80\x02}q\x01U\x07user_idq\x02K\x05s.'
    >>>
    

    上面哪一个看起来最像你看到的?您可以发布十六进制编辑器/转储程序所显示的pickled文件内容,或者PHP中类似于python的repr()的内容吗?一本典型的字典里有多少项?除了“整数”和“8位字节字符串”(什么编码?)?

        4
  •  0
  •   Evgeny Smolin    11 年前

    我也有同样的问题。 我找不到解决方案,所以我用PHP创建了自己的Python模块的极简端口。 后来我发现 Zend序列化程序适配器pythonpickle 来自Zend框架。