Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python subprocess.Popen to create a new directory

Tags:

python

I know that I can create a new directory with the os module. But I was trying to create a new directory with the subprocess module as follows:

p=subprocess.Popen("mkdir extractions", shell=True)
os.chdir("extractions")

When the script executes, I notice that the directory extractions is created but the next os.chdir call fails saying the directory extractions does not exist. I know that I am missing something in terms of using subprocess that makes the next line unaware of the directory created. Please help!

like image 927
NPE Avatar asked Oct 11 '25 15:10

NPE


2 Answers

You probably want to call p.wait() to wait for the mkdir to complete, before calling os.chdir. Or even better, use (stdout, stderr) = p.communicate(), and check the result.

like image 139
happydave Avatar answered Oct 14 '25 04:10

happydave


Why dont you use os.mkdir("extractions")? You could even use subprocess.call("mkdir extractions") Both of those methods will work After Popen, you have to do something like communicate()

p1 = subprocess.Popen('mkdir extractions', shell=True)
p1.communicate()

However, this is the same as just using subprocess.call("mkdir extractions", shell=True).

like image 32
mehtunguh Avatar answered Oct 14 '25 04:10

mehtunguh