Sunday, May 26, 2013

Some tips on python's subprocess module

Here is a weird case I faced when using Subprocess module, or because I do not know deep enough about it:

As you knew, we can execute terminal shell script by calling subprocess: for example, we want to archive all of the pdf file to a tar ball, and delete all of pdf file after that:

>>> import subprocess
>>> tar_path = "/home/projects/mytar.tar.gz"
>>> files_path = "/home/projects/*.pdf"
>>> command = ["tar", "-cvvf", tar_path, files_path, "--remove-files"]

But, those above command will add all pdf files including their path to the tar ball.

I found a solution, and it's pretty easy: instead of declaring command as a list, stating it as a string of command

>>> command = 'tar -cvvf ' + tar_path + ' ' + files_path + ' --remove-files'
>>>, shell=True)

(Be careful with 'shell=True')