-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfortune_to_sqlite3.py
More file actions
executable file
·48 lines (34 loc) · 1.16 KB
/
fortune_to_sqlite3.py
File metadata and controls
executable file
·48 lines (34 loc) · 1.16 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from sqlalchemy import create_engine
from fortune import schema
def usage():
print 'fortune_to_sqlite3.py <fortune-path> <database-path>'
def parse_args(args):
fortune_path = None
database_path = None
if len(args) >= 2:
fortune_path = args[0]
database_path = args[1]
help_needed = fortune_path == None or database_path == None
return help_needed, fortune_path, database_path
def read_fortunes(fortunes_path):
with open(fortunes_path) as f:
return [fortune.decode('utf-8')
for fortune in f.read().split("\n%\n")
if len(fortune) > 0]
def add_fortunes(db, fortunes):
db.execute(schema.fortunes.insert(),
[{'body': fortune} for fortune in fortunes])
def main():
help_needed, fortunes_path, database_path = parse_args(sys.argv[1:])
if help_needed:
usage()
sys.exit(0)
engine = create_engine('sqlite:///' + database_path)
schema.metadata.create_all(engine)
with engine.connect() as db:
add_fortunes(db, read_fortunes(fortunes_path))
if __name__ == '__main__':
main()