2017-08-14 74 views
-1

我有这样的Python脚本3,现在我需要它从我已阅读urilib应更改为urlib2什么关于Python 2, 运行。 但它看起来像编码类有变化。 因为我得到这个错误:需要把蟒蛇3脚本到Python 2.7脚本

16:29:27 + python p.py 
16:29:27 Traceback (most recent call last): 
16:29:27 File "p.py", line 20, in <module> 
16:29:27  binary_data = params.encode(encoding=repr,errors=strict) 
16:29:27 NameError: name 'strict' is not defined 

这是我的Python 3脚本:

import urllib 
import urllib.request 
import sys 
import os 
url = 'http://google.com' 
params = urllib.parse.urlencode({ 
'profile': 'dev' , 
'KEY':'bdi.key' , 
}) 
binary_data = params.encode(encoding='ascii',errors='strict') 
response = urllib.request.urlopen(url, binary_data).read() 

这是我的Python 2脚本:

import urllib 
import urllib2 
from contextlib import closing 
import sys 
import os 
url = 'http://google.com' 
params = urllib.urlencode({ 
'profile': 'dev' , 
'KEY':'bdi.key' , 
}) 
binary_data = params.encode(encoding=repr,errors=strict) 
response = urllib2.urlopen(url, binary_data).read() 

怎么样 我可以让它工作吗? 我以前从来没有用过Python,这是一个维护脚本,我试图保持活力:)

+1

'binary_data = params.encode(编码= 'ASCII',错误= '严格')'?注意我在wordc'strict'和'repr'周围使用引号''来告诉Python它们是字符串而不是名称。 –

+0

'strict'应该是'string' 编码也应该是一个字符串('“ascii”'') –

回答

0

问题在字符串编码功能,即errors参数。您应该将strict放在引号中,因为变量strict不存在。

所以,它应该是这样的:

binary_data = params.encode(encoding=repr, errors='strict')