AllTradesJack
AllTradesJack

Reputation: 2882

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.

Upvotes: 5

Views: 4800

Answers (2)

Nagev
Nagev

Reputation: 13207

Indeed it is possible to make your code compatible with both versions. The obvious one and potentially more annoying is the print statement.

Let's say you have the following Python 2.x code:

name = "beautiful"
print "Hallo"
print "I mean, hallo ", name

The first line works fine in both versions. The second line, can just become:

print("Hallo")

Which is compatible with both versions too. Note that you can use single or double quotes.

The last line requires a little trick, otherwise, Python 2 will print the brackets as well. In order to make it work the same way in Python 2 as it does in Python 3, you have to import print_function from future, at the top of your module.

In summary, this is the dual compatible code:

#Works in Python 2.x or Python 3.x
from __future__ import print_function

print("Hallo")
print("I mean, hallo ", name)

See this cheat sheet for more details.

Upvotes: 0

hagai
hagai

Reputation: 148

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.

Upvotes: 3

Related Questions