2011-03-09 170 views
5

我想創建一個符號鏈接到大型目錄結構中所有文件的文件夾。我首先使用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 

這是什麼意思,以及如何我能解決這個問題嗎?

回答

1

Python字符串是Unicode的,但是您要寫入的管道只支持字節。試試:

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

啊。那是,謝謝。現在這整個事情停止工作10個左右的文件後...也許你也知道這件事?我在http://stackoverflow.com/questions/5253835/yet-another-python-windows-cmd-mklink-problem-cant-get-it-to-work THX上提出了一個新問題 – 2011-03-09 23:57:52