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 为导入模块的名字,这里经过测试可以随便写

  • 相关阅读:
    华为2019软件题
    图像的存储格式转化(python实现)
    windows+两个ubuntu系统的引导启动问题
    《视觉SLAM十四讲》课后习题—ch6
    视觉SLAM十四讲课后习题—ch8
    LINQ根据时间排序问题(OrderBy、OrderByDescending)
    Element的扩展
    CSharp
    jQuery函数使用记录
    日记越累
  • 原文地址:https://www.cnblogs.com/jkklearn/p/13975315.html
Copyright © 2011-2022 走看看