4

I have a script file (.py) which I need to run in my POST API requests. The scripts have few input parameters as well.

I am able to follow the link: https://django-extensions.readthedocs.io/en/latest/runscript.html and now I am successfully able to run a script from the shell.

python manage.py runscript scriptName --script-args arg1 arg2

But now, I want to run the same script with arguments in my API where arguments will be posted from the POST requests. I found that I can use subprocess for it. But it's not working.

Below is the code I am trying to run:

cmd = subprocess.Popen(['scriptName', arg1, arg2], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, err = cmd.communicate()

On executing the above code the script file opens up in the browser.

NOTE: The script which I am executing contains Machine Learning Code.

Please help me out and let me know what I am doing wrong here. I also need the output of the script to return as a response.

10
  • what is the error showing on console? Commented Mar 25, 2019 at 7:55
  • @NakulNarayanan It is not executing the script but opening the script file in the browser. Commented Mar 25, 2019 at 7:57
  • I didn't understand.. Commented Mar 25, 2019 at 7:59
  • 2
    Why are you running a python script as a subprocess, rather than just executing the code directly in your program? Commented Mar 25, 2019 at 8:38
  • 1
    But why not just import it and call it from the view? Commented Mar 25, 2019 at 8:56

1 Answer 1

3

Here is a working code

DjangoProject/Project/view.py

from rest_framework.generics import ListAPIView
from rest_framework.response import Response
import os

class MyView(ListAPIView):
    def post(self,request):
        message = self.request.POST.get('message','')
        os.system('python cout.py '+message)
        return Response(
            {
                "Status":True
            }
        )

my python script on the root django folder

DjangoProject/cout.py

import sys
print("Python : ",sys.argv[1])

with post man you can send a post request with form data 'message' and you can see that message on your console

Example: In postman

message = hi jasir 

In your console :

Python : hi jasir
Sign up to request clarification or add additional context in comments.

1 Comment

a minimalist approach. nice

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.