Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call python3 code from python2 code

I am designing a GUI using the wxPython toolkit, which means it's being written in python2. However, I want to use python3 for the actual application code. How would I go about calling my python3 code from the GUI?

like image 829
Matthew G Avatar asked Jul 15 '13 22:07

Matthew G


People also ask

How do I run Python 3 code in Python 2?

To use the Python 3 processor for Python code within a program block, use BEGIN PROGRAM PYTHON3-END PROGRAM . By default, Python scripts that are run from the SCRIPT command are run with the Python 2 processor. To run a script that uses the Python 3 processor, use PYTHONVERSION=3 on the SCRIPT command.

Are Python 2 and 3 compatible with each other?

The latest stable version is Python 3.9 which was released in 2020. The nature of python 3 is that the changes made in python 3 make it incompatible with python 2. So it is backward incompatible and code written in python 3 will not work on python 2 without modifications.

Is Python 3 backward compatible with Python 2?

Python version 3 is not backwardly compatible with Python 2. Many recent developers are creating libraries which you can only use with Python 3. Many older libraries created for Python 2 is not forward-compatible.

Why are Python 2 and 3 not compatible?

Basically, developers deliberately made python 3 not backwards compatible, for two main reasons: First of all, they wanted to change some things integral to python 2, and while the differences seemed small, the improvements that they had made would not have combined well with the existing structure.


2 Answers

  1. Talk over a pipe or socket

  2. Enable such python 3 features as you can from __future__ or use a library like six to write code which is compatible with both.

  3. Don't do this.

Finally, are you sure you can't use wxPython in Python 3? There's nothing in the online docs saying you can't.

like image 167
Marcin Avatar answered Nov 07 '22 07:11

Marcin


You can run the application code as a shell script.

from subprocess import call
exit_code = call("python3 my_python_3_code.py", shell=True)

You can also pass in terminal arguments as usual.

arg1 = "foo"
arg2 = "bar"
exit_code = call("python3 my_python_3_code.py " + arg1 + " " + arg2, shell=True)

If you want to collect more information back from the application you can instead capture stdout as describe here: Capture subprocess output

If you want to fluidly communicate in both directions a pipe or socket is probably best.

like image 27
eadsjr Avatar answered Nov 07 '22 06:11

eadsjr