通过Python运行Windows CMD命令

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

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

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

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

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