luofeiyu_cu 发表于 2014-07-28 11:37

模块导入的问题

我有个文件 mydown.py,这个文件放置在D:\Python34\Lib\site-packages
这个文件只有一行
import requests

请看下面:

C:\Users\pengsir>d:\Python34\python
Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:25:23) [MSC v.1600 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import mydown
>>> dir(mydown)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'requests']
>>> url='http://quote.eastmoney.com/hk/02222.html?StockCode=02222'
>>> requests.get(url)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'requests' is not defined

为何会出现NameError: name 'requests' is not defined ?

q1208c 发表于 2014-07-28 12:47

你没在任何地方定义 requests 呀.

icymirror 发表于 2014-07-28 13:22

回复 1# luofeiyu_cu
你最好先在你的Lib目录下搜索下,看有没有requests这个模块。

luofeiyu_cu 发表于 2014-07-28 14:22

本帖最后由 luofeiyu_cu 于 2014-07-28 14:51 编辑

1.有requests这个模块。
2.老外的答复。
> there is a simple file `mydown.py`saved in
> `D:\Python34\Lib\site-packages`
>there is only one line in mydown.py .
>
>import requests

Just because mydown has imported requests, doesn't mean it is visible
everywhere. Each module is a separate namespace, so that

    requests = "something"

inside module A doesn't break

    import requests

inside module B.

Inside mydown you import requests, but you still need to import it in the
interactive interpreter too. Don't worry, the second import will be very
fast, once a module is imported once the second and subsequent times is
very quick.

柠檬妞 发表于 2014-07-30 15:55

直接用名称的话应该用以下语句导入,
from mydown import *

或者按照你的导入方法在用requests是应该加类名 mydown.requests.get(url)

ssfjhh 发表于 2014-07-31 09:17

回复 5# 柠檬妞


    这个应该是正解了。

Linux_manne 发表于 2014-08-15 16:33

嗯 既然import 了mydown 那应该这样mydown.requests 这样调用吧

lizhihui_kevin 发表于 2014-09-15 17:50

:mrgreen: 回复 5# 柠檬妞


   
页: [1]
查看完整版本: 模块导入的问题