Skip to content Skip to sidebar Skip to footer

Why This Dos Command Does Not Work Inside Python?

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. su

Solution 1:

\ (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)

Solution 2:

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 ospath = 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.

Solution 3:

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)

Solution 4:

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

Post a Comment for "Why This Dos Command Does Not Work Inside Python?"