2

I am trying to execute a Python script from within my Django app. I tried executing it from the terminal and it works correctly, so I know the called Python script is working fine. The Python scripts calls an external program which overwrites a file on the server. The external program has all required permissions. I even tried using 777 permissions for all files involved, but still no use.

Django View:

import subprocess
subprocess.call("python " + script_dir+"testScript.py", shell=True)

Python - 2.7

I can execute simpler commands like

subprocess.call("rm " + script_dir+"test.txt", shell=True)

EDIT: I am not only executing python scripts from the terminal, I also need to execute a blender script, which again works fine by itself(when executed directly from the terminal) but does not generate the required output from within django.

This was the error as in my Django console :

OSError at /getObj/

[Errno 2] No such file or directory

Request Method:     GET
Request URL:    http://192.168.1.21:8081/getObj/?width=5.0&height=6.0&depth=7.0
Django Version:     1.7.8
Exception Type:     OSError
Exception Value:    

[Errno 2] No such file or directory

Exception Location:     /usr/lib/python2.7/subprocess.py in _execute_child, line 1327
Python Executable:  /usr/bin/python
Python Version:     2.7.6
7
  • 2
    Why would you call a Python script via subprocess? Why not import it and call it directly? Commented Jul 10, 2015 at 11:57
  • actually I need to run 3 scripts from the Django app, 2 of which are not directly python scripts. So I need to use subprocess anyway. Though you do have a point there. Commented Jul 10, 2015 at 12:13
  • What the error you got? Commented Jul 10, 2015 at 12:21
  • 1
    You specified wrong path to file. Write to log the string script_dir+"testScript.py" Make sure it's absolute Commented Jul 10, 2015 at 12:38
  • I checked the path just before the function call. It is indeed absolute. Commented Jul 10, 2015 at 12:44

1 Answer 1

2

First, I'd suggest to run Python code by importing it, not running it in a separate process (unless you have special reasons to do that). Since you mentioned other non-Python scripts you want to run, I'll suggest a generic way.

I would try and run the script using Popen like this:

from subprocess import Popen, PIPE

# ...

p = Popen(["python", "testScript.py"], cwd=script_dir, stdout=PIPE, stderr=PIPE)
out, err = p.communicate()

Then you have standard output in out and standard error output in err. Even if it doesn't run successfully, you have something to work with after inspecting the two variables.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.