Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve 'str' has no attribute 'maketrans' error in python?

Tags:

python

I got an error while run python proxy.py

$ python proxy.py 
INFO - [Sep 28 14:59:19] getting appids from goagent plus common appid pool!
Traceback (most recent call last):
  File "proxy.py", line 2210, in <module>
    main()
  File "proxy.py", line 2180, in main
    pre_start()
  File "proxy.py", line 2157, in pre_start
    common.set_appids(get_appids())
  File "proxy.py", line 94, in get_appids
    fly = bytes.maketrans(
AttributeError: type object 'str' has no attribute 'maketrans'

The proxy.py file in https://code.google.com/p/smartladder/,

def get_appids():
    fly = bytes.maketrans(
        b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
        b"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"
    )
    f = urllib.request.urlopen(url="http://lovejiani.com/v").read().translate(fly)
    d = base64.b64decode(f)
    e = str(d, encoding='ascii').split('\r\n')
    random.shuffle(e)
    return  e
like image 219
Victor S Avatar asked Sep 28 '13 07:09

Victor S


1 Answers

You are running code written for Python 3, with Python 2. This won't work.

maketrans is a classmethod on the bytes built-in type, but only in Python 3.

# Python 3
>>> bytes
<class 'bytes'>
>>> bytes.maketrans
<built-in method maketrans of type object at 0x10aa6fe70>

In Python 2, bytes is an alias for str, but that type does not have that method:

# Python 2.7
>>> bytes
<type 'str'>
>>> bytes.maketrans
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'str' has no attribute 'maketrans'

Run your code with Python 3 instead, or translate all code in this project to Python 2; the latter requires in-depth knowledge of how Python 2 and 3 differ and is likely a major undertaking.

Just the illustrated function, translated to Python 2, would be:

import string
import urllib2
import base64
import random

def get_appids():
    fly = string.maketrans(
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
        "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"
    )
    f = urllib2.urlopen("http://lovejiani.com/v").read().translate(fly)
    d = base64.b64decode(f)
    e = unicode(d, encoding='ascii').split(u'\r\n')
    random.shuffle(e)
    return e
like image 130
Martijn Pieters Avatar answered Oct 25 '22 17:10

Martijn Pieters