Convert python 3.x code to python 2.x

background

I've been using python3 for a long time, but it's a new development, and I wrote it in 3 because it was developed in python2, but in the end, I needed to unify it, so I investigated it. ..

Install 3to2

  1. Download the zip from https://pypi.python.org/pypi/3to2
  2. Open the zip and cd 3to2-x.x.x
  3. python setup.py install

Try 3to2

You can check the Option by typing the following command in the terminal

3to2 --help
Usage: 3to2 [options] file|dir ...

Options:
  -h, --help            show this help message and exit
  -d, --doctests_only   Fix up doctests only
  -f FIX, --fix=FIX     Each FIX specifies a transformation; default: all
  -j PROCESSES, --processes=PROCESSES
                        Run 3to2 concurrently
  -x NOFIX, --nofix=NOFIX
                        Prevent a fixer from being run.
  -l, --list-fixes      List available transformations (fixes/fix_*.py)
  -v, --verbose         More verbose logging
  -w, --write           Write back modified files
  -n, --nobackups       Don't write backups for modified files.
  --no-diffs            Don't show diffs of the refactoring

For the time being, I decided to write directly using -w (cutting Branch). Otherwise, only the part that changes from 3 to 2 will be displayed.

3to2 -w aaaa.py



 Run and succeed!

# Other

 However, this alone may still cause an error.

## 1. Character code related

SyntaxError: Non-ASCII character '\xe6' in file aaaa.py on line 3, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

 In this case, write `# coding = <encoding name>` on the first line according to the support of URL.
 In the Encoding name part, write ʻutf-8`

## 2. All Strings are preceded by ʻu`, which causes an error

TypeError: "delimiter" must be string, not unicode


 For example, if you convert a pandas dataframe:


 Before conversion (python3)
`df.to_csv('aaa.tsv', sep='\t')`

 After conversion (python2)
`df.to_csv(u'aaa.tsv', sep=u'\t')`

 And it says `TypeError:" delimiter "must be string, not unicode`, so
 Remove ʻu` before sep ='\ t'

## 3. Similarly, a mysterious error appears in the `to_csv` part.

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

 In Python2, it seems that csv does not support unicode, so

 Add ʻencoding ='utf-8'`,

df.to_csv('aaa.tsv', sep='\t', encoding='utf-8')


 If so, it will be solved

## 4. cld2 can no longer be installed

 After making python 2.7.6

 `pip intall cld2` fails with the error` No package'libffi' found`

 For mac
 Install with `brew install libffi`. → Success

 I'm not sure because I haven't done it for Ubuntu, but is it okay to use ʻapt-get install libffi` or `libffi-dev`? .. ??

## 5. Unicode-related mystery error 2

TypeError: initializer for ctype 'char *' must be a str or list or tuple, not unicode

 The one passed to cld2 above was unicode, so change it as follows

 Change before

reliable, _, lang = cld2.detect(name)


 After change

reliable, _, lang = cld2.detect(name.encode('utf-8'))



# Conclusion from the error

 Python2 has a lot of errors in Unicode, so be careful!


# bonus

## version control
 For those who use both Python 2 and 3, it may be convenient to use `pyenv` and separate it by Local.

### Check which version you have

pyenv versions


### Install the required version

pyenv install 2.7.10


### Set locally

pyenv local 2.7.10


 This will create a file called .python-verion with the version inside. If you delete this file, you can use the global python version.


## Note the 3to2 execution Python version
 I installed python3, so it is said that there is no `3to2` command in the place where I changed to local version python2 with pyenv. So, when changing multiple files, you need to think about whether to execute `3to2` in python3 and then switch to python2 or install both python3 and 2.


Recommended Posts

Convert python 3.x code to python 2.x
Rewrite Python2 code to Python3 (2to3)
Python code to convert region mesh code to latitude / longitude
Python script to convert latitude / longitude to mesh code
Convert cubic mesh code to WKT in Python
[python] Convert date to string
[Python] Convert list to Pandas [Pandas]
2.x, 3.x character code of python
Convert Scratch project to Python
[Python] Convert Shift_JIS to UTF-8
Convert markdown to PDF in Python
Workflow to convert formula (image) to python
Convert list to DataFrame with python
Python> list> Convert double list to single list
[Python] Convert natural numbers to ordinal numbers
Convert decimal numbers to n-ary numbers [python]
Python> tuple> Convert double tuple to single tuple
[Python] How to convert db file to csv
Updated to Python 2.7.9
Convert memo at once with Python 2to3
Convert to HSV
Convert Python> two value sequence to dictionary
[Python] How to convert a 2D list to a 1D list
[Python] Convert csv file delimiters to tab delimiters
Convert psd file to png in Python
Convert Excel data to JSON with python
Convert Hiragana to Romaji with Python (Beta)
python character code
How to erase Python 2.x on Mac.
Convert FX 1-minute data to 5-minute data with Python
python> Convert tuple to list> aList = list (pi_tuple)
[Python] Algorithm-aware code
Convert HEIC files to PNG files with Python
Convert Chinese numerals to Arabic numerals with Python
Convert from Markdown to HTML in Python
[Blender x Python] How to use modifiers
Convert absolute URLs to relative URLs in Python
"Backport" to python 2
Sample to convert image to Wavelet with Python
I wrote a code to convert quaternions to z-y-x Euler angles in Python
Convert FBX files to ASCII <-> BINARY in Python
Convert PDF to image (JPEG / PNG) with Python
Convert "number" of excel date to python datetime
Convert PDFs to images in bulk with Python
[Python] Convert from DICOM to PNG or CSV
Convert svg file to png / ico with Python
Personal notes to doc Python code in Sphinx
[Automation] Convert Python code into an exe file
How to convert SVG to PDF and PNG [Python]
Excel X Python The fastest way to work
[Algorithm x Python] How to use the list
[Blender x Python] How to make an animation
Convert STL to Voxel mesh using Python VTK
List of Python code to move and remember
[Blender x Python] How to make vertex animation
Convert the character code of the file with Python3
Convert exponential notation float to str in Python
I want to make C ++ code from Python code!
[Blender x Python] Think of code with symbols
Convert strings to character-by-character list format with python
How to install Python