通过Python运行Windows CMD命令

5

我想创建一个文件夹,其中包含指向大型目录结构中所有文件的符号链接。我首先使用了subprocess.call(["cmd", "/C", "mklink", linkname, filename]),它有效了,但是每个符号链接都会打开一个新的命令窗口。

我无法找到在后台运行命令而不弹出窗口的方法,因此现在我尝试保持一个CMD窗口打开,并通过stdin在其中运行命令:

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")

在哪里

cmdprocess = subprocess.Popen("cmd",
                              stdin  = subprocess.PIPE,
                              stdout = subprocess.PIPE,
                              stderr = subprocess.PIPE)

然而,我现在遇到了这个错误:
File "mypythonfile.py", line 181, in makelink
cmdprocess.stdin.write("mklink " + linkname + " " + fullname + "\r\n")
TypeError: 'str' does not support the buffer interface

这是什么意思?我该如何解决这个问题?
1个回答

1

Python字符串是Unicode,但你正在写入的管道只支持字节。尝试:

cmdprocess.stdin.write(("mklink " + linkname + " " + fullname + "\r\n").encode("utf-8"))

啊,好的。谢谢你。现在,在处理大约10个文件后,这整个东西就停止工作了...也许你还知道其他的解决办法吗?我在http://stackoverflow.com/questions/5253835/yet-another-python-windows-cmd-mklink-problem-cant-get-it-to-work发了一个新的问题。谢谢。 - Felix Dombek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接