python - 通过 Python 运行 Windows CMD 命令

标签 python windows python-3.x popen mklink

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

我无法弄清楚如何在不弹出窗口的情况下在后台运行命令,所以我现在试图让一个 CMD 窗口保持打开状态并通过标准输入在那里运行命令:

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

这是什么意思,我该如何解决?

最佳答案

Python 字符串是 Unicode,但您写入的管道仅支持字节。尝试:

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

关于python - 通过 Python 运行 Windows CMD 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5253206/

相关文章:

c++ - Windows.h CONDITION_VARIABLE 导致异常 (C/C++)

python - BS4 + Python3 : unable to crawl tree: 'NavigableString' object has no attribute 'has_attr'

python - 制作一个新字典,删除一些键并且不更改原始字典

python - 函数的返回值可以在where子句中传递吗

Python 3 - 键错误 0

python - 在 Keras 中制作自定义规范化层(每个功能)

Python - 通过 enumerate() 迭代和替换列表索引

python - 在 Sanic 中使用 asyncpg 连接池

windows - F# 使用 WinForms 拖放 : DragDrop event of a control does not call the referenced member function

java - 使用 java.awt.Toolkit 捕获全局按键