Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best method to call a Python 3.x program from within Python 2.x?

I'm writing a Django web application. As of now, Django does not support Python 3. For the purposes of my web application, and without getting into to much detail, I essentially need to use some libraries that only support Python 3. Suffice it to say that after much thorough research no 2.x alternative was found.

So my question is this: How should I go about this?

I have both Python 2 and 3 installed on my server, and I have the Python 3 code written and waiting to be called. I was considering simply using the subprocess module, effectively calling Python 3 from the command line, but the question is, is this the best method or is there a best practice I could use instead here? Using subprocess seems pretty hackish to me. Don't get me wrong, I'm okay with hackish, I just want to make sure there's nothing else I should be doing instead.

like image 352
Ken Bellows Avatar asked Nov 15 '11 15:11

Ken Bellows


2 Answers

Since the Python 3 and Python 2 interpreters are totally separate executables and have separate libraries installed on your system, using subprocess to invoke one from the other is the best practice. It's not a hack at all. There are a number of ways to pass data between them but the two interpreters should be run as separate processes.

That said, you may need to keep in mind the startup time associated with launching an interpreter process. That gets back to how to pass data between the two processes. If your Python 2 code is going to be frequently calling the Python 3 routines, you may need to structure the Python 3 program as a daemon. But you would still use subprocess to launch it.

like image 171
Ned Deily Avatar answered Dec 09 '22 19:12

Ned Deily


Run the 3.x program as a separate service and then connect using some kind of RPC mechanism?

like image 39
Noufal Ibrahim Avatar answered Dec 09 '22 20:12

Noufal Ibrahim