z/OS Tools & Language

Expand all | Collapse all

Codec troubles with Python 2.7.6

  • 1.  Codec troubles with Python 2.7.6

    Posted 04-05-2017 04:30

    TL;DR: Is there a way to properly encode received bytes using EBCDIC ?

    Hello,

    while working with sockets I noticed that python always expects and EBCDIC string.

    I have currently been able to get a Python client-server configuration (Linux client, z/OS server) to communicate by forcing the client to use ‘cp500’ encoding, but I haven’t been able to do the same server-side (decoding Latin-1 to EBCDIC).

    This is what I tried up until now:

    >>> import codecs, sys
    >>> test = ‘\x48\x54\x54\x50’
    >>> test.encode(‘cp500’)
    UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0x48 in position 0: ordinal not in range(128)

    I also tried by setting the default encoding to ‘cp500’ with:

    >>> reload(sys)
    >>> sys.setdefaultencoding(‘cp500’)
    >>> test.decode(‘Latin1’)
    u’\x48\x54\x54&’

    Still, without success.

    Any hints?



  • 2.  RE: Codec troubles with Python 2.7.6

    Posted 04-06-2017 05:14

    try this:

    >>> test = '\x48\x54\x54\x50'
    >>> test.decode('latin1')                  # convert latin1 byte string to unicode
    u'HTTP'
    >>> test.decode('latin1').encode('cp500')  # and then convert further to EBCDIC
    '\xc8\xe3\xe3\xd7'
    >>>


  • 3.  RE: Codec troubles with Python 2.7.6

    Posted 04-06-2017 10:12

    Unfortunately this doesn’t work:

    >>> test.decode(‘latin1’).encode(‘cp500’)
    ’\x48\x54\x54&’



  • 4.  RE: Codec troubles with Python 2.7.6

    Posted 04-06-2017 08:43

    Hello!

    Try to use this code:

    import codecs
    test = '\x48\x54\x54\x50’
    ascii_text = codecs.decode(test, ‘cp437’)
    print (ascii_text)
    ebcdic_text = codecs.encode(ascii_text, ‘cp500’)
    print (ebcdic_text)



  • 5.  RE: Codec troubles with Python 2.7.6

    Posted 04-06-2017 10:16

    For some reason this works, thanks:

    >>> import codecs
    >>> test = ‘\x48\x54\x54\x50’
    >>> ascii_text = codecs.decode(test, ‘cp437’)
    >>> print ascii_text
    HTTP

    I also found another solution, which is to use the module “oe2a.py” posted here on the forum (just remove the last backslash).


    Now that I am able to decode/encode ascii properly the problem shifted to socket.py, I think that the readline/read/write functions will need the proper changes.