开发者

Run Windows CMD commands via Python

开发者 https://www.devze.com 2023-02-16 08:44 出处:网络
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, bu

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?


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"))
0

精彩评论

暂无评论...
验证码 换一张
取 消