I understand this question has been asked before but the methods adviced don't work for me. This is what I want to do from my Django view:
sudo python mypythonscript.py arg1 arg2 > mypythonscript.log
If I execute this from command line it works like a charm but can't get it to work through django views. I have tried using os.system(command) and subprocess.call(command, shell=True) but they don't work. Thanks in advance.
EDIT: This is my views.py:
from django.http import HttpResponse
import datetime
import subprocess
def li_view(request):
if request.is_ajax():
if request.method == 'GET':
message = "This is an XHR GET request"
elif request.method == 'POST':
message = "This is an XHR POST request"
print request.POST
else:
message = "No XHR"
num_instances = request.POST['num_instances']
ami_id = "ami-ff02058b"
command = "sudo python /home/bitnami/launch_instances.py 1 " + num_instances + " " + ami_id + " > /home/bitnami/launcinstances.log"
subprocess.call(commad, shell=True)
return HttpResponse("something creative will go here later")
The whole story is that I have a form on my website and I want to pass the contents of that form as arguements to my launch_instances.py script. When I press the submit button in my form it posts to /luanch_instances/ which 'redirects' to this view. Executing the code as it is will do nothing, it'll simply just show me "something creating will go here later" on a new page. If I was to how ever use
suprocess.check_call(command, shell=True)
This is what I get:
Command 'sudo python /home/bitnami/launch_instances.py 1 ami-ff02058b > /home/bitnami/launchinstances.log' returned non-zero exit status 2
As you're trying to run python script, you may simply import code from launch_instances.py into your view, redirect output to /home/bitnami/launcinstances.log (about redirecting stdout to file in python: Redirect stdout to a file in Python?). But there's still problem with root privileges - one option is to change permissions of: resources needed for calling code from launch_instances.py; your log file; to allow your django process to execute that, second option (not recommended) is to run django app as root.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With