Skip to content
Snippets Groups Projects
Commit 7572308a authored by tuhe's avatar tuhe
Browse files

no more p and w expect

parent 2422dc07
Branches
No related tags found
No related merge requests found
Pipeline #19325 passed
# wexpect # wexpect
git+https://github.com/raczben/wexpect.git@dev # Changing to dev bc of venv incompatibility stuff. (th juli 2023: problem with 4.0.0). # git+https://github.com/raczben/wexpect.git@dev # Changing to dev bc of venv incompatibility stuff. (th juli 2023: problem with 4.0.0).
pexpect # pexpect
pybtex pybtex
numpy
\ No newline at end of file
...@@ -35,5 +35,5 @@ setuptools.setup( ...@@ -35,5 +35,5 @@ setuptools.setup(
package_dir={"": "src"}, package_dir={"": "src"},
packages=setuptools.find_packages(where="src"), packages=setuptools.find_packages(where="src"),
python_requires=">=3.8", python_requires=">=3.8",
install_requires=['pexpect', 'wexpect', 'pybtex', 'numpy'], install_requires=['pybtex', 'numpy'],
) )
Metadata-Version: 2.1 Metadata-Version: 2.1
Name: codesnipper Name: codesnipper
Version: 0.1.18.8 Version: 0.1.18.9
Summary: A lightweight framework for censoring student solutions files and extracting code + output Summary: A lightweight framework for censoring student solutions files and extracting code + output
Home-page: https://lab.compute.dtu.dk/tuhe/snipper Home-page: https://lab.compute.dtu.dk/tuhe/snipper
Author: Tue Herlau Author: Tue Herlau
......
pexpect
wexpect
pybtex pybtex
numpy numpy
...@@ -8,118 +8,118 @@ import sys ...@@ -8,118 +8,118 @@ import sys
from snipper.block_parsing import block_split, block_join from snipper.block_parsing import block_split, block_join
import os import os
if os.name == 'nt': # if os.name == 'nt':
import wexpect as we # import wexpect as we
else: # else:
import pexpect as we # import pexpect as we
def rsession(analyzer, lines, extra): # def rsession(analyzer, lines, extra):
l2 = [] # l2 = []
dbug = False # dbug = False
# analyzer = we.spawn("python", encoding="utf-8", timeout=20) # # analyzer = we.spawn("python", encoding="utf-8", timeout=20)
# analyzer.expect([">>>"]) # # analyzer.expect([">>>"])
if "b = make_square(5)" in "\n".join(lines): # in "\n".join(lines): # if "b = make_square(5)" in "\n".join(lines): # in "\n".join(lines):
print("\n".join(lines)) # print("\n".join(lines))
print("-"*50) # print("-"*50)
for k in extra['session_results']: # for k in extra['session_results']:
print(k['input']) # print(k['input'])
print(k['output']) # print(k['output'])
#
import time # import time
an = we.spawn(sys.executable, encoding="utf-8", timeout=20) # an = we.spawn(sys.executable, encoding="utf-8", timeout=20)
try: # try:
an.setwinsize(400, 400) # set window size to avoid truncated output or input. # an.setwinsize(400, 400) # set window size to avoid truncated output or input.
except AttributeError as e: # except AttributeError as e:
print("> Mulble pexpect('pyhon',...) does not support setwinsize on this system (windows?). Ignoring") # print("> Mulble pexpect('pyhon',...) does not support setwinsize on this system (windows?). Ignoring")
#
an.expect([">>>"]) # an.expect([">>>"])
l3 = """ # l3 = """
2 + 4 # Add two integers # 2 + 4 # Add two integers
50 - 5 * 6 # 50 - 5 * 6
(2 + 2) * (3 - 1) # You can group operations using parenthesis # (2 + 2) * (3 - 1) # You can group operations using parenthesis
width = 20 # Assign the variable 'width' to a value of 20 # width = 20 # Assign the variable 'width' to a value of 20
height = 5*9 # And also height is assigned the value of 5 * 9 = 45 # height = 5*9 # And also height is assigned the value of 5 * 9 = 45
area = 2*3 # Compute the area of a rectangle and assign it to area now the text will be longer is that an issue # area = 2*3 # Compute the area of a rectangle and assign it to area now the text will be longer is that an issue
area # This line shows us the value of 'area' #!i=b # area # This line shows us the value of 'area' #!i=b
""" # """
lines2 = l3.strip().splitlines() # lines2 = l3.strip().splitlines()
from collections import defaultdict # from collections import defaultdict
dd = defaultdict(list) # dd = defaultdict(list)
#
for l in lines2: # for l in lines2:
dd['code'].append(l) # dd['code'].append(l)
an.sendline(l.rstrip()) # an.sendline(l.rstrip())
an.expect_exact([">>>", "..."]) # an.expect_exact([">>>", "..."])
dd["output"].append(an.before.strip()) # dd["output"].append(an.before.strip())
# print(">>>", an.before.strip()) # # print(">>>", an.before.strip())
if len(an.after.strip()) > 4: # if len(an.after.strip()) > 4:
print(">>>>>>>>>>>>> That was a long after?") # print(">>>>>>>>>>>>> That was a long after?")
# analyzer.be # # analyzer.be
#
print('*' * 50) # print('*' * 50)
# analyzer = an # # analyzer = an
dbug = True # dbug = True
import tabulate # import tabulate
print(tabulate.tabulate(dd, headers='keys')) # print(tabulate.tabulate(dd, headers='keys'))
#
lines = "\n".join(lines).replace("\r", "").splitlines() # lines = "\n".join(lines).replace("\r", "").splitlines()
#
for i, l in enumerate(lines): # for i, l in enumerate(lines):
l2.append(l) # l2.append(l)
if l.startswith(" ") and i < len(lines)-1 and not lines[i+1].startswith(" "): # if l.startswith(" ") and i < len(lines)-1 and not lines[i+1].startswith(" "):
if not lines[i+1].strip().startswith("else:") and not lines[i+1].strip().startswith("elif") : # if not lines[i+1].strip().startswith("else:") and not lines[i+1].strip().startswith("elif") :
l2.append("") # Empty line instead? # l2.append("") # Empty line instead?
#
lines = l2 # lines = l2
alines = [] # alines = []
in_dot_mode = False # in_dot_mode = False
if len(lines[-1]) > 0 and (lines[-1].startswith(" ") or lines[-1].startswith("\t")): # if len(lines[-1]) > 0 and (lines[-1].startswith(" ") or lines[-1].startswith("\t")):
lines += [""] # lines += [""]
#
#
for i, word in enumerate(lines): # for i, word in enumerate(lines):
if dbug:
print("> Sending...", word)
analyzer.sendline(word.rstrip())
import time
before = ""
while True:
time.sleep(0.05)
analyzer.expect_exact([">>>", "..."])
# if dbug and "total_cost" in word:
# aaa = 23234
before += analyzer.before
# if dbug: # if dbug:
# print("> analyzer.before...", analyzer.before.strip(), "...AFTER...", analyzer.after.strip()) # print("> Sending...", word)
# AFTER = # analyzer.sendline(word.rstrip())
if analyzer.before.endswith("\n"): # import time
# print("> BREAKING LOOP") # before = ""
break # while True:
else: # time.sleep(0.05)
before += analyzer.after # analyzer.expect_exact([">>>", "..."])
break # # if dbug and "total_cost" in word:
# # aaa = 23234
# print("Before is", before) # before += analyzer.before
abefore = analyzer.before.rstrip() # # if dbug:
# Sanitize by removing garbage binary stuff the terminal puts in # # print("> analyzer.before...", analyzer.before.strip(), "...AFTER...", analyzer.after.strip())
abefore = "\n".join([l for l in abefore.splitlines() if not l.startswith('\x1b')] ) # # AFTER =
# if analyzer.before.endswith("\n"):
dotmode = analyzer.after == "..." # # print("> BREAKING LOOP")
if 'dir(s)' in word: # break
pass # else:
if 'help(s.find)' in word: # before += analyzer.after
pass # break
if dotmode: #
alines.append(">>>" +abefore.rstrip() if not in_dot_mode else "..." + abefore.rstrip()) # # print("Before is", before)
in_dot_mode = True # abefore = analyzer.before.rstrip()
else: # # Sanitize by removing garbage binary stuff the terminal puts in
alines.append( ("..." if in_dot_mode else ">>>") + abefore.rstrip()) # abefore = "\n".join([l for l in abefore.splitlines() if not l.startswith('\x1b')] )
in_dot_mode = False #
if dbug: # dotmode = analyzer.after == "..."
print("-"*50) # if 'dir(s)' in word:
print("\n".join(alines)) # pass
extra['session_results'].append({'input': '\n'.join(lines), 'output': '\n'.join(alines)}) # if 'help(s.find)' in word:
return alines # pass
# if dotmode:
# alines.append(">>>" +abefore.rstrip() if not in_dot_mode else "..." + abefore.rstrip())
# in_dot_mode = True
# else:
# alines.append( ("..." if in_dot_mode else ">>>") + abefore.rstrip())
# in_dot_mode = False
# if dbug:
# print("-"*50)
# print("\n".join(alines))
# extra['session_results'].append({'input': '\n'.join(lines), 'output': '\n'.join(alines)})
# return alines
def run_i(lines, file, output): def run_i(lines, file, output):
...@@ -222,27 +222,28 @@ class FileConsole(code.InteractiveConsole): ...@@ -222,27 +222,28 @@ class FileConsole(code.InteractiveConsole):
def write(self, str): def write(self, str):
print(str) print(str)
pass pass
# self.output[self.k].append(str)
def showtraceback(self):
"""Display the exception that just occurred.
We remove the first stack item because it is our own code.
The output is written by self.write(), below. # self.output[self.k].append(str)
# def showtraceback(self):
""" # """Display the exception that just occurred.
sys.last_type, sys.last_value, last_tb = ei = sys.exc_info() #
sys.last_traceback = last_tb # We remove the first stack item because it is our own code.
try: #
lines = traceback.format_exception(ei[0], ei[1], last_tb.tb_next) # The output is written by self.write(), below.
if sys.excepthook is sys.__excepthook__: #
self.write(''.join(lines)) # """
else: # sys.last_type, sys.last_value, last_tb = ei = sys.exc_info()
# If someone has set sys.excepthook, we let that take precedence # sys.last_traceback = last_tb
# over self.write # try:
sys.excepthook(ei[0], ei[1], last_tb) # lines = traceback.format_exception(ei[0], ei[1], last_tb.tb_next)
finally: # if sys.excepthook is sys.__excepthook__:
last_tb = ei = None # self.write(''.join(lines))
# else:
# # If someone has set sys.excepthook, we let that take precedence
# # over self.write
# sys.excepthook(ei[0], ei[1], last_tb)
# finally:
# last_tb = ei = None
def run_blocks(self, blocks): def run_blocks(self, blocks):
from collections import defaultdict from collections import defaultdict
...@@ -286,8 +287,8 @@ def new_run_i(lines, file, output): ...@@ -286,8 +287,8 @@ def new_run_i(lines, file, output):
art = b['name'] art = b['name']
outf = output + ("_" + art if art is not None and len(art) > 0 else "") + ".shell" outf = output + ("_" + art if art is not None and len(art) > 0 else "") + ".shell"
# print(outf) # print(outf)
id = os.path.basename(outf) # id = os.path.basename(outf)
cutouts[id] = {'first': b['first'], 'block': b['block'], 'last': []} cutouts[os.path.basename(outf)] = {'first': b['first'], 'block': b['block'], 'last': []}
lines = b['last'] lines = b['last']
# #
# continue # continue
...@@ -321,7 +322,6 @@ def new_run_i(lines, file, output): ...@@ -321,7 +322,6 @@ def new_run_i(lines, file, output):
blks = {} blks = {}
for id, block in cutouts.items(): for id, block in cutouts.items():
# b = block['block']
dx = min( [k for k, l in enumerate(block['block']) if len(l.strip()) != 0] ) dx = min( [k for k, l in enumerate(block['block']) if len(l.strip()) != 0] )
blks[id +"_pre"] = "\n".join( block['first'] + block['block'][:dx] ) blks[id +"_pre"] = "\n".join( block['first'] + block['block'][:dx] )
blks[id] = "\n".join(block['block'][dx:]) blks[id] = "\n".join(block['block'][dx:])
...@@ -330,26 +330,8 @@ def new_run_i(lines, file, output): ...@@ -330,26 +330,8 @@ def new_run_i(lines, file, output):
out = run_code_blocks(blks) out = run_code_blocks(blks)
for id in cutouts: for id in cutouts:
print("-"*5, id, "-"*5) # print("-"*5, id, "-"*5)
print("".join(out[id])) # print("".join(out[id]))
with open(f"{os.path.dirname(output)}/{id}", 'w') as f: with open(f"{os.path.dirname(output)}/{id}", 'w') as f:
f.write("".join(out[id])) f.write("".join(out[id]))
return l0 return l0
#
#
# # import sys
# sys.ps1 = ">>>"
# fc = FileConsole(lines='print("hello world")\nprint("world")\na=23')
# # fc.interact()
# fc = FileConsole()
# out = fc.run_blocks({'a': 'print("hello world")\nprint("world")\na=23\nprint("buy!")',
# 'b': """for i in range(4):
# print("i is", i)
#
# """, 'c': 'th = 31'})
# print(out)
#
#
# return lines
# a = 234
# pass
\ No newline at end of file
__version__ = "0.1.18.8" __version__ = "0.1.18.9"
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment