Calling Python 2 script from Python 3

前端 未结 7 2114
青春惊慌失措
青春惊慌失措 2020-12-01 02:00

I have two scripts, the main is in Python 3, and the second one is written in Python 2 (it also uses a Python 2 library).

There is one method in the Python 2 script

7条回答
  •  醉梦人生
    2020-12-01 02:46

    Calling different python versions from each other can be done very elegantly using execnet. The following function does the charm:

    import execnet
    
    def call_python_version(Version, Module, Function, ArgumentList):
        gw      = execnet.makegateway("popen//python=python%s" % Version)
        channel = gw.remote_exec("""
            from %s import %s as the_function
            channel.send(the_function(*channel.receive()))
        """ % (Module, Function))
        channel.send(ArgumentList)
        return channel.receive()
    

    Example: A my_module.py written in Python 2.7:

    def my_function(X, Y): 
        return "Hello %s %s!" % (X, Y)
    

    Then the following function calls

    result = call_python_version("2.7", "my_module", "my_function",  
                                 ["Mr", "Bear"]) 
    print(result) 
    result = call_python_version("2.7", "my_module", "my_function",  
                                 ["Mrs", "Wolf"]) 
    print(result)
    

    result in

    Hello Mr Bear!
    Hello Mrs Wolf!
    

    What happened is that a 'gateway' was instantiated waiting for an argument list with channel.receive(). Once it came in, it as been translated and passed to my_function. my_function returned the string it generated and channel.send(...) sent the string back. On other side of the gateway channel.receive() catches that result and returns it to the caller. The caller finally prints the string as produced by my_function in the python 3 module.

提交回复
热议问题