-
Notifications
You must be signed in to change notification settings - Fork 2
/
SetShowAnswerIfGraded.py
111 lines (90 loc) · 2.76 KB
/
SetShowAnswerIfGraded.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# import XML libraries
import xml.etree.ElementTree as ET
import sys
import os
import argparse
instructions = """
To use:
python3 SetShowAnswer.py show_answer_value path/to/problem/folder
show_answer_value can be one of the usual edX set:
Always
Answered
Attempted
Closed
Finished
CorrectOrPastDue
PastDue
Never
It can also be delete or default, in which case all
show_answer values are removed and the course-wide
default takes over.
Options:
-h Print help message and exit.
Last update: March 15th 2018
"""
# Here are all the options for show_answer values:
allAnswerValues = [
"always",
"answered",
"attempted",
"closed",
"finished",
"correctorpastdue",
"pastdue",
"never",
]
parser = argparse.ArgumentParser(usage=instructions, add_help=False)
parser.add_argument("-h", "--help", action="store_true")
parser.add_argument("answerSetting", default="finished")
parser.add_argument("directory", default=".")
args = parser.parse_args()
if args.help:
sys.exit(instructions)
answerSetting = args.answerSetting.lower()
if not os.path.exists(args.directory):
sys.exit("Directory not found: " + args.directory)
numfiles = 0
# Walk through the problems folder
for dirpath, dirnames, filenames in os.walk(args.directory):
for eachfile in filenames:
# Get the XML for each file
tree = ET.parse(os.path.join(dirpath, eachfile))
root = tree.getroot()
# If this isn't a problem file, skip it.
if root.tag != "problem":
continue
# Only set showanswer if the problem is graded.
try:
maxScore = float(root.attrib["weight"])
except KeyError:
# If weight isn't defined, it's 1.
maxScore = 1
except ValueError:
print("Something weird is stored in problem weight for " + eachfile)
continue
if maxScore > 0:
# Set the showanswer value
if answerSetting in allAnswerValues:
root.set("showanswer", answerSetting)
elif answerSetting == "default" or answerSetting == "delete":
try:
del root.attrib["showanswer"]
except:
pass
else:
sys.exit("Invalid showanswer setting.")
else:
# If it's ungraded, let the course default take over.
try:
del root.attrib["showanswer"]
except:
pass
# Save the file
tree.write(
os.path.join(dirpath, eachfile), encoding="UTF-8", xml_declaration=False
)
numfiles += 1
if numfiles == 0:
print("No files found - wrong or empty directory?")
else:
print("Show Answer options set for " + str(numfiles) + " files.")