Skip to content

Commit

Permalink
improved: long string handle - step 1
Browse files Browse the repository at this point in the history
  • Loading branch information
panyanyany committed Jun 16, 2016
1 parent a77d51d commit 62b0ef1
Show file tree
Hide file tree
Showing 8 changed files with 153 additions and 5 deletions.
5 changes: 5 additions & 0 deletions beeprint/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,8 @@
_DL_MODULE_ = 1
_DL_FUNC_ = 2
_DL_STATEMENT = 3

# long string
_LS_WRAP_BY_NONE = 0
_LS_WRAP_BY_TERMINAL = 1
_LS_WRAP_BY_80_COLUMN = 2
2 changes: 1 addition & 1 deletion beeprint/printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ def typeval(v):
ret = ret.replace(u'\n', u'\\n')
ret = ret.replace(u'\r', u'\\r')
else:
ret = u'<YOU HAVE UNSET S.united_str_coding_representation>'
ret = u'<YOU HAVE SET S.united_str_coding_representation TO True>'

except Exception as e:
if S.priority_strategy == C._PS_CORRECTNESS_FIRST:
Expand Down
7 changes: 6 additions & 1 deletion beeprint/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
# use buffer_handler.flush() every print
write_to_buffer_when_execute = False

# >> class controll
# >> class control
# 过滤以 x 开头的属性
prop_leading_filters = ["__", "func_"]
# 根据类型过滤对象的属性
Expand All @@ -39,12 +39,17 @@
# debug = False
debug_level = 0

# >> string control
# united_str_coding_representation
# In spite of python version
# unicode string will be displayed as u''
# non-unicode string will be displayed as b''
united_str_coding_representation = True
str_display_not_prefix_u = True
str_display_not_prefix_b = True
str_display_escape_special_char = True

element_display_last_with_comma = True

# >> long string control
long_str_wrap_method = C._LS_WRAP_BY_TERMINAL
96 changes: 96 additions & 0 deletions beeprint/terminal_size.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# -*- coding:utf-8 -*-
"""
copied from https://gist.github.com/jtriley/1108174
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
import os
import shlex
import struct
import platform
import subprocess


def get_terminal_size():
""" getTerminalSize()
- get width and height of console
- works on linux,os x,windows,cygwin(windows)
originally retrieved from:
http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python
"""
current_os = platform.system()
tuple_xy = None
if current_os == 'Windows':
tuple_xy = _get_terminal_size_windows()
if tuple_xy is None:
tuple_xy = _get_terminal_size_tput()
# needed for window's python in cygwin's xterm!
if current_os in ['Linux', 'Darwin'] or current_os.startswith('CYGWIN'):
tuple_xy = _get_terminal_size_linux()
if tuple_xy is None:
print("default")
tuple_xy = (80, 25) # default value
return tuple_xy


def _get_terminal_size_windows():
try:
from ctypes import windll, create_string_buffer
# stdin handle is -10
# stdout handle is -11
# stderr handle is -12
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if res:
(bufx, bufy, curx, cury, wattr,
left, top, right, bottom,
maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
sizex = right - left + 1
sizey = bottom - top + 1
return sizex, sizey
except:
pass


def _get_terminal_size_tput():
# get terminal width
# src: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window
try:
cols = int(subprocess.check_call(shlex.split('tput cols')))
rows = int(subprocess.check_call(shlex.split('tput lines')))
return (cols, rows)
except:
pass


def _get_terminal_size_linux():
def ioctl_GWINSZ(fd):
try:
import fcntl
import termios
cr = struct.unpack('hh',
fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
return cr
except:
pass
cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
if not cr:
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
cr = ioctl_GWINSZ(fd)
os.close(fd)
except:
pass
if not cr:
try:
cr = (os.environ['LINES'], os.environ['COLUMNS'])
except:
return None
return int(cr[1]), int(cr[0])

if __name__ == "__main__":
sizex, sizey = get_terminal_size()
print('width =', sizex, 'height =', sizey)
7 changes: 7 additions & 0 deletions beeprint/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import sys
import types

from . import constants as C


if sys.version_info < (3, 0):
pyv = 2
Expand All @@ -32,3 +34,8 @@ def is_pan_function(name, val):
function and unbound method and bound method in python 2
"""
return inspect.isfunction(val) or inspect.ismethod(val)

def long_string_wrapper(ls, how):
if how == C._LS_WRAP_BY_80_COLUMN:
pass
pass
26 changes: 26 additions & 0 deletions tests/definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,29 @@ def mth():pass
u'key2': {},
},
]

long_text_en = """
The sky and the earth were at first one blurred1 entity2 like an egg. Pangu was born into it.
The separation of the sky and the earth took eighteen thousand years-the yang which was light and pure rose to become the sky, and the yin which was heavy and murky3(朦胧的) sank to form the earth. Between them was Pangu, who went through nine changes every day, his wisdom greater than that of the sky and his ability greater than that of the earth. Every day the sky rose ten feet higher, the earth became ten feet thicker, and Pangu grew ten feet taller.
Another eighteen thousand years passed, and there was an extremely high sky, an extremely thick earth, and an extremely tall Pangu. After Pangu died, his head turned into the Five Sacred Mountains (Mount4 Tai, Mount Heng, Mount Hua, Mount Heng, Mount Song), his eyes turned into the moon and the sun, his blood changed into water in river and sea, his hair into grass.
In all, the universe and Pangu combine in one.
"""

long_text_cn = """
据民间神话传说古时盘古生在黑暗团中,他不能忍受黑暗,用神斧劈向四方,逐渐使天空高远,大地辽阔。他为不使天地会重新合并,继续施展法术。每当盘古的身体长高一尺,天空就随之增高一尺,经过1.8万多年的努力,盘古变成一位顶天立地的巨人,而天空也升得高不可及,大地也变得厚实无比。盘古生前完成开天辟地的伟大业绩,死后永远留给后人无穷无尽的宝藏,成为中华民族崇拜的英雄。
"""

long_text_in_list = [
[
long_text_en,
long_text_cn,
],
]

long_text_in_dict = [
{"english version": long_text_en},
{"simplify chinese versino": long_text_cn},
]
6 changes: 5 additions & 1 deletion tests/t.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,11 @@
try:
from .definition import values
from .definition import inst_of_normal_class_old_style, inst_of_normal_class_new_style, NormalClassOldStyle, NormalClassNewStyle, EmptyFunc
from . import definition as df
except:
from definition import values
from definition import inst_of_normal_class_old_style, inst_of_normal_class_new_style, NormalClassOldStyle, NormalClassNewStyle, EmptyFunc
import definition as df


# >> utilities
Expand Down Expand Up @@ -82,6 +84,7 @@ def builtin_test():
# print('%40s: %s' % (v, inspect.ismethod(v))) py3 FFTT
print('%40s: %s, %s' % (v, v.__qualname__, inspect.getargspec(v).args))


args = {
"class_test": class_test,
"inst_test": inst_test,
Expand All @@ -94,7 +97,8 @@ def main():
# S.str_display_not_prefix_u = False
# S.str_display_not_prefix_b = False

pp(values)
pp(df.long_text_in_dict)
pp(df.long_text_in_list)
# pp([inst_of_normal_class_old_style.mth, inst_of_normal_class_new_style.mth])
return

Expand Down
9 changes: 7 additions & 2 deletions tests/test_default_beeprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@
from beeprint import settings as S

try:
from .definition import values
from .definition import values, long_text_en
except:
from definition import values
from definition import values, long_text_en


class TestSimpleTypes(unittest.TestCase):
Expand Down Expand Up @@ -82,6 +82,11 @@ def test_complicate_data(self):
self.assertEqual(res == ans or res == ans2, True)
# self.assertEqual(res, ans)

def test_long_text(self):
pass
# res = beeprint(long_text_en, output=False)
# self.assertEqual(res, ans)


if __name__ == '__main__':
unittest.main()

0 comments on commit 62b0ef1

Please sign in to comment.