通过 Python 运行 Windows CMD 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5253206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:23:22  来源:igfitidea点击:

Run Windows CMD commands via Python

pythonwindowspython-3.xpopenmklink

提问by Felix Dombek

I want to create a folder with symlinks to all files in a large directory structure. I used subprocess.call(["cmd", "/C", "mklink", linkname, filename])first, and it worked, but opened a new command windows for each symlink.

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

I couldn't figure out how to run the command in the background without a window popping up, so I'm now trying to keep one CMD window open and run commands there via stdin:

我不知道如何在不弹出窗口的情况下在后台运行命令,所以我现在试图保持一个 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")

where

在哪里

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

However, I now get this error:

但是,我现在收到此错误:

File "mypythonfile.py", line 181, in makelink
cmdprocess.stdin.write("mklink " + linkname + " " + fullname + "\r\n")
TypeError: 'str' does not support the buffer interface

What does this mean and how can I solve this?

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

采纳答案by Greg Hewgill

Python strings are Unicode, but the pipe you're writing to only supports bytes. Try:

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

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