zoukankan      html  css  js  c++  java
  • python导入py文件模块

    有时我们写了一些lib文件,想作为模块导入引用

    python import导入模块时搜索模块文件路径在 sys.path

    在root下执行的 t.py (print sys.path)

    ['/root', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib/python2.7/site-packages']

    默认会在执行脚本的当前路径下去找,找不到时回去python 的lib目录等依次去找

    有时需要手动将某个文件的路径加入到 sys.path中

     模块路径中加入项目代码主目录

    下面的代码是cloud-init 部分中的源码,将项目root目录插入到 sys.path中,用来导入项目目录下的模块文件

    sys.path.insert(0, find_root())
    sys.path.append(find_root())

    有时可以使用imp 模块 来导入一个绝对路径的文件

    [root@test ~]# cat /home/file.py
    def printinfo():
        print("hello world")
    
    #test.py
    import imp
    
    testfunc = imp.load_source('testfunc', '/home/file.py')
    testfunc.printinfo()
    #打印hello world

    imp.load_source('testfunc', '/home/file.py')  中的 testfunc 为导入模块的名字,这里经过测试可以随便写

  • 相关阅读:
    Chaos网络库(一) 开篇介绍
    对Oracle中的表进行分区
    java socket编程
    SQL优化
    冒泡排序、选择排序和插入
    集合有趣的地方
    java中String s = new String("abc")创建了几个对象
    集合排序
    接口与抽象类的区别
    软件测试流程
  • 原文地址:https://www.cnblogs.com/jkklearn/p/13975315.html
Copyright © 2011-2022 走看看