Is there a way to call python3.8 code, from python3.11?

192 Views Asked by At

I have some code that breaks in python3.11 for some reason, namely paddleocr. I want to integrate it in a program that is otherwise written in python3.11.

Although there is the obvious method of running paddleocr in a web service, and calling it from the rest of the program through that service, or maybe through that method, I am wondering if there is a better method that exists to do this.

In summary, is there a way to call a function in a python3.8 environment from a python3.11 environment, in a more direct manner than creating an API?

1

There are 1 best solutions below

3
On

Running Python code written for a specific version like Python 3.8 in an environment/program using Python 3.11 can indeed pose compatibility issues, especially with libraries (in this case, paddleocr) that may have dependencies not yet compatible with newer versions of Python.

While setting up a web service and calling it through an API is a common solution, there is a direct and local way of doing it: You can use Python's subprocess module to run a script with Python 3.8 from your Python 3.11 program. This method involves invoking the Python 3.8 interpreter as a subprocess and then running the necessary Python script or command.

import subprocess
result = subprocess.run(["path/to/python3.8", "path/to/script.py", "arg1", "arg2"], capture_output=True, text=True)
print(result.stdout)

While this method is more direct than an API, it's somewhat less flexible and can be more challenging to manage, especially for complex interactions.

Notes:

  • The above solution using subprocess will not work if you are using a virtual environment because the Python 3.8 executable may not have all the required Python packages installed. Thanks Bill Huneke for pointing that out.
  • Rather than setting up a web service and calling it through an API, implementing a message queue (like RabbitMQ or Kafka) between the two Python environments can be another solution. The Python 3.11 program sends messages (tasks) to the queue, which are then consumed by a worker running in the Python 3.8 environment. This method is beneficial if the tasks are asynchronous and do not require immediate response.