我试图编写一个python脚本,该脚本遍历脚本当前所在目录中的所有目录,其子目录和目录中的文件名为" .symlink"然后在主目录中创建符号链接。
但我遇到了问题。脚本找不到任何目录或文件。我可能误用了walk方法。有什么建议吗?
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 :(得分:0)
currentDirectory = os.path.realpath(__file__)
我想这就是问题 - currentDirectory
是脚本本身的路径,而不是脚本的父目录。您还需要调用os.path.dirname()
currentDirectory = os.path.dirname(os.path.realpath(__file__))