[FIX] Refactored readConsole() fixes issue #10.

This commit is contained in:
Benedek Racz 2019-11-01 16:43:43 +01:00
parent d85f9b3d49
commit 9ce8421316
3 changed files with 80 additions and 77 deletions

View File

@ -18,14 +18,16 @@ child_script = here + '\\long_printer.py'
def main(): def main():
longPrinter = python_executable + ' ' + child_script longPrinter = python_executable + ' ' + child_script
prompt = '> ' prompt = 'puskas> '
# Start the child process # Start the child process
p = wexpect.spawn(longPrinter) p = wexpect.spawn(longPrinter)
# Wait for prompt # Wait for prompt
p.expect(prompt) p.expect(prompt)
try:
for i in range(10): for i in range(10):
print('.', end='')
p.sendline('0') p.sendline('0')
p.expect(prompt) p.expect(prompt)
if p.before.splitlines()[1] != puskas_wiki[0]: if p.before.splitlines()[1] != puskas_wiki[0]:
@ -34,9 +36,10 @@ def main():
p.sendline('all') p.sendline('all')
p.expect(prompt) p.expect(prompt)
for a,b in zip(p.before.splitlines()[1:-1], puskas_wiki): for a,b in zip(p.before.splitlines()[1:], puskas_wiki):
if a!=b: if a!=b:
print(p.before.splitlines()[1:-1]) print(a)
print(b)
raise Exception() raise Exception()
for j, paragraph in enumerate(puskas_wiki): for j, paragraph in enumerate(puskas_wiki):
@ -48,6 +51,13 @@ def main():
print(j) print(j)
print(paragraph) print(paragraph)
raise Exception() raise Exception()
except:
p.interact()
time.sleep(5)
else:
print('')
print('[PASS]')
main() main()

View File

@ -5,53 +5,53 @@ This is is a very basic stdio handler script. This is used by python.py example.
import time import time
puskas_wiki = ['''Ferenc Puskas was a Hungarian footballer and manager, widely regarded as one of \ puskas_wiki = ['''Ferenc Puskas was a Hungarian footballer and manager, widely regarded as one of \
the greatest players of all time. He is the son of former footballer Ferenc Puskás Senior. A \ the greatest players of all time. He is the son of former footballer Ferenc Puskas Senior. A \
prolific forward, he scored 84 goals in 85 international matches for Hungary, played 4 \ prolific forward, he scored 84 goals in 85 international matches for Hungary, played 4 \
international matches for Spain and scored 514 goals in 529 matches in the Hungarian and Spanish \ international matches for Spain and scored 514 goals in 529 matches in the Hungarian and Spanish \
leagues. He became an Olympic champion in 1952 and led his nation to the final of the 1954 World \ leagues. He became an Olympic champion in 1952 and led his nation to the final of the 1954 World \
Cup where he was named the tournament's best player. He won three European Cups (1959, 1960, 1966),\ Cup where he was named the tournament's best player. He won three European Cups (1959, 1960, 1966),\
10 national championships (5 Hungarian and 5 Spanish Primera División) and 8 top individual \ 10 national championships (5 Hungarian and 5 Spanish Primera Division) and 8 top individual \
scoring honors. In 1995, he was recognized as the top scorer of the 20th century by the IFFHS.''', scoring honors. In 1995, he was recognized as the top scorer of the 20th century by the IFFHS.''',
'''Puskás started his career in Hungary playing for Kispest and Budapest Honvéd. He was the top scorer\ '''Puskas started his career in Hungary playing for Kispest and Budapest Honved. He was the top scorer\
in the Hungarian League on four occasions, and in 1948, he was the top goal scorer in Europe. \ in the Hungarian League on four occasions, and in 1948, he was the top goal scorer in Europe. \
During the 1950s, he was both a prominent member and captain of the Hungarian national team, known\ During the 1950s, he was both a prominent member and captain of the Hungarian national team, known\
as the Mighty Magyars. In 1958, two years after the Hungarian Revolution, he emigrated to Spain \ as the Mighty Magyars. In 1958, two years after the Hungarian Revolution, he emigrated to Spain \
where he played for Real Madrid. While playing with Real Madrid, Puskás won four Pichichis and \ where he played for Real Madrid. While playing with Real Madrid, Puskas won four Pichichis and \
scored seven goals in two European Champions Cup finals.''', scored seven goals in two European Champions Cup finals.''',
'''After retiring as a player, he became a coach. The highlight of his coaching career came in 1971 \ '''After retiring as a player, he became a coach. The highlight of his coaching career came in 1971 \
when he guided Panathinaikos to the European Cup final, where they lost 20 to AFC Ajax. In 1993, \ when he guided Panathinaikos to the European Cup final, where they lost 2-0 to AFC Ajax. In 1993, \
he returned to Hungary and took temporary charge of the Hungarian national team. In 1998, he \ he returned to Hungary and took temporary charge of the Hungarian national team. In 1998, he \
became one of the first ever FIFA/SOS Charity ambassadors. In 2002, the Népstadion in Budapest \ became one of the first ever FIFA/SOS Charity ambassadors. In 2002, the Nepstadion in Budapest \
was renamed the Puskás Ferenc Stadion in his honor. He was also declared the best Hungarian \ was renamed the Puskas Ferenc Stadion in his honor. He was also declared the best Hungarian \
player of the last 50 years by the Hungarian Football Federation in the UEFA Jubilee Awards in \ player of the last 50 years by the Hungarian Football Federation in the UEFA Jubilee Awards in \
November 2003. In October 2009, FIFA announced the introduction of the FIFA Puskás Award, \ November 2003. In October 2009, FIFA announced the introduction of the FIFA Puskas Award, \
awarded to the player who has scored the "most beautiful goal" over the past year. He was also \ awarded to the player who has scored the "most beautiful goal" over the past year. He was also \
listed in Pelé's FIFA 100.''', listed in Pele's FIFA 100.''',
'''Ferenc Purczeld was born on 2 April 1927 to a German (Danube Swabian) family in Budapest and \ '''Ferenc Purczeld was born on 2 April 1927 to a German (Danube Swabian) family in Budapest and \
brought up in Kispest, then a suburb, today part of the city. His mother, Margit Biró \ brought up in Kispest, then a suburb, today part of the city. His mother, Margit Biro \
(19041976), was a seamstress. He began his career as a junior with Kispest AC,[10] where his \ (1904-1976), was a seamstress. He began his career as a junior with Kispest AC,[10] where his \
father, who had previously played for the club, was a coach. He had grandchildren, who were the \ father, who had previously played for the club, was a coach. He had grandchildren, who were the \
children of his brothers son[clarification needed]; the two sons of his brother are Zoltan and \ children of his brothers son[clarification needed]; the two sons of his brother are Zoltan and \
Istvan, the first one have 3 children; Ilonka, Camila and Andrés, and the second one have two.''', Istvan, the first one have 3 children; Ilonka, Camila and Andres, and the second one have two.''',
'''He changed his name to Puskás. He initially used the pseudonym "Miklós Kovács" to help \ '''He changed his name to Puskas. He initially used the pseudonym "Miklos Kovacs" to help \
circumvent the minimum age rules[12] before officially signing at the age of 12. Among his early \ circumvent the minimum age rules[12] before officially signing at the age of 12. Among his early \
teammates was his childhood friend and future international teammate József Bozsik. He made his \ teammates was his childhood friend and future international teammate Jozsef Bozsik. He made his \
first senior appearance for Kispest in November 1943 in a match against Nagyváradi AC.[13] It was \ first senior appearance for Kispest in November 1943 in a match against Nagyvaradi AC.[13] It was \
here where he got the nickname "Öcsi" or "Buddy".[14]''', here where he got the nickname "Ocsi" or "Buddy".[14]''',
'''Kispest was taken over by the Hungarian Ministry of Defence in 1949, becoming the Hungarian Army \ '''Kispest was taken over by the Hungarian Ministry of Defence in 1949, becoming the Hungarian Army \
team and changing its name to Budapest Honvéd. As a result, football players were given military \ team and changing its name to Budapest Honved. As a result, football players were given military \
ranks. Puskás eventually became a major (Hungarian: Őrnagy), which led to the nickname "The \ ranks. Puskas eventually became a major (Hungarian: Ornagy), which led to the nickname "The \
Galloping Major".[15] As the army club, Honvéd used conscription to acquire the best Hungarian \ Galloping Major".[15] As the army club, Honved used conscription to acquire the best Hungarian \
players, leading to the recruitment of Zoltán Czibor and ndor Kocsis.[16] During his career at \ players, leading to the recruitment of Zoltan Czibor and Sandor Kocsis.[16] During his career at \
Budapest Honvéd, Puskás helped the club win five Hungarian League titles. He also finished as top \ Budapest Honved, Puskas helped the club win five Hungarian League titles. He also finished as top \
goal scorer in the league in 194748, 194950, 1950 and 1953, scoring 50, 31, 25 and 27 goals, \ goal scorer in the league in 1947-48, 1949-50, 1950 and 1953, scoring 50, 31, 25 and 27 goals, \
respectively. In 1948, he was the top goal scorer in Europe.[17]''' ] respectively. In 1948, he was the top goal scorer in Europe.[17]''' ]
def main(): def main():
print('Welcome!') print('Welcome!')
while True: while True:
print('> ', end='') print('puskas> ', end='')
num = input() num = input()
if num == 'exit': if num == 'exit':

View File

@ -130,8 +130,8 @@ if 'dev' in __version__ :
logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG)
else: else:
logger.setLevel(logging.INFO) logger.setLevel(logging.INFO)
fh = logging.FileHandler('wexpect.log') fh = logging.FileHandler('wexpect.log', 'w', 'utf-8')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') formatter = logging.Formatter('%(asctime)s - %(filename)s::%(funcName)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter) fh.setFormatter(formatter)
logger.addHandler(fh) logger.addHandler(fh)
@ -2142,57 +2142,49 @@ class Wtty:
self.switchBack() self.switchBack()
return wrote return wrote
def getPoint(self, offset): def getCoord(self, offset):
"""Converts an offset to a point represented as a tuple.""" """Converts an offset to a point represented as a tuple."""
x = offset % self.__consSize[0] x = offset % self.__consSize[0]
y = offset // self.__consSize[0] y = offset // self.__consSize[0]
return (x, y) return win32console.PyCOORDType(x, y)
def getOffset(self, x, y): def getOffset(self, coord):
"""Converts a tuple-point to an offset.""" """Converts a tuple-point to an offset."""
return x + y * self.__consSize[0] return coord.X + coord.Y * self.__consSize[0]
def readConsole(self, startCo, endCo): def readConsole(self, startCo, endCo):
"""Reads the console area from startCo to endCo and returns it """Reads the console area from startCo to endCo and returns it
as a string.""" as a string."""
logger.info("STARTED")
buff = [] buff = []
self.lastRead = 0 self.lastRead = 0
startX = startCo.X
startY = startCo.Y
endX = endCo.X
endY = endCo.Y
while True: while True:
startOff = self.getOffset(startX, startY) startOff = self.getOffset(startCo)
logger.info("startOff %s" % startOff) endOff = self.getOffset(endCo)
endOff = self.getOffset(endX, endY)
logger.info("endOff %s" % endOff)
readlen = endOff - startOff readlen = endOff - startOff
logger.info("readlen %s" % readlen)
if readlen <= 0:
break
logger.info("startOff: %d endOff: %d readlen: %d", startOff, endOff, readlen)
if readlen > 4000: if readlen > 4000:
readlen = 4000 readlen = 4000
endPoint = self.getPoint(startOff + 4000) endPoint = self.getCoord(startOff + readlen)
logger.info("endPoint {}".format(endPoint))
else:
endPoint = self.getPoint(endOff)
logger.info("endPoint {}".format(endPoint)) logger.info("endPoint {}".format(endPoint))
s = self.__consout.ReadConsoleOutputCharacter(readlen, startCo) s = self.__consout.ReadConsoleOutputCharacter(readlen, startCo)
ln = len(s) logger.info("len {}".format(len(s)))
self.lastRead += ln self.lastRead += len(s)
self.totalRead += ln self.totalRead += len(s)
buff.append(s) buff.append(s)
logger.info(s.replace(screenbufferfillchar, '*'))
startX, startY = endPoint[0], endPoint[1] startCo = endPoint
logger.info("startX %s startY %s" % (startX, startY))
logger.info("endX %s endY %s" % (endX, endY))
if readlen <= 0 or (startX >= endX and startY >= endY):
break
return ''.join(buff) return ''.join(buff)
@ -2204,7 +2196,7 @@ class Wtty:
strlist = [] strlist = []
for i, c in enumerate(s): for i, c in enumerate(s):
if c == screenbufferfillchar: if c == screenbufferfillchar:
if (self.totalRead - self.lastRead + i + 1) % 80 == 0: if (self.totalRead - self.lastRead + i + 1) % self.__consSize[0] == 0:
strlist.append('\r\n') strlist.append('\r\n')
else: else:
strlist.append(c) strlist.append(c)
@ -2249,6 +2241,7 @@ class Wtty:
raw = raw[self.__consSize[0]:] raw = raw[self.__consSize[0]:]
raw = ''.join(rawlist) raw = ''.join(rawlist)
s = self.parseData(raw) s = self.parseData(raw)
logger.info(s)
for i, line in enumerate(reversed(rawlist)): for i, line in enumerate(reversed(rawlist)):
if line.endswith(screenbufferfillchar): if line.endswith(screenbufferfillchar):
# Record the Y offset where the most recent line break was detected # Record the Y offset where the most recent line break was detected
@ -2268,7 +2261,7 @@ class Wtty:
if s: if s:
lastReadData = self.lastReadData lastReadData = self.lastReadData
pos = self.getOffset(self.__currentReadCo.X, self.__currentReadCo.Y) pos = self.getOffset(self.__currentReadCo)
self.lastReadData = s self.lastReadData = s
if isSameY or not lastReadData.endswith('\r\n'): if isSameY or not lastReadData.endswith('\r\n'):
# Detect changed lines # Detect changed lines