Python wait for shell command to complete

I run a script to untie some files and then delete the rar files. I do this by executing a command through the shell. I tried several different ways to make the script wait until it decompresses the files, but it still continues and deletes the file before it is used.

I tried the code below which does not go. I tried to see if I can make wait () work, but also no luck.

Any ideas? launch python 2.7

EDIT: I want the script to execute the command :)

p = subprocess.Popen('unrar e ' + root + '/' + i + ' ' + testfolder, bufsize=2048, shell=True, stdin=subprocess.PIPE) p.stdin.write('e') p.communicate() for root, dirs, files in os.walk(testfolder): for i in files: print 'Deleting rar files' os.remove(i) for i in os.listdir(testfolder): if os.path.isdir(testfolder + i): shutil.rmtree(testfolder + i) 
+4
source share
2 answers

This evil:

 p = subprocess.Popen('unrar e ' + root + '/' + i + ' ' + testfolder, bufsize=2048, shell=True, stdin=subprocess.PIPE) 

Instead of this

 p = subprocess.Popen(['unrar', 'e', '%s/%s' % (root, i), testfolder], bufsize=2048, stdin=subprocess.PIPE) p.stdin.write('e') p.wait() if p.returncode == 0: pass # put code that must only run if successful here. 

By Popen exact array, not a string, to Popen and not using shell=True , a file name with a space in it cannot be interpreted as more than one argument or a subshell command or some other potentially malicious one (think of a file with $(rm -rf ..) in his name).

Then after calling p.wait() (there is no need for p.communicate() when you are not doing stderr or stdout), you should check p.returncode to determine if the process was successful, and only continue deleting files if p.returncode == 0 (indicating success).

An initial diagnosis that p.communicate() returns while the unrar process is still running is not possible; p.communicate() and p.wait() do not work.


If you use ssh , this will change a bit:

 import pipes # in Python 2.x; in 3.x, use shlex.quote() instead p = subprocess.Popen(['ssh', ' '.join( [pipes.quote(s) for s in ['unrar', 'e', '%s/%s' % (root, i), testfolder]]) 
+5
source

Whether your problem is waiting on a subprocess or performing an order (which means unpacking and then uninstalling).

If your problem is waiting for a subprocess, you should check the subprocess.call function

Check:

http://docs.python.org/2/library/subprocess.html#module-subprocess

This function is blocked until another process is completed.

If your problem, however, decompresses the files, and you don’t have to use a subprocess, then just check any other library to decompress, for example pyunrar2:

or other:

+1
source

All Articles