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.
Why command line cp?
Use Python's builtin copyfile() instead. Portable and much less error-prone.
import shutil
shutil.copyfile(src, dest)
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
In Python:
import os
if os.system("cp file1 file2") == 0:
# success
else:
# failure
I would use iterpipes, which reduces the 'By Hemidall's beard, what foul syntax!' one tends to think when working with subprocess.
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.