Python Windows CMD mklink停止工作,无错误信息

1 投票
2 回答
3527 浏览
提问于 2025-04-16 13:24

我想为一个嵌套的文件夹结构中的每个文件创建符号链接(symlink),并把所有的链接放到一个大的平坦文件夹里。目前我有以下的代码:

# 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个符号链接后就停止了。

程序似乎还在运行,但没有新的输出产生。它为一些文件创建了9个符号链接,分别在 # tag & reencodeChillOutMix 文件夹中的前三个文件。cmd.exe窗口仍然打开且是空的,标题栏显示它正在处理 ChillOutMix 中第三个文件的mklink命令。

我尝试在每个 cmdprocess.stdin.write 后面插入一个 time.sleep(2),以防Python运行得太快跟不上cmd进程,但这并没有帮助。

有没有人知道可能是什么问题呢?

2 个回答

0

试试在最后加上这个:

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

看看它打印了什么命令。你可能会发现问题。

因为有时候 mklink 的参数里会有空格,所以可能需要在它周围加上双引号。

0

为什么不直接执行 mklink 呢?

撰写回答