-
Notifications
You must be signed in to change notification settings - Fork 0
/
lookupSetRebrick.py
executable file
·103 lines (83 loc) · 2.2 KB
/
lookupSetRebrick.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
#!/usr/bin/env python3
import os
import sys
import libbrick
import rebrick_wrapper
#============================
#============================
def write_header(setID: str, RBW: rebrick_wrapper.Rebrick) -> list:
"""
Write the header row to the CSV file.
Args:
setID: LEGO set ID.
RBW: Instance of Rebrick API wrapper.
Returns:
List of keys for the data dictionary.
"""
data = RBW.getSetData(setID)
allkeys = list(data.keys())
allkeys.sort()
print(', '.join(allkeys))
return allkeys
#============================
#============================
def get_set_data_output(setID: str, RBW: rebrick_wrapper.Rebrick, allkeys: list) -> str:
"""
Get data output string for a single LEGO set.
Args:
setID: LEGO set ID.
RBW: Instance of Rebrick API wrapper.
allkeys: List of keys for the data dictionary.
Returns:
Data output string.
"""
sys.stderr.write(".")
data = RBW.getSetData(setID)
output = ""
row = []
for key in allkeys:
try:
if '{' in str(data.get(key, "")):
row.append("")
continue
row.append(str(data[key]).replace('\n', ''))
except KeyError:
print(f"missing key: {key}")
row.append("")
output += "\t".join(row) + "\n"
return output
#============================
#============================
def main():
"""
Main function to look up LEGO set data using Rebrick API.
"""
if len(sys.argv) < 2:
print("usage: ./lookupLego.py <txt file with lego IDs>")
sys.exit(1)
setIDFile = sys.argv[1]
if not os.path.isfile(setIDFile):
print("usage: ./lookupLego.py <txt file with lego IDs>")
sys.exit(1)
setIDs = libbrick.read_setIDs_from_file(setIDFile)
timestamp = libbrick.make_timestamp()
csvfile = f"set_data-rebrick-{timestamp}.csv"
line_count = 0
RBW = rebrick_wrapper.Rebrick()
with open(csvfile, "w") as f:
allkeys = write_header(setIDs[0], RBW)
f.write("\t".join(allkeys) + "\n")
for setID in setIDs:
if not '-' in setID:
setID = str(setID) + "-1"
line_count += 1
output = get_set_data_output(setID, RBW, allkeys)
f.write(output)
RBW.close()
sys.stderr.write("\n")
print(f"Wrote {line_count} lines to {csvfile}")
print(f"open {csvfile}")
#============================
#============================
if __name__ == '__main__':
main()