0

What is the most better way to use Python 2.7 code if I have installed Python 3 already?

I've never used a Python 2.7 because I am new in Python and most video tutorials and web topics said it's better to use Python 3. But when I try to run code who is for 2.7 and not exist for Python 3, sometimes it's not working. What is the better option. To use Python 2 and 3 both on my PC. Or to try looking for Python 3 code only. Or to modify somehow Python 2.7 code? These are the errors:

IPython 6.1.0 -- An enhanced Interactive Python.

runfile('C:/Users/G/Desktop/image_recognition/new_test/GemData.py', wdir='C:/Users/G/Desktop/image_recognition/new_test')

Traceback (most recent call last):

  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-1-02441e959cce>", line 1, in <module>
    runfile('C:/Users/G/Desktop/image_recognition/new_test/GemData.py', wdir='C:/Users/G/Desktop/image_recognition/new_test')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile
    execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/G/Desktop/image_recognition/new_test/GemData.py", line 19
    print "error: image not read from file \n\n"        # print error message to std out
                                               ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(print "error: image not read from file \n\n"        # print error message to std out)?
cs95
  • 379,657
  • 97
  • 704
  • 746
George Tanev
  • 191
  • 1
  • 3
  • 7

1 Answers1

0

You cannot run your present code with Python 3 interpreter, so you have two options: translate this code to Python 3 or run it with Python 2.

Porting 2 to 3

There is some materials about porting from python 2 to 3:

Official docs

DigitalOcean tutorial

Also there is a tool for automated translation: 2to3. I haven't use it by myself so I cannot recommend it, but you can have a look and decide if it suites your needs.

Running with python 2

I think the best way here is to create a virtual environment with python 2. Something like this

$ virtualenv -p python2 venv
$ source venv/bin/activate
$ python <your-script>.py

For the further reading, there are a techniques to write python 2/3 compatible code. See this.

Alex Mozharov
  • 446
  • 6
  • 16