tags:

views:

79

answers:

5

Sorry if this is a duplicate - couldn't find an answer by searching.

How can I run a Unix command from within a Django views file? I want to run a 'cp' command to copy a file that's just been uploaded.

Thanks in advance.

+1  A: 

In Python:

import os
if os.system("cp file1 file2") == 0:
    # success
else:
    # failure
Lucas Jones
Great. Thanks. Should have searched for Python!
AP257
+10  A: 

Why command line cp?

Use Python's builtin copyfile() instead. Portable and much less error-prone.

import shutil
shutil.copyfile(src, dest)
Yuval A
definitely true, use the python builtin.
Michael
A: 

I'd recommend subprocess.Popen() for the general case. It's more flexible than os.system().

Mike DeSimone
+3  A: 

In fact, the preferred way to run system program is to use the subprocess module, like:

import subprocess    
subprocess.Popen('cp file1 file2',shell=True).wait()

Subprocess module is a replacement for os.system and other older modules and functions, see http://docs.python.org/library/subprocess.html

Of course if you need just to copy files you may use more convenient function copyfile from shutil module

dragoon
A: 

It's better to use Popen/PIPE for that kind of stuff.

from subprocess import Popen, PIPE

def script(script_text):
     p = Popen(args=script_text,
               shell=True,
               stdout=PIPE,
               stdin=PIPE)

     output, errors = p.communicate()
     return output, errors

script('./manage.py sqlclear my_database_name')  

I would not recommend using os.system since it has got a number of limitations.

As Python documentation says:

This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command.

Art