from user_config import g_cfg
import time
在看py代码的时候常常看到import 和from … import …
参考https://www.cnblogs.com/sanduzxcvbnm/p/11990676.html
这import 和 from…import…有什么区别?
import sys
print('================Python import mode==========================');
print ('The command line arguments are:')
for i in sys.argv:
print (i)
print ('\n The python path',sys.path)
from sys import argv,path #导入特定的成员
print('================python from import===================================')
print('path:',path)
如果你要使用所有sys模块使用的名字,你可以这样:
from sys import *
print('path:',path)
可以看到 from sys import path ,就是导入sys 中的path成员,可以直接使用path,不用在前面加sys.
这样的话可能会导致命名冲突,也不易读。所以建议使用import ,不要加from
在使用 from xxx import * 时,如果想精准的控制模块导入的内容,可以使用 all = [xxx,xxx] 来实现,例如:
two.py
__all__ = ['a','b'] #__为双横线
class two():
def __init__(self):
print('this is two')
a = 'this is two a'
b = 'this is two b'
if __name__=='__main__':
t = two()
one.py
from two import *
print a
print b
t = two()
这时,类two() 将不会被import * 导入进来
自己写的模块,怎么导入,py怎么知道到哪里去找对应的文件?
类似于头文件,模块也是需要系统的搜索路径的,下面的命令即是系统默认的搜索路径,当你导入一个模块时,系统就会在下面的路径列表中搜索相应的文件。
先在当前目录中搜索,再在其他路径下查找,如果没找到会报错。
当然也可以自己添加搜索路径,调用列表的append方法即可:
import sys
sys.path.append('/home/python/newcode')