为什么这个 dos 命令在 python 中不起作用?
我尝试将批处理文件中的一些 dos 命令移至 python 中,但出现此错误,对于以下语句,文件名、目录名或卷标语法不正确。
subprocess.Popen('rd /s /q .\ProcessControlSimulator\bin', shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
如果我只是将该 dos 命令复制到窗口控制台中,它就可以工作。 os.getcwd() 给了我预期的工作目录。
我的问题是: 1. 这是为什么? 2.如何避免这种情况?我是否需要获取当前工作目录并为该命令构建抽象路径?怎么办?
谢谢
I try to move some dos command from my batch file into python but get this error, The filename, directory name, or volume label syntax is incorrect, for the following statement.
subprocess.Popen('rd /s /q .\ProcessControlSimulator\bin', shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
if I just copy that dos command into window console, it works. The os.getcwd() gave me expected working directory.
My questions are:
1. why is that?
2. how to avoid that? do I need to get current working directory and construct an abstract path for that command? how to do that?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
\
(反斜杠)是字符串常量中的转义字符,因此您的字符串最终会发生变化。在字符串常量中使用双\
(如\\
):\
(backslash) is an escape character within string constants, so your string ends up changed. Use double\
s (like so\\
) within string constants:我的建议是尽量不要使用不必要的系统命令。您正在使用 Python,因此请使用它附带的可用模块。据我所知,您正在尝试删除目录,对吗?然后你就可以使用shutil这样的模块了。示例:
还有其他的,例如 os.removedirs、os.remove 您可以从文档中查看。
My advice is try not to use system commands unnecessarily. You are using Python, so use the available modules that come with it. From what i see, you are trying to remove directories right? Then you can use modules like shutil. Example:
there are others also, like os.removedirs, os.remove you can take a look at from the docs.
你有未转义的反斜杠。您可以使用 python 原始字符串来避免转义斜杠,或者将它们加倍:
或
You've got unescaped backslashes. You can use a python raw string to avoid having to escape your slashes, or double them up:
or
你不能只是一对一地复制它。例如,您的转义字符 () 变得不正确。在这种情况下,您可能需要双 \ 。
另外,还有用于创建和终止目录的特定 API 调用,请查看 os.path
You can't just copy it one-to-one. For example, your escape characters () become incorrect. You may need a double \ in this case.
Also, there are specific API calls for creating and killing directories, look at os.path