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

no more p and w expect

parent 2422dc07
No related branches found
No related tags found
No related merge requests found
Pipeline #19325 passed
# 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).
pexpect
# 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
pybtex
numpy
\ No newline at end of file
......@@ -35,5 +35,5 @@ setuptools.setup(
package_dir={"": "src"},
packages=setuptools.find_packages(where="src"),
python_requires=">=3.8",
install_requires=['pexpect', 'wexpect', 'pybtex', 'numpy'],
install_requires=['pybtex', 'numpy'],
)
Metadata-Version: 2.1
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
Home-page: https://lab.compute.dtu.dk/tuhe/snipper
Author: Tue Herlau
......
pexpect
wexpect
pybtex
numpy
......@@ -8,118 +8,118 @@ import sys
from snipper.block_parsing import block_split, block_join
import os
if os.name == 'nt':
import wexpect as we
else:
import pexpect as we
def rsession(analyzer, lines, extra):
l2 = []
dbug = False
# analyzer = we.spawn("python", encoding="utf-8", timeout=20)
# analyzer.expect([">>>"])
if "b = make_square(5)" in "\n".join(lines): # in "\n".join(lines):
print("\n".join(lines))
print("-"*50)
for k in extra['session_results']:
print(k['input'])
print(k['output'])
import time
an = we.spawn(sys.executable, encoding="utf-8", timeout=20)
try:
an.setwinsize(400, 400) # set window size to avoid truncated output or input.
except AttributeError as e:
print("> Mulble pexpect('pyhon',...) does not support setwinsize on this system (windows?). Ignoring")
an.expect([">>>"])
l3 = """
2 + 4 # Add two integers
50 - 5 * 6
(2 + 2) * (3 - 1) # You can group operations using parenthesis
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
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
"""
lines2 = l3.strip().splitlines()
from collections import defaultdict
dd = defaultdict(list)
for l in lines2:
dd['code'].append(l)
an.sendline(l.rstrip())
an.expect_exact([">>>", "..."])
dd["output"].append(an.before.strip())
# print(">>>", an.before.strip())
if len(an.after.strip()) > 4:
print(">>>>>>>>>>>>> That was a long after?")
# analyzer.be
print('*' * 50)
# analyzer = an
dbug = True
import tabulate
print(tabulate.tabulate(dd, headers='keys'))
lines = "\n".join(lines).replace("\r", "").splitlines()
for i, l in enumerate(lines):
l2.append(l)
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") :
l2.append("") # Empty line instead?
lines = l2
alines = []
in_dot_mode = False
if len(lines[-1]) > 0 and (lines[-1].startswith(" ") or lines[-1].startswith("\t")):
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:
# print("> analyzer.before...", analyzer.before.strip(), "...AFTER...", analyzer.after.strip())
# AFTER =
if analyzer.before.endswith("\n"):
# print("> BREAKING LOOP")
break
else:
before += analyzer.after
break
# print("Before is", before)
abefore = analyzer.before.rstrip()
# Sanitize by removing garbage binary stuff the terminal puts in
abefore = "\n".join([l for l in abefore.splitlines() if not l.startswith('\x1b')] )
dotmode = analyzer.after == "..."
if 'dir(s)' in word:
pass
if 'help(s.find)' in word:
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
# if os.name == 'nt':
# import wexpect as we
# else:
# import pexpect as we
# def rsession(analyzer, lines, extra):
# l2 = []
# dbug = False
# # analyzer = we.spawn("python", encoding="utf-8", timeout=20)
# # analyzer.expect([">>>"])
# if "b = make_square(5)" in "\n".join(lines): # in "\n".join(lines):
# print("\n".join(lines))
# print("-"*50)
# for k in extra['session_results']:
# print(k['input'])
# print(k['output'])
#
# import time
# an = we.spawn(sys.executable, encoding="utf-8", timeout=20)
# try:
# an.setwinsize(400, 400) # set window size to avoid truncated output or input.
# except AttributeError as e:
# print("> Mulble pexpect('pyhon',...) does not support setwinsize on this system (windows?). Ignoring")
#
# an.expect([">>>"])
# l3 = """
# 2 + 4 # Add two integers
# 50 - 5 * 6
# (2 + 2) * (3 - 1) # You can group operations using parenthesis
# 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
# 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
# """
# lines2 = l3.strip().splitlines()
# from collections import defaultdict
# dd = defaultdict(list)
#
# for l in lines2:
# dd['code'].append(l)
# an.sendline(l.rstrip())
# an.expect_exact([">>>", "..."])
# dd["output"].append(an.before.strip())
# # print(">>>", an.before.strip())
# if len(an.after.strip()) > 4:
# print(">>>>>>>>>>>>> That was a long after?")
# # analyzer.be
#
# print('*' * 50)
# # analyzer = an
# dbug = True
# import tabulate
# print(tabulate.tabulate(dd, headers='keys'))
#
# lines = "\n".join(lines).replace("\r", "").splitlines()
#
# for i, l in enumerate(lines):
# l2.append(l)
# 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") :
# l2.append("") # Empty line instead?
#
# lines = l2
# alines = []
# in_dot_mode = False
# if len(lines[-1]) > 0 and (lines[-1].startswith(" ") or lines[-1].startswith("\t")):
# 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:
# # print("> analyzer.before...", analyzer.before.strip(), "...AFTER...", analyzer.after.strip())
# # AFTER =
# if analyzer.before.endswith("\n"):
# # print("> BREAKING LOOP")
# break
# else:
# before += analyzer.after
# break
#
# # print("Before is", before)
# abefore = analyzer.before.rstrip()
# # Sanitize by removing garbage binary stuff the terminal puts in
# abefore = "\n".join([l for l in abefore.splitlines() if not l.startswith('\x1b')] )
#
# dotmode = analyzer.after == "..."
# if 'dir(s)' in word:
# pass
# if 'help(s.find)' in word:
# 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):
......@@ -222,27 +222,28 @@ class FileConsole(code.InteractiveConsole):
def write(self, str):
print(str)
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.
"""
sys.last_type, sys.last_value, last_tb = ei = sys.exc_info()
sys.last_traceback = last_tb
try:
lines = traceback.format_exception(ei[0], ei[1], last_tb.tb_next)
if sys.excepthook is sys.__excepthook__:
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
# 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.
#
# """
# sys.last_type, sys.last_value, last_tb = ei = sys.exc_info()
# sys.last_traceback = last_tb
# try:
# lines = traceback.format_exception(ei[0], ei[1], last_tb.tb_next)
# if sys.excepthook is sys.__excepthook__:
# 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):
from collections import defaultdict
......@@ -286,8 +287,8 @@ def new_run_i(lines, file, output):
art = b['name']
outf = output + ("_" + art if art is not None and len(art) > 0 else "") + ".shell"
# print(outf)
id = os.path.basename(outf)
cutouts[id] = {'first': b['first'], 'block': b['block'], 'last': []}
# id = os.path.basename(outf)
cutouts[os.path.basename(outf)] = {'first': b['first'], 'block': b['block'], 'last': []}
lines = b['last']
#
# continue
......@@ -321,7 +322,6 @@ def new_run_i(lines, file, output):
blks = {}
for id, block in cutouts.items():
# b = block['block']
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] = "\n".join(block['block'][dx:])
......@@ -330,26 +330,8 @@ def new_run_i(lines, file, output):
out = run_code_blocks(blks)
for id in cutouts:
print("-"*5, id, "-"*5)
print("".join(out[id]))
# print("-"*5, id, "-"*5)
# print("".join(out[id]))
with open(f"{os.path.dirname(output)}/{id}", 'w') as f:
f.write("".join(out[id]))
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.
Finish editing this message first!
Please register or to comment