Run external command from Python 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&gt; tmp_01.txt;ls -ltr &gt;&gt;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?
Give a try to shutil and subprocess.

To copy all the files:
http://docs.python.org/2/library/shutil.html#shutil.copyfile

import shutil
shutil.copy(src_file, destination_file)


To make the system calls:
http://docs.python.org/2/library/subprocess.html#subprocess.check_call

import subprocess
subprocess.check_call('ls -al', shell=True)