为什么这个dos命令在python中不起作用?

2024-06-09 17:40:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一些dos命令从批处理文件移到python中,但得到以下语句的文件名、目录名或卷标语法不正确。在

subprocess.Popen('rd /s /q .\ProcessControlSimulator\bin', shell=True, 
                  stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

如果我把dos命令复制到窗口控制台,它就可以工作了。这个操作系统getcwd()给了我预期的工作目录。在

我的问题是: 1为什么? 2如何避免呢?我需要获取当前工作目录并为该命令构造一个抽象路径吗?怎么做?在

谢谢


Tags: 文件命令目录truebin文件名rd语句
3条回答

我的建议是尽量不要不必要地使用系统命令。您使用的是Python,因此请使用它附带的可用模块。从我看来,你是在试图删除目录,对吗?然后你可以使用像shutil这样的模块。示例:

import shutil
import os
path = os.path.join("c:\\","ProcessControlSimulator","bin") #example only
try:
    shutil.rmtree(path)
except Exception,e:
    print e
else:
    print "removed"

还有其他人,比如os.removedirs操作系统, 操作系统删除你可以看看文件。在

\(反斜杠)是字符串常量中的转义字符,因此字符串最终被更改。在字符串常量中使用双\s(如so\\): 在

subprocess.Popen('rd /s /q .\\ProcessControlSimulator\\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

你的反斜杠没有被转义。可以使用python原始字符串来避免必须转义斜杠或将斜杠加倍:

subprocess.Popen(r'rd /s /q .\ProcessControlSimulator\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

或者

^{pr2}$

相关问题 更多 >