やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

PyOpenGL-DemoのコードをPython3に変換して実行できるか試してみた

Python2のコードを3で動かしたい。

2to3

python3にはPython2コードをPython3コードに変換するツール2to3が付属しているらしい。

PyOpenGL-Demo

Python3.6.1でインストールしたが、ソースコードがPython2用っぽい。

venvでgame仮想環境を作成し、インストール。以下のパスを見てみた。

/.../game/lib/python3.6/site-packages/PyOpenGL-Demo/NeHe配下にlesson1.pyのようなコードがある。

2→3

lesson1.pyファイルをコピーする(上書きされたら困るから)

$ 2to3 lesson1.py -w
$ 2to3 lesson1.py -w
RefactoringTool: Skipping optional fixer: buffer
RefactoringTool: Skipping optional fixer: idioms
RefactoringTool: Skipping optional fixer: set_literal
RefactoringTool: Skipping optional fixer: ws_comma
RefactoringTool: No changes to lesson1.py
RefactoringTool: Files that need to be modified:
RefactoringTool: lesson1.py

lesson1.pyが上書きされている。そして、lesson1.py.bakが作成されている。元々の内容がバックアップされたファイル。

実行

$ python lesson1.py 
Traceback (most recent call last):
  File "lesson1.py", line 8, in <module>
    __version__ = string.split('$Revision: 1.1.1.1 $')[1]
AttributeError: module 'string' has no attribute 'split'

以下、調べてみるとstring.split()はPython2にしか存在しなかった。こういうところは修正できないらしい。かなり大量にありそう……。

修正

結局、以下の部分を手で直した。

lesson1.py抜粋

import string
#__version__ = string.split('$Revision: 1.1.1.1 $')[1]
__version__ = '$Revision: 1.1.1.1 $'.split()[1]
#__date__ = string.join(string.split('$Date: 2007/02/15 19:25:19 $')[1:3], ' ')
__date__ = ' '.join('$Date: 2007/02/15 19:25:19 $'.split()[1:3])
__author__ = 'Tarn Weisner Burton <twburton@users.sourceforge.net>'

実行2

$ python lesson1.py 
Hit ESC key to quit.

ESCキーを押下しても終了しなかった。真っ黒な画面が表示された。

f:id:ytyaru:20170716132913p:plain

help

$ 2to3 -h
$ 2to3 -h
Usage: 2to3 [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 2to3 concurrently
  -x NOFIX, --nofix=NOFIX
                        Prevent a transformation from being run
  -l, --list-fixes      List available transformations
  -p, --print-function  Modify the grammar so that print() is a function
  -v, --verbose         More verbose logging
  --no-diffs            Don't show diffs of the refactoring
  -w, --write           Write back modified files
  -n, --nobackups       Don't write backups for modified files
  -o OUTPUT_DIR, --output-dir=OUTPUT_DIR
                        Put output files in this directory instead of
                        overwriting the input files.  Requires -n.
  -W, --write-unchanged-files
                        Also write files even if no changes were required
                        (useful with --output-dir); implies -w.
  --add-suffix=ADD_SUFFIX
                        Append this string to all output filenames. Requires
                        -n if non-empty.  ex: --add-suffix='3' will generate
                        .py3 files.

所感

結局、むずかしいところは手動で直すしかないというオチ。