1- # Corresponds to the Requirements for homework 6. Requires cloc and nbconvert. Usage:
1+ # Corresponds to the Requirements for homework 6. Usage:
22#
33# python3 ./extras/scripts/hw_6_check.py <assignment>.ipynb
44
55import ast
6- import json
76import os
7+ import tempfile
88import pandas as pd
9+ from pygount import SourceAnalysis
910import re
10- import shlex
11- import subprocess
1211import sys
1312
1413sys .path .append (os .path .dirname (os .path .abspath (__file__ )))
@@ -59,39 +58,9 @@ def visit_Call(self, node):
5958 self .is_present = True
6059
6160
62- def handle_process_err (cmd , err ):
63- if type (cmd ) == list :
64- cmd = shlex .join (cmd )
65-
66- output = err .stderr .decode ("utf-8" )
67- print (
68- f"{ bcolors .FAIL } ERROR{ bcolors .ENDC } while running\n \n \t { cmd } \n \n { output } " ,
69- file = sys .stderr ,
70- )
71- sys .exit (err .returncode )
72-
73-
74- def get_cmd_output (cmd , input = None , shell = False ):
75- try :
76- process = subprocess .run (
77- cmd ,
78- capture_output = True ,
79- check = True ,
80- input = bytes (input , "utf-8" ),
81- shell = shell ,
82- )
83- except subprocess .CalledProcessError as err :
84- handle_process_err (cmd , err )
85-
86- return process .stdout
87-
88-
89- def lines_of_code (code ):
90- output = get_cmd_output (
91- "cloc --stdin-name=script.py --json -" , input = code , shell = True
92- )
93- data = json .loads (output )
94- return data ["SUM" ]["code" ]
61+ def lines_of_code (file_path ):
62+ results = SourceAnalysis .from_file (file_path , "pygount" )
63+ return results .code_count
9564
9665
9766def code_contains (pattern , code ):
@@ -164,12 +133,20 @@ def exit(results):
164133 sys .exit (exit_code )
165134
166135
167- if __name__ == "__main__" :
136+ def write_to_tmp_file (content ):
137+ with tempfile .NamedTemporaryFile (delete = False , suffix = ".py" ) as temp :
138+ temp .write (bytes (content , "utf-8" ))
139+ return temp .name
140+
141+
142+ def run ():
168143 notebook_path = sys .argv [1 ]
169144
170145 notebook = read_notebook (notebook_path )
171146 script = notebook_to_script (notebook )
172- num_lines = lines_of_code (script )
147+
148+ script_path = write_to_tmp_file (script )
149+ num_lines = lines_of_code (script_path )
173150
174151 # use pandas for outputting a table
175152 results = pd .Series (
@@ -184,3 +161,7 @@ def exit(results):
184161 outputs = results .apply (lambda val : pass_fail (val ))
185162 print (outputs .to_string ())
186163 exit (results )
164+
165+
166+ if __name__ == "__main__" :
167+ run ()
0 commit comments