通过Python运行Windows CMD命令

问题描述:

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

我无法弄清楚如何运行在没有窗口的背景命令弹出,所以我现在想保持一个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")) 
+0

啊。那是,谢谢。现在这整个事情停止工作10个左右的文件后...也许你也知道这件事?我在http://*.com/questions/5253835/yet-another-python-windows-cmd-mklink-problem-cant-get-it-to-work THX上提出了一个新问题 – 2011-03-09 23:57:52