Running Windows CMD Commands Through Python

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

I could not figure out how to run a command in the background without a popup, so now I am trying to open one CMD window and run the commands there via 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")

Where

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

However, now I 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 it?

+5
source share
1 answer

Python strings are Unicode, but the pipe you write only supports bytes. Try:

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

All Articles