开发者

python2.7:A sample script ,in C partition it can run however in D partition it has AttributeError

I am learning python. Today 开发者_StackOverflowI meet with a odd problem.

from urllib import urlopen

url='http://www.google.com'
f=urlopen(url).read()
print f

It is a sample script ,it can run if it in C partition however in D partition it has AttributeError:

Traceback (most recent call last):

File "D:\urlopen.py", line 1, in <module>

from urllib import urlopen File "D:\urllib.py", line 7, in <module>

nettext=urllib.urlopen(strurl).read()

AttributeError: 'module' object has no attribute 'urlopen'

I installed python2.7 and python3.1 in win7,and I run the script in python2.7's shell.


I don't know why it works on C:\. It should fail either way. You're importing something from urllib. Your script is called urllib. The current directory comes before standard library dirs, so you import yourself. It's only because imports are "cached" (a second import x in the same interpreter process just gives a reference to the already imported module instead of loading it again) that this doesn't lead to an infinite loop. Of course your module doesn't have anything that's in the stdlib urllib package, e.g. no urlopen.


In Python 3 many modules were reorganized. One of them happens to be urllib. To get the above code to work in Python 3 you would want to do:

import urllib.request
url = "http://www.google.com"
f = urllib.request.urlopen(url).read()
print(f)

Edit:

You will also notice that in Python 3 you must use parentheses with print. For a list of changes from Python 2.x to 3.x, see this documentation

If you are not trying to run this code in Python 3.1 but in 2.7 instead, then it seems your "D partition" is pointing to your Python 3.1 install, whereas your "C Partition" is pointing to 2.7. Python 2.x and 3.x is typically not compatible (see above documentation).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜