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. The external program makes many temporary files (which conflict with other instance of same program).

My strategy is:

  1. get current directory (native) path
  2. change to temp directory
  3. run external command
  4. copy output to native directory
  5. 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:

  1. Is it right or is there a simpler way to do it?
  2. Do I need to remove the tmp directory?
  3. 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?
share|improve this question

closed as off-topic by 200_success May 27 '14 at 3:52

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions must involve real code that you own or maintain. Questions seeking an explanation of someone else's code are off-topic. Pseudocode, hypothetical code, or stub code should be replaced by a concrete example." – 200_success
If this question can be reworded to fit the rules in the help center, please edit the question.

    
This code doesn't appear to do anything useful, so I've classified it as hypothetical / example code, which would be off-topic for Code Review. –  200_success May 27 '14 at 3:53

1 Answer 1

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
    
Please avoid shell and prefer using list arguments instead –  Antti Haapala May 26 '14 at 18:22
    
Also, these are not system calls –  Antti Haapala May 26 '14 at 18:22

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