Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2to3 Script Not Working - Unicode Error

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()
like image 983
Robin Andrews Avatar asked Mar 11 '26 09:03

Robin Andrews


1 Answers

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.

like image 197
Tim Pietzcker Avatar answered Mar 12 '26 22:03

Tim Pietzcker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!