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
\
(backslash) is an escape character within string constants, so your string ends up changed. Use double \
s (like so \\
) within string constants:
subprocess.Popen('rd /s /q .\\ProcessControlSimulator\\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
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:
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"
there are others also, like os.removedirs, os.remove you can take a look at from the docs.
You've got unescaped backslashes. You can use a python raw string to avoid having to escape your slashes, or double them up:
subprocess.Popen(r'rd /s /q .\ProcessControlSimulator\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
or
subprocess.Popen('rd /s /q .\\ProcessControlSimulator\\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
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