3

I found a repo with lots of Python2 files that includes a script to convert them to Python 3. However I get the following error when I run it:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 3-4: truncated \UXXXXXXXX escape

The only change I have made is to add the path to 2to3 rather then just having 2to3 since that is not in my path.

Any suggestions for how to get it working please?

import os

def makepython3():
    """This is a script to transform all the solutions into 
    Python 3 solutions."""
    files = os.listdir('exercises')

    exfolder = 'exercises'
    ex3folder = 'exercisespy3'

    if not os.path.exists(ex3folder):
        os.mkdir(ex3folder)

    for f in files:
        os.system('cp {} {}'.format(exfolder+os.sep+f, ex3folder+os.sep+f))
        if f.endswith('.py'):
            os.system('"C:\Users\HP\AppData\Local\Programs\Python\Python37-32\Tools\scripts\2to3.py" -w -n --no-diffs {}'.format(ex3folder+os.sep+f))

    print('All done!')

if __name__ == '__main__':
    makepython3()
Robin Andrews
  • 3,514
  • 11
  • 43
  • 111

2 Answers2

4

The problem is here:

os.system('"C:\Users\HP\....
              ^-- interpreted as a \U unicode escape

Try using a raw string:

os.system(r'"C:\Users\HP\....

\U escape sequence was introduced in python 3, which explains that the script worked in python 2. But raw strings should always be used when dealing with literal windows paths.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
1

Just use os.path.sep together with os.path.join to build the path instead of a hardcoded string.

from os.path import join, sep

windows_exe_path = join(
    sep, 
    "C:" + sep, 
    "Users", sep, 
    "HP", sep, 
    "AppData", sep, 
    "Local", sep,
    "Programs", sep, 
    "Python", sep 
    "Python37-32", sep, 
    "Tools", sep,
    "scripts", sep, 
    "2to3.py",
)

Otherwise a / will also work.

windows_exe_path = "C:/Users/HP/AppData/Local/Programs/Python/Python37-32/Tools/scripts/2to3.py"
Klemen Tusar
  • 9,261
  • 4
  • 31
  • 28