【问题标题】:Python Windows CMD mklink, stops working without error messagePython Windows CMD mklink,停止工作而没有错误消息
【发布时间】:2011-03-09 23:54:10
【问题描述】:

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

# 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 &amp; reencode 中的一些文件和ChillOutMix 文件夹中的前三个文件创建了9 个符号链接。 cmd.exe 窗口仍然打开且为空,并在其标题栏中显示它当前正在处理 ChillOutMix 中第三个文件的 mklink 命令。

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

有谁知道问题出在哪里?

【问题讨论】:

  • 这与您的问题无关,但您是否考虑过使用os.walk() 而不是递归?它可能会更简单。

标签: python windows cmd popen mklink


【解决方案1】:

为什么不直接执行 mklink 呢?

【讨论】:

  • 因为不是windows命令,是cmd命令,需要在cmd中运行。 subprocess.call("mklink") 导致WindowsError: [Error 2] The system cannot find the specified file
  • 对不起,我没有意识到这一点。我要尝试的下一件事是 cmd /c mklink
  • 当然,这就是我所做的,但我想创建数千个符号链接,并认为如果我为每个 mklink 命令只使用一个 cmd.exe 进程,这会更快。然而,它没有成功。我的电脑似乎只是在几个命令后关闭了管道,我不知道为什么。所以我最后不得不按照你说的方式去做:subprocess.call("cmd", "/c", "mklink", linkname, filename) 用于每个链接。使用shell = True 之类的,我什至设法抑制了 cmd 窗口。
  • 在这种情况下,使用 ctypes 直接调用msdn.microsoft.com/en-us/library/aa363866.aspx 可能更容易。
【解决方案2】:

最后试试这个:

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

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

mklink 的 arg 可能需要双引号,因为它有时包含空格。

【讨论】:

  • 我实际上使用了引号,但我还是尝试了你的方法——命令绝对没问题。
  • 也许CMD只能接受这么多命令?尝试喂它别的东西,比如 dir &gt;&gt;dummy.txt 重复 100 次,看看会发生什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-09
  • 1970-01-01
  • 1970-01-01
  • 2014-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多