Import python module NOT on path

前端 未结 4 2012
悲&欢浪女
悲&欢浪女 2020-12-04 16:30

I have a module foo, containing util.py and bar.py.

I want to import it in IDLE or python session. How do I go about this?

I could find no documentation on h

相关标签:
4条回答
  • 2020-12-04 16:56

    Following phihag's tip, I have this solution. Just give the path of a source file to load_src and it will load it. You must also provide a name, so you can import this module using this name. I prefer to do it this way because it's more explicit:

    def load_src(name, fpath):
        import os, imp
        return imp.load_source(name, os.path.join(os.path.dirname(__file__), fpath))
    
    load_src("util", "../util.py")
    import util
    
    print util.method()
    

    Another (less explicit) way is this:

    util = load_src("util", "../util.py")    # "import util" is implied here
    
    print util.method()    # works, util was imported by the previous line
    

    Edit: the method is rewritten to make it clearer.

    0 讨论(0)
  • 2020-12-04 17:10

    Give this a try

    import sys
    sys.path.append('c:/.../dir/dir2')
    import foo
    
    0 讨论(0)
  • 2020-12-04 17:12

    You could customize the module search path using the PYTHONPATH environment variable, or manually modify the sys.path directory list.

    See Module Search Path documentation on python.org.

    0 讨论(0)
  • 2020-12-04 17:15

    One way is to simply amend your path:

    import sys
    sys.path.append('C:/full/path')
    from foo import util,bar
    

    Note that this requires foo to be a python package, i.e. contain a __init__.py file. If you don't want to modify sys.path, you can also modify the PYTHONPATH environment variable or install the module on your system. Beware that this means that other directories or .py files in that directory may be loaded inadvertently.

    Therefore, you may want to use imp.load_source instead. It needs the filename, not a directory (to a file which the current user is allowed to read):

    import imp
    util = imp.load_source('util', 'C:/full/path/foo/util.py')
    
    0 讨论(0)
提交回复
热议问题