2014-08-29 48 views
0

我正在嘗試編寫一個python腳本,它通過與腳本當前所在目錄相同的目錄中的所有目錄,它們的子目錄和文件位於具有後綴「.symlink」的目錄中,之後創建主目錄中的符號鏈接。腳本沒有找到指定的文件

但我遇到了問題。該腳本沒有找到任何目錄或文件。我可能濫用散步方法。有什麼建議麼?

import os 

class Symlink: 
    """A reference to a file or (sub)directory in the filesystem "marked" to be linked to from the user's home directory.'""" 

    def __init__(self, targetPath, linkName): 
     self.targetPath = targetPath 
     self.linkName = linkName 

    def getTargetPath(self): 
     return self.targetPath 

    def getLinkName(self): 
     return self.linkName 

    def linkExists(self, linkName): 
     return os.path.exists(os.path.join(os.path.expanduser('~'), linkName)) 

    def createSymlink(self): 
     overwrite, skip = False, False 

     answer = '' 
     while True: 
      try: 
       if linkExists(self.getLinkName()) and \ 
        not overwriteAll and \ 
        not skipAll: 
        answer = input('A file or link already exists in your home directory with the name', linkName, '. What do you want to do? [o]verwrite, [O]verwrite all, [s]kip or [S]kip all?') 

       if not answer in ['o', 'O', 's', 'S']: 
        raise ValueError(answer) 

       break 

      except ValueError as err: 
       print('Error: Wrong answer:', err) 

     if answer == 'o': 
      overwrite = True 
     if answer == 'O': 
      overwriteAll = True 
     if answer == 's': 
      skip = True 
     if answer == 'S': 
      skipAll = True 

     if overwrite or overwriteAll: 
      os.symlink(self.getTargetPath(), self.getLinkName()) 

def main(): 
    symlinks = [] 

    print('Adding directories and files to list...') 
    currentDirectory = os.path.realpath(__file__) 

    # Going throu this file's current directory and it's subdirs and files 
    for dir_, directories, files in os.walk(currentDirectory): 

     # For every subdirectory 
     for dirName in directories: 

      # Check if directory is marked for linking 
      if dirName[-8:] == '.symlink': 
       symlink = Symlink(os.path.join(dir_, dirName), os.path.join(os.path.expanduser('~'), dirName[:-8])) 

       # Add link to list of symbolic links to be made 
       symlinks.append(symlink) 

     # For every file in the subdirectory 
     for fileName in files: 

      # Check if file is marked for linking 
      if fileName[-8:] == '.symlink': 
       symlink = Symlink(os.path.join(dir_, fileName), os.path.join(os.path.expanduser('~'), fileName[:-8])) 

       # Add link to list of symbolic links to be made 
       symlinks.append(symlink) 

    print(symlinks) 
    print('Creating symbolic links...') 
    overwriteAll, skipAll = False, False 
    for link in symlinks: 
     link.createSymlink() 

    print("\nInstallation finished!") 

回答

0
currentDirectory = os.path.realpath(__file__) 

我想這就是問題所在 - currentDirectory是腳本路徑本身,而不是到腳本的父目錄。你也需要調用os.path.dirname()

currentDirectory = os.path.dirname(os.path.realpath(__file__)) 

Find current directory and file's directory