2012-06-28

Fixing Python 2.6+ to run Python 3 code:

# -*- coding: utf-8 -*-
from __future__ import print_function
__doc__ = """XLS2DB by Cees Timmerman"""
changelog = """
2012-06-28 v1.0
"""
import glob, locale, os, re, sys, time
#from pyXLSX.xlsx import workbook  # no MergedCells support and fails at Unicode.
from win32com.client import Dispatch  # PyWin32 or ActivePython required. Excel, too.
#from win32com.client.gencache import EnsureDispatch as Dispatch  # Also makes constants available.
#import Image  # PIL to resize images.
import pymysql   # Note: Python 3 doesn't support old db protocol.

print(__doc__)
print(changelog.split("\n")[-2])
print()

if sys.version[:2] == '2.':
 #print("Python 2 sucks at Unicode; use Python 3 to run this.")
 #sys.exit(2)

 # Fix Python 2. We should be running in Python 3, though.
 original_print = print
 def print(*args, **kwargs):
  #original_print("args: " + str(args))
  #original_print("kwargs: " + str(kwargs))
  new_args = []
  for arg in args:
   try:
    new_args.append(arg.encode('ascii', errors='xmlcharrefreplace'))
   except:
    new_args.append(arg)
  original_print(*new_args, **kwargs)
 
 try:
  input = raw_input
  str = unicode
 except: pass

1 comment:

  1. Instead of original_print, you can use __builtins__.print, but dot lookups are slow in Python.

    ReplyDelete