Python Forum

Full Version: run part of a script with a different version of Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
In my work environment, I have very little leeway with my the software configuration. I concurrently use two versions of python: a 2.xx version to access the API of another software and a 3.xx version for my personal developments.

I am developing a little software for myself and coworkers, and I'd like to keep the interface as simple as possible. My goal -- I'm starting to doubt it's feasible (let alone elegant...) -- is that the user can seamlessly write his custom script using functions relying on the 2.xx version (i.e. function relying on the external software) and functions for python 3.xx.

To make the matter a little more complicated, the 2.xx version needs to be invoked by the external software interpreter. The one thing that might save me is that the execution is quite sequential: pre-processing, processing and post-processing. Only the post-processing needs to be executed with python 3.xx.

So, if I had to reformulate my question, would anyone have an idea/suggestion how to write a script that will be executed by some python 2 interpreter, and at some point of the execution, will switch to another python (3) interpreter? The only avenue I can think of at the moment is to use a subprocess, but I don't think it fulfills all my requierements.

Thank you.
I think you need two processes. You might consider using remote procedure calls (RPC) to allow the Python 3 process to make calls in the Python 2 process. You could use XMLRPC wich exists in the standard library for both Python 2 and Python 3.

For example here is my Python 2 process
#!/usr/bin/env python2

from SimpleXMLRPCServer import SimpleXMLRPCServer

def is_even(n):
    return n % 2 == 0

server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(is_even, "is_even")
server.serve_forever()
Output:
λ python2 paillasse/pf/xserver.py Listening on port 8000... 127.0.0.1 - - [09/Jan/2024 18:02:33] "POST / HTTP/1.1" 200 - 127.0.0.1 - - [09/Jan/2024 18:02:33] "POST / HTTP/1.1" 200 -
And here is my Python 3 process
import xmlrpc.client

with xmlrpc.client.ServerProxy("http://localhost:8000/") as proxy:
    print("3 is even: %s" % str(proxy.is_even(3)))
    print("100 is even: %s" % str(proxy.is_even(100)))
Output:
λ python3 paillasse/pf/xclient.py 3 is even: False 100 is even: True
For more complete example, look in pymotw3 and also the Python 2 version pymotw2
Thanks for the suggestion. I had never heard of these, so worse case scenario, I have learned something new. But this gave me food for thoughts, I might be able to introduce this concept in my code.