Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to import 2.7 module into 3.4 program?

Question:

Is it possible to import a module I wrote in python 2.7 into a 3.4 program that I wrote?

Background:

I've tried doing this and as expected it throws a SyntaxError: Invalid Syntax, once it sees the first print "string literal" statement instead of 3.4's print(). There are a few additional incompatible code snippets, like import Tkinter instead of tkinter. The 2.7 module must remain in 2.7 because one of its dependencies doesn't seem to work in 3.X (a python binding for the switchvox api).

I'm building a display app that will call any module specified in its config file and display that module's output (a string, or in the future possible a dict) in a tkinter widget. All my program needs to do is import the 2.7 module and call one function once (every x number of seconds) to receive that string of data.

like image 519
AllTradesJack Avatar asked Oct 20 '22 05:10

AllTradesJack


1 Answers

You can make your python 2.7 code be 3.4 compatible - this way you can import it from 3.4 and use the same classes and functions.

For running you have to run it on different process using python 2.7 - using subprocess. Assume main27.py has the following line:

print 1

To run it using subprocess, you do as follow:

import subprocess
cmd = [r'c:\python27\python.exe', 'main27.py']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()

Than in stdout you have the following output:

1

For more complex data exchange you can use json or pickle using files.

like image 87
hagai Avatar answered Oct 22 '22 18:10

hagai