How to embed python2 into python3?

Ian Kelly ian.g.kelly at gmail.com
Wed May 16 14:10:30 EDT 2012


On Wed, May 16, 2012 at 8:59 AM, ytj <ytj000 at gmail.com> wrote:
> Hello, all:
>
> I have two programs, one is written in py3k, the other is written in
> python 2. I am wondering how to make them work together except port
> the python 2 code to py3k? Is that possible to expose python2's
> function to py3k? In other words, I want to embed the Python 2
> interpreter into my py3k program. So I can call python2's function in
> py3k's code.

I think you're likely to run into conflicts doing that.  Here's the
result of a quick test using ctypes:

Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import *
>>> python27 = cdll.python27
>>> python27.Py_Initialize()
  File "c:\python32\lib\site.py", line 159
    file=sys.stderr)
        ^
SyntaxError: invalid syntax

For some reason, even though I loaded the Python 2.7 DLL, it's then
trying to import the Python 3.2 libraries.  My suggestion: instead of
embedding, use the subprocess module, and keep both Python
interpreters firmly entrenched in separate processes.

Cheers,
Ian



More information about the Python-list mailing list