views:

232

answers:

4

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

+12  A: 

\ (backslash) is an escape character within string constants, so your string ends up changed. Use double \s within string constants:

subprocess.Popen('rd /s /q .\\ProcessControlSimulator\\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
Bandi-T
I also suggest to check out the recommendation in other answers to check out the `os` module for functions doing file and directory manipulations.
Bandi-T
+2  A: 

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

Uri
+5  A: 

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)
Andrew Aylett
+1 for the mention of raw strings alone
D.Shawley
+8  A: 

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.

ghostdog74
Also, don't catch the exception. Let it fly - unless you're going to do something about it.
nosklo