I have to run an external program from Python. The external program makes many temporary files (which conflict with other instance of same program).
My strategy is:
- get current directory (native) path
- change to temp directory
- run external command
- copy output to native directory
- change back to native directory
Here is my code:
import os, tempfile
current_dir = os.getcwd()
tmp_dir = tempfile.mkdtemp()
input_file, outfile = 'input_file', 'result'
os.system('cp %s %s' %(input_file, tmp_dir))
os.chdir(tmp_dir)
cmd = 'pwd> tmp_01.txt;ls -ltr >>tmp_01.txt' ##system command goes here
os.system(cmd)
os.system('cp tmp_01.txt %s/%s' %(current_dir, outfile))
os.chdir(current_dir)
My questions are:
- Is it right or is there a simpler way to do it?
- Do I need to remove the tmp directory?
- Is it safe to use this code as Python module/class in a web application? Does it make shell injection easy, or can it possible reveal more information than needed?