~chris-rogers/junk/physics_devil

« back to all changes in this revision

Viewing changes to physics_devil/common/_run_db.py

  • Committer: Chris Rogers
  • Date: 2015-03-25 20:37:49 UTC
  • Revision ID: chris.rogers@stfc.ac.uk-20150325203749-3f53k8yk7861a0ml
Update to accept some arguments on command line

Show diffs side-by-side

added added

removed removed

Lines of Context:
45
45
        shutil.rmtree(self.table_path(table))
46
46
 
47
47
    def set_document(self, table, primary_key, document):
48
 
        fout = open(self.doc_path(table, primary_key), 'w')
 
48
        try:
 
49
            fout = open(self.doc_path(table, primary_key), 'w')
 
50
        except IOError:
 
51
            raise RunDbError("Failed to write document "+str(primary_key)+\
 
52
                             " to table "+str(table))
49
53
        fout.write(json.dumps(document, indent=2))
50
54
        fout.close()
51
55
 
52
56
    def get_document(self, table, primary_key):
53
 
        fin = open(self.doc_path(table, primary_key))
 
57
        try:
 
58
            fin = open(self.doc_path(table, primary_key))
 
59
        except IOError:
 
60
            raise RunDbError("Failed to find document "+str(primary_key)+\
 
61
                             " in table "+str(table))
 
62
                 
54
63
        doc_str = fin.read()
55
64
        fin.close()
56
65
        document = json.loads(doc_str)
61
70
 
62
71
    def doc_path(self, table, primary_key):
63
72
        if str(primary_key) == ".rundb":
64
 
            raise IOError("Cannot use primary key .rundb")
 
73
            raise RunDbError("Cannot use primary key .rundb")
65
74
        return os.path.join(self.table_path(table), str(primary_key)+".json")
66
75
 
67
76
    def table_path(self, table):
68
77
        if str(table) == ".rundb":
69
 
            raise IOError("Cannot use table with name .rundb")
 
78
            raise RunDbError("Cannot use table with name .rundb")
70
79
        return os.path.join(self.db_dir, str(table))
71
80
 
72
 
    def print_csv(self, table, keys_sorted, file_name):
 
81
    def print_csv(self, table, keys_sorted, output_dir):
73
82
        """
74
83
        Print a table in csv format (comma separated values)
75
84
        - table: name of the table to be printed
80
89
        table_primary_keys = self.list_keys(table)
81
90
        output_list = [self.get_document(table, key) for key in sorted(table_primary_keys)]           
82
91
        # write the header
 
92
        file_name = os.path.join(output_dir, str(table)+".csv")
83
93
        fout = open(file_name, "w")
84
94
        for key in keys_sorted:
85
95
            fout.write(str(key)+" , ")
86
96
        fout.write("\n")
87
97
        # write the data
88
 
        print output_list
89
98
        for output in output_list:
90
99
            for key in keys_sorted:
91
100
                if key not in output.keys():