Why is this dos command not working inside python?

I am trying to move some dos command from my batch file in python but get this error. The file name, 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 this dos command to the window console, it works. The os.getcwd () command gave me the expected working directory.

My questions: 1. Why? 2. How to avoid this? Do I need to get the current working directory and build an abstract path for this command? how to do it?

thank

+3
source share
4 answers

\ ( ) escape- , . double \ (, \\) :

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

, . 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, os.remove, .

+9

. python, :

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

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

You cannot just copy it one to one. For example, your escape characters () become invalid. In this case, you may need double \.

In addition, there are special API calls to create and destroy directories, look at os.path

+2
source

Source: https://habr.com/ru/post/1729247/


All Articles