python 调用自定义的模块函数

来源:互联网 发布:阿里云cname绑定 编辑:程序博客网 时间:2024/06/05 23:30

有一些自己定义的基础模块函数,在很多任务中会重复使用,例如读取列表,保存结果等,每次复制相同的代码到一个.py文件中进行调用太过麻烦,把基础模块放在固定文件夹(或相对固定文件夹),使用sys.append(r'自定义的模块路径'),将自定义模块所在路径添加到搜索路径,当需要在不同的电脑(或服务器)使用时,会便利很多。

示例如下:

在E:\python_lib新建print_module.py实现基础功能函数

# -*- coding: utf-8 -*-def print_test():print('function: print_test')print('happy~')returndef print_test2(n):print('function: print_test2')for i in xrange(n):print(str(i) + ' : ' + 'happy~')print('haha~')

在E:\learn_soft\python\practice中新建test_path.py使用该模块中的函数:

# -*- coding: utf-8 -*-import syssys.path.append(r'E:/python_lib')import print_moduleprint_module.print_test()print_module.print_test2(3)

运行结果如下: