1

我想为嵌套目录结构中的每个文件创建符号链接,其中所有符号链接都将放在一个大的平面文件夹中,并且现在具有以下代码:

# loop over directory structure:
# for all items in current directory,
# if item is directory, recurse into it;
# else it's a file, then create a symlink for it
def makelinks(folder, targetfolder, cmdprocess = None):
    if not cmdprocess:
        cmdprocess = subprocess.Popen("cmd",
                                  stdin  = subprocess.PIPE,
                                  stdout = subprocess.PIPE,
                                  stderr = subprocess.PIPE)
    print(folder)
    for name in os.listdir(folder):
        fullname = os.path.join(folder, name)
        if os.path.isdir(fullname):
            makelinks(fullname, targetfolder, cmdprocess)
        else:
            makelink(fullname, targetfolder, cmdprocess)

#for a given file, create one symlink in the target folder
def makelink(fullname, targetfolder, cmdprocess):
    linkname = os.path.join(targetfolder, re.sub(r"[\/\\\:\*\?\"\<\>\|]", "-", fullname))
    if not os.path.exists(linkname):
        try:
            os.remove(linkname)
            print("Invalid symlink removed:", linkname)
        except: pass
    if not os.path.exists(linkname):
        cmdprocess.stdin.write("mklink " + linkname + " " + fullname + "\r\n")

所以这是一个自上而下的递归,首先打印文件夹名称,然后处理子目录。如果我现在在某个文件夹上运行它,整个事情就会在 10 个左右的符号链接后停止。

该程序似乎仍在运行,但没有生成新的输出。它为文件夹中的某些文件# tag & reencode和前三个文件创建了 9 个符号链接ChillOutMix。cmd.exe 窗口仍然打开且为空,并在其标题栏中显示它当前正在处理ChillOutMix.

我尝试time.sleep(2)在每个之后插入一个cmdprocess.stdin.write,以防 Python 对于 cmd 进程来说太快了,但这没有帮助。

有谁知道问题可能是什么?

4

2 回答 2

0

最后试试这个:

if not os.path.exists(linkname):
    fullcmd = "mklink " + linkname + " " + fullname + "\r\n"
    print fullcmd
    cmdprocess.stdin.write(fullcmd)

看看它打印了什么命令。你可能会看到一个问题。

它可能需要在 arg 周围加上双引号mklink,因为它有时包含空格。

于 2011-03-10T00:19:59.390 回答
0

为什么不直接执行 mklink 呢?

于 2011-03-10T00:08:25.307 回答