-1

I have a script that uses a library that is not available in python 3. I used the answer (execnet) to this question to call the python 2 script X from a python 3 script Y. This works fine without any problem. I added both scripts to the directory of the Django app I want to use script X in. Testing script Y still works. Importing script Y to be called from views.py works. Calling the function in Y form views.py works. But now script Y does not find script X anymore.

The Django error says ImportError: No module named X

If I add the script n the settings.py script to INSTALLED_APPS I get

ModuleNotFoundError: No module named 'X'.

Is there an easier way to run a python2 script from django 3?

1 Answer 1

1

I don't recommend doing this, but if you're really up the creek:

  • create a Python 2 virtualenv for your Python 2 script called something like py_env
  • install the package you need into py2_env

Then, in the view (which is running Python 3+ and Django 2+):

from subprocess import check_output
from django.views.generic import TemplateView

class MyView(TemplateView):
    template_name = "my_app/my_template.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["program_output"] = check_output(
            "source /path/to/py2_env/bin/activate && /path/to/py2_script.py",
            shell=True,
        ).decode("utf-8")
        return context

This example will run the Python 2 script from the view and put the output of the program into the context as program_output. Good luck!

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.