Tidied up the recording script to use named variables, and added an optional file...
[recordtv.git] / src / rtv_utils.py
blob16d922407d6161429615ae552fcb1fd158b0d866
1 #!/usr/bin/python
3 import os, select, re, datetime, time, xml.parsers.expat, popen2
4 import rtv_saxhandler
6 SECS_IN_DAY = 60*60*24
7 MINS_IN_DAY = 60*24
9 def ensure_dir_exists( dr ):
10 if os.path.isfile( dr ):
11 raise Exception( ( "Can't create config directory '%s' "
12 + "- there is a file already there!" ) % dr )
14 if not os.path.isdir( dr ):
15 os.makedirs( dr )
17 ALLOWED_CHARS_RE = re.compile( "[0-9a-zA-Z_-]" )
18 def prepare_filename( fn ):
19 ret = ""
20 for ch in fn[:20]:
21 if ALLOWED_CHARS_RE.match( ch ):
22 ret += ch
23 else:
24 ret += "_"
25 return ret
27 def run_command( cmd_array ):
29 pop = popen2.Popen4( " ".join( cmd_array ) )
31 ret_val = pop.wait()
33 #print "Return value = '%s'" % ret_val
35 return ret_val == 0
37 def run_command_write_output( cmd_array, output_filename ):
39 cmd = " ".join( cmd_array )
40 cmd += " > "
41 cmd += output_filename
43 #print "Running command " + cmd
45 ret_val = os.system( cmd )
47 #print "Return value = '%s'" % ret_val
49 return ret_val == 0
51 def run_command_feed_input( cmd_array, input_string ):
53 #print "Running command " + str( cmd_array )
54 (i, oe) = os.popen4( cmd_array )
56 #print "Feeding input " + input_string
58 i.write( input_string )
59 i.close()
61 ret = []
62 for ln in oe.readlines():
63 ret.append( ln )
64 #print "Output: " + ln,
66 return ret
68 def parse_xmltv_files( config, sax_callback ):
70 parser = xml.parsers.expat.ParserCreate()
71 handler = rtv_saxhandler.SaxHandler( sax_callback )
72 parser.StartElementHandler = handler.startElement
73 parser.EndElementHandler = handler.endElement
74 parser.CharacterDataHandler = handler.characters
76 done = False
77 for fn in os.listdir( config.xmltv_files_dir ):
78 if fn[-6:] == ".xmltv":
79 done = True
81 full_fn = os.path.join( config.xmltv_files_dir, fn )
82 #print "Parsing '%s'" % full_fn
83 fl = file( full_fn, "r" )
84 parser.ParseFile( fl )
85 fl.close()
87 if not done:
88 print ( "Unable to parse xmltv listings - no files found"
89 + " in directory '%s'." % config.xmltv_files_dir )
92 def parse_datetime( stringdatetime, format ):
93 return datetime.datetime( *time.strptime( stringdatetime, format )[0:6] )
95 def read_file_into_str( filename ):
96 fl = file( filename, "r" )
97 ans = fl.read()
98 fl.close()
100 return ans
102 def encode_text( text ):
103 return unicode( text ).encode( 'ascii', 'ignore' )