Importing in Python

前端 未结 4 1505
南旧
南旧 2020-12-20 04:27

In Python 2.5, I import modules by changing environment variables. It works, but using site-packages does not. Is there another way to import modules in directories other

相关标签:
4条回答
  • 2020-12-20 04:33

    Append the location to the module to sys.path.

    Edit: (to counter the post below ;-) ) os.path does something completely different. You need to use sys.path.

    sys.path.append("/home/me/local/modules")
    
    0 讨论(0)
  • 2020-12-20 04:40

    sys.path is a list to which you can append custom paths to search like this:

    sys.path.append("/home/foo")
    
    0 讨论(0)
  • 2020-12-20 04:52

    On way is with PYTHONPATH environment variable. Other one is to add path to sys.path either directly by sys.path.append(path) or by defining .pth files and add them to with site.addsitedir(dirWithPths). Path files (.pth) are simple text files with a path in each line. Every .pth file in dirWithPths will be read.

    0 讨论(0)
  • 2020-12-20 04:54

    Directories added to the PYTHONPATH environment variable are searched after site-packages, so if you have a module in site-packages with the same name as the module you want from your PYTHONPATH, the site-packages version will win. Also, you may need to restart your interpreter and the shell that launched it for the change to the environment variable to take effect.

    If you want to add a directory to the search path at run time, without restarting your program, add the directory to sys.path. For example:

    import sys
    sys.path.append(newpath)
    

    If you want your new directory to be searched before site-packages, put the directory at the front of the list, like this:

    import sys
    sys.path.insert(0, newpath)
    
    0 讨论(0)
提交回复
热议问题