Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Windows CMD commands via Python

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.

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:

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?

like image 856
Felix Dombek Avatar asked Nov 15 '22 02:11

Felix Dombek


1 Answers

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

cmdprocess.stdin.write(("mklink " + linkname + " " + fullname + "\r\n").encode("utf-8"))
like image 166
Greg Hewgill Avatar answered Dec 12 '22 03:12

Greg Hewgill