Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have to run an external program from python. 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 there are simple 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 makes shell injection essay or can possible reveal more information then needed?

share|improve this question
add comment

1 Answer

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)
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.