PYTHONPATH环境变量......之后如何创建每个子目录?

时间:2009-10-31 23:38:26

标签: python linux unix environment-variables

我目前这样做:

PYTHONPATH=/home/$USER:/home/$USER/respository:/home/$USER/repository/python-stuff

我怎样才能使PYTHONPATH包含所有子目录?

PYTHONPATH = /home/$USER/....and-all-subdirectories

2 个答案:

答案 0 :(得分:9)

sys.path两条路径上通常是一个坏主意,其中一条路径是另一条路径的父路径 - 假设子目录一包含__init__.py文件以将其标记为包,当然。如果只有父目录在路径中($PYTHONPATHsys.path初始化的一部分),子目录中的模块可以从包中导入,即只通过一个文件系统路径,避免单个模块以多种不同的形式进口的风险。

那你为什么不把__init__.py个文件放在需要它的所有子目录中,并使用包导入?

虽然我认为您的请求是个坏主意,但它确实可行 - Unix find命令可以轻松列出目录的所有子目录,每行一个(find . -type d),您可以轻松地将线粘在一起,例如通过将find的输出汇总到tr '\n' :

答案 1 :(得分:1)

我是这样做的:

import os
import sys

all_modules = {} #keeps track of the module names

def discoverModules():
    ''' Populates a dictionary holding every module name in the directory tree that this file is run '''    
    global all_modules

    for dirname, dirnames, filenames in os.walk('.'):
        # Advanced usage:
        # editing the 'dirnames' list will stop os.walk() from recursing into there.
        if '.git' in dirnames:
            # don't go into any .git directories.
            dirnames.remove('.git')

        # save path to all subdirectories in the sys.path so we can easily access them:
        for subdirname in dirnames:                    
            name = os.path.join(dirname, subdirname) # complete directory path
            sys.path.append(name) # add every entry to the sys.path for easy import

        # save path to all filenames:
        for filename in filenames:        
            # we want to save all the .py modules, but nothing else:
            if '.py' in filename and '.pyc' not in filename and '__init__' not in filename:
                moduleName = '' #this will hold the final module name

                # If on Mac or Linux system:
                if str(os.name) == 'posix': 
                    for element in dirname.split('\/'): # for each folder in the traversal
                        if element is not '.': # the first element is always a '.', so remove it
                            moduleName += element + '.' # add a '.' between each folder

                # If on windoze system:
                elif str(os.name) == 'nt': 
                    for element in dirname.split('\\'): # for each folder in the traversal
                        if element is not '.': # the first element is always a '.', so remove it
                            moduleName += element + '.' # add a '.' between each folder

                # Important to use rstrip, rather than strip. If you use strip, it will remove '.', 'p', and 'y' instead of just '.py'
                moduleName += filename.rstrip('.py') # finally, add the filename of the module to the name, minus the '.py' extension            
                all_modules[str(filename.rstrip('.py'))] = moduleName # add complete module name to the list of modules
    print 'Discovering Modules...Complete!'
    print 'Discovered ' + str(len(all_modules)) + ' Modules.'