how can I import a module without using pythonpath?

Discussion in 'Python' started by Phd, Dec 14, 2004.

  1. Phd

    Phd Guest

    Hi,

    I'm using python 2.2, I want to import a module by referring to its
    relative location. The reason for this is that there is another module
    with the same name that's already in pythonpath( not my decision, but I
    got to work around it, bummer). So is there any easy way to do it?

    something like
    import module "from this location"


    Thanks!
     
    Phd, Dec 14, 2004
    #1
    1. Advertising

  2. Phd

    Doug Holton Guest

    Phd wrote:
    > Hi,
    >
    > I'm using python 2.2, I want to import a module by referring to its
    > relative location. The reason for this is that there is another module
    > with the same name that's already in pythonpath( not my decision, but I
    > got to work around it, bummer). So is there any easy way to do it?


    import sys, os
    sys.path.insert(0,os.path.abspath("relative path"))
    import module
    sys.path.remove(os.path.abspath("relative path"))
     
    Doug Holton, Dec 14, 2004
    #2
    1. Advertising

  3. Phd

    Phd Guest

    Nice, thanks so much!



    Doug Holton wrote:

    > Phd wrote:
    >
    >> Hi,
    >>
    >> I'm using python 2.2, I want to import a module by referring to its
    >> relative location. The reason for this is that there is another module
    >> with the same name that's already in pythonpath( not my decision, but
    >> I got to work around it, bummer). So is there any easy way to do it?

    >
    >
    > import sys, os
    > sys.path.insert(0,os.path.abspath("relative path"))
    > import module
    > sys.path.remove(os.path.abspath("relative path"))
     
    Phd, Dec 14, 2004
    #3
  4. Doug Holton wrote:

    >> I'm using python 2.2, I want to import a module by referring to its relative location. The reason
    >> for this is that there is another module with the same name that's already in pythonpath( not my
    >> decision, but I got to work around it, bummer). So is there any easy way to do it?

    >
    > import sys, os
    > sys.path.insert(0,os.path.abspath("relative path"))
    > import module
    > sys.path.remove(os.path.abspath("relative path"))


    a try-finally clause is a pretty good idea, in this case.

    you might also wish to store the calculated path, in case the module
    changes the current directory. or store the original sys.path, in case
    the module messes with the path but shouldn't. (on the other hand, if
    the module is nice and well behaved, you can replace the last line with
    del sys.path[0]...)

    </F>
     
    Fredrik Lundh, Dec 14, 2004
    #4
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page