1. 导入模块时,如果导入的新模块不在当前模块所在同一路径下,那么直接import会出错。解决办法有:
(1)如果当前模块和要导入的模块属于不同的包,但是包的上级路径是一样的,那么可以直接import 包名.模块名,如import myPackeg.myModule
(2)可以先将要导入的模块加入sys.path中,再import. 如下示例:导入F:\DeepLearning目录下的test1模块
>>> import test1
Traceback (most recent call last):
File "", line 1, in
import test1
ModuleNotFoundError: No module named 'test1'
>>> import sys
>>> sys.path
['', 'D:\\Program Files\\Python\\Lib\\idlelib', 'D:\\Program Files\\Python\\python36.zip', 'D:\\Program Files\\Python\\DLLs', 'D:\\Program Files\\Python\\lib', 'D:\\Program Files\\Python', 'D:\\Program Files\\Python\\lib\\site-packages']
>>> sys.path.append('F:\\DeepLearning')
>>> sys.path
['', 'D:\\Program Files\\Python\\Lib\\idlelib', 'D:\\Program Files\\Python\\python36.zip', 'D:\\Program Files\\Python\\DLLs', 'D:\\Program Files\\Python\\lib', 'D:\\Program Files\\Python', 'D:\\Program Files\\Python\\lib\\site-packages', 'F:\\DeepLearning']
>>> import test1
>>>
先看tc模块和calc模块的代码
calc模块代码:
import tc
print("32摄氏度 = %.2f华氏度"%tc.c2f(32))
print("99华氏度 = %.2f摄氏度"%tc.f2c(99))
tc模块代码:
def c2f(cel):
fah = cel * 1.8 + 32
return fah
def f2c(fah):
cel = (fah - 32) / 1.8
return cel
def test():
print("测试,0摄氏度 = %.2f华氏度"%c2f(0))
print("测试,0华氏度 = %.2f摄氏度"%f2c(0))
test()
运行calc模块后:
>>> runfile('F:/DeepLearning/calc.py', wdir='F:/DeepLearning')
Reloaded modules: tc
测试,0摄氏度 = 32.00华氏度
测试,0华氏度 = -17.78摄氏度
32摄氏度 = 89.60华氏度
99华氏度 = 37.22摄氏度
将测试语句的函数test()也执行了,如果要避免直接执行test()函数,可以将tc模块中最后一句test()语句改为:
if __name__ == '__main__':
test()
再执行就是
>>> runfile('F:/DeepLearning/calc.py', wdir='F:/DeepLearning')
Reloaded modules: tc
32摄氏度 = 89.60华氏度
99华氏度 = 37.22摄氏度
查看__name__属性:
>>> __name__
'__main__'
>>> tc.__name__
'tc'