[英]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. 我首先使用了subprocess.call(["cmd", "/C", "mklink", linkname, filename])
,但它工作正常,但为每个符号链接打开了一个新的命令窗口。
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: 我无法弄清楚如何在没有窗口弹出的情况下在后台运行命令,所以我现在试图保持一个CMD窗口打开并通过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. Python字符串是Unicode,但您写入的管道仅支持字节。 Try: 尝试:
cmdprocess.stdin.write(("mklink " + linkname + " " + fullname + "\r\n").encode("utf-8"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.