0.23 Python bindings

From MythTV Official Wiki
Revision as of 21:03, 4 May 2010 by Wagnerrp (talk | contribs)

Jump to: navigation, search

The Python bindings received a rewrite in the 0.23 development cycle. An overview of the necessary changes needed to be made to existing scripts is outlined in the Transition Guide.

All classes and functions detailed below are included in the MythTV module.

All objects which may use the database for any purpose will have a 'db' keyword input, providing it an existing database connection to use. This allows one to specify the database to use at the beginning of the application, and have it carried through out all subsequent calls. The input will accept any object or subclass of type 'MythDBConn'.

Requirements

Contents

Data Objects

Connection Objects

MythDB(db=None, args=None, **kwargs)

This is the database connection class. It accepts connection settings through the 'args' input as a tuple of tuples, or through several keywords. The usable keywords are 'DBHostName', 'DBName', 'DBUserName', 'DBPassword', 'DBPort', and 'SecurityPin'.

>>> db1 = MythDB(args=(('DBHostName','mybackend'),
                  ('DBName','mythconverg'),
                  ('DBUserName','mythtv'),
                  ('DBPassword','mythtv')))
>>> db2 = MythDB(DBHostName='mybackend',  DBName='mythconverg',
            DBUserName='mythtv',     DBPassword='mythtv')
>>> db3 = MythDB(db=db2)

If the connection settings are not given by the user, they are searched for in '~/.mythtv/config.xml'. If not found there, the object will attempt to find a backend on the network over UPnP, using 0000 if 'SecurityPin' has not been defined.

settings

This is a pseudo-variable with access to the settings table. It accepts two values, the hostname (or 'NULL') and the setting name, and can take them as keys or attributes.

>>> db.settings.NULL.DBSchemaVer
u'1252'
>>> db.settings['mybackend']['BackendServerPort']
u'6543'
>>> db.settings.mybackend.BackendServerPort = 6553

tablefields

This is another pseudo-variable providing access to the database field names.

>>> db.tablefields.jobqueue
[u'id', u'chanid', u'starttime', u'inserttime', u'type', u'cmds', u'flags', u'status', u'statustime', u'hostname', u'args', u'comment', u'schedruntime']
>>> db.tablefields['storagegroup']
[u'id', u'groupname', u'hostname', u'dirname']

cursor(log=None)

This returns a cursor for manual database access. Queries are automatically logged, and an initialized logging object can be specified.

getStorageGroup(groupname=None, hostname=None)

Return a tuple of StorageGroup objects, optionally filtering by groupname and hostname.

>>> db.getStorageGroup(groupname='Videos')
(<StorageGroup 'myth://Videos@mybackend/mnt/mythtv/store/media/video/' at 0x8031eff90,)

getFrontends()

Attempt to connect to all frontends listed in the database, and return a tuple of Frontend objects to all successfully connected to.

getFrontend(host)

Attempt to connect to a single Frontend, using the port defined in the database for the given hostname.

getChannels()

Return a tuple of Channel objects.

getRecorded(title=None, subtitle=None, chanid=None, starttime=None, progstart=None)

Return a single Recorded object, or None, matching the specified search parameters.

searchRecorded(**kwargs)

Return a tuple of Recorded objects, matching the specified search parameters. Accepts the following keywords: title, subtitle, chanid, starttime, progstart, category, hostname, autoexpire, commflagged, stars, recgroup, playgroup, duplicate, transcoded, watched, storagegroup, airdate, stereo, subtitled, hdtv, closecaptioned, partnumber, parttotal, seriesid, showtype, syndicatedepisodenumber, programid, manualid, generic, cast, livetv.

>>> db.searchRecorded(cast='Kiefer Sutherland')
(<Recorded '24','2010-01-18 20:00:00' at 0x803922850>, <Recorded '24','2010-01-25 21:00:00' at 0x803924310>)

>>> db.searchRecorded(title='24', subtitle='Day 8: 6:00PM - 8:00PM') (<Recorded '24','2010-01-18 20:00:00' at 0x80391ff50>,)

searchOldRecorded(**kwargs)

Return a tuple of OldRecorded objects, matching the specified search parameters. Accepts the following keywords: title, subtitle, chanid, starttime, endtime, category, seriesid, programid, station, duplicate, generic.

searchJobs(**kwargs)

Return a tuple of Job objects, matching the specified search parameters. Accepts the following keywords: chanid, starttime, type, status, hostname, title, subtitle, flags, olderthan, newerthan.

searchGuide(**kwargs)

Return a tuple of Guide objects, matching the specified search parameters. Accepts the following keywords: chanid, starttime, endtime, title, subtitle, category, airdate, stars, previouslyshown, stereo, subtitled, hdtv, closecaptioned, partnumber, parttotal, seriesid, originalairdate, showtype, syndicatedepisodenumber, programid, generic, startbefore, startafter, endbefore, endafter.

searchRecord(**kwargs)

Return a tuple of Record objects, matching the specified search parameters. Accepts the following keywords: type, chanid, starttime, startdate, endtime, enddate, title, subtitle, category, profile, recgroup, station, seriesid, programid, playgroup.

MythBE(backend=None, type='Monitor', db=None, single=False)

This is the backend socket connection class. It accepts a 'backend' as a hostname, or IP, otherwise using the master backend. Port number is always pulled from the database. Type can be either 'Monitor' or 'Playback', to determine whether or not the backend is allowed to shut down. This class provides automatic connection sharing between multiple instances, and 'single' tells the class to always create a new connection.

getPendingRecordings()

Returns a list of Program objects for shows matching a recording rule.

getScheduledRecordings()

Returns a list of Program objects for shows scheduled to record.

getUpcomingRecordings()

Returns a list of Program objects for shows matching a recording rule, marked 'will record'.

getRecorderList()

Returns a list of cardids.

getFreeRecorderList()

Returns a list of free cardids.

lockTuner(id=None)

Attempts to lock the specified tuner, returning a tuple of cardid, video device node, audio device node, and VBI device node. Returns -2 on failure, and -1 on no card found.

freeTuner(id=None)

Free the specified tuner, or free all tuners used by this object if none specified.

getCurrentRecording(recorder)

Returns a Program object of the currently recording show.

isRecording(recorder)

Returns a boolean whether the specified cardid is recording.

isActiveBackend(hostname)

Returns a boolean whether the specified backend is currently online.

getRecording(chanid, starttime)

Returns a Program object of the specified show.

getRecordings()

Returns a list of Program objects for all recorded shows.

getExpiring()

Returns a list of Program objects recorded shows eligible for expiration, in the order they will be expired.

getCheckfile(program)

Returns an absolute path in the file system for the specified Program object.

getFreeSpace(all=False)

Returns a list of FreeSpace objects for the current backend, or the whole system.

getFreeSpaceSummary()

Returns a tuple of total space, and total used space.

getLoad()

Returns a tuple of 1, 5, and 15 minute load averages.

getUptime()

Returns machine uptime in seconds.

walkSG(host, sg, top=None)

Behaves similarly to os.walk(). Returns a list of tuples containing the folder name, tuple of directories, and dictionary of files with file sizes as values.

getSGList(host, sg, path, filenamesonly=False)

Returns a tuple of a list of directories, list of files, and list of matching file sizes. If 'filenamesonly' is set, only return the filenames.

getSGFile(host, sg, path)

Returns a tuple of last modification time, and size.

getLastGuideData()

Returns the last date for which guide data is available.

Frontend(host, port)

Connects to a frontend control socket, specified by a hostname or IP and a port.

getJump()

Returns a list of jump points.

getKey()

Returns a list of usable keys.

getQuery()

Returns a list of usable queries.

getPlay()

Returns a list of usable playback commands.

sendJump(jumppoint)

Issues a jump point.

sendKey(key)

Issues a key press.

sendQuery(query)

Issues a query, and returns the response.

sendPlay(play)

Issues a playback command.

MythVideo(db=None, args=None, **kwargs)

This class behaves similarly to MythDB, and accepts the same input arguments. Additionally, the 'settings', 'tablefields', and 'getStorageGroup()' functions are available.

scanStorageGroups(deleteold=True)

This function performs a scan of the storage groups directories on each machine with a Videos group listed. It returns a tuple containing two lists of Video objects. The function checks new files against existing hashes, and the two lists are new videos to be added, and old videos to be deleted, respectively. The function will remove old videos from the database automatically by default, and new videos are uninitialized, but populated with 'title', 'subtitle', 'season', 'episode', 'host', and 'hash'.

searchVideos(**kwargs)

Return a list of Video objects, matching the specified search parameters. Accepts the following keywords: title, subtitle, season, episode, host, director, year, cast, genre, country, file, exactfile, insertedbefore, insertedafter.

getVideo(**kwargs)

Behaves identically to searchVideos, but returns the first response.

MythXML(backend=None, db=None)

getServDesc()

getHosts()

Returns a list of unique hosts found in the settings table.

getKeys()

Returns a list of unique keys found in the settings table.

getSetting(key, hostname=None, default=None)

Returns the requested setting value from the settings table, accepting a default value.

getProgramGuide(starttime, enddime, startchan=None, numchan=None)

Returns a list of Guide objects for the specified time period, taking an optional starting channel and channel range.

getProgramDetails(chanid, starttime)

Returns a Program object for the specified show.

getChannelIcon(chanid)

Returns a channel icon.

getRecorded(descending=True)

Returns a list of Program objects for all recorded shows

getExpiring()

Returns a list of Program objects for recorded shows nearing expiration.

System Objects

Grabber(path=None, setting=None, db=None)

Basic handler for external data handlers. Accepts either an absolute path to the external executable, or a field in the settings table containing the path.

append(*args)

Permanently appends one or more arguments to the executable path, separated by spaces.

command(*args)

Calls the executable with one or more arguments appended to the existing command, and returns the standard output as a string. Raises an exception if the return code is not equal to one. The return code and standard error can be retrieved through the exception, or through Grabber.returncode and Grabber.stderr.

VideoGrabber(mode, lang='en', db=None)

Modified Grabber class, taking 'TV' and 'Movie' for mode.

setOverride(data)

Accepts a tuple of tuples containing a show title and matching inetref. Allows overriding the responses returned by the searchTitle function.

>>> grab = VideoGrabber('TV')
>>> grab.searchTitle('24')
[(76290, '24', None), (79848, '24 Hour Design', None), (73012, 'Pure 24', None), (88501, 'Truth in 24', None), (90351, 'Final 24', None), (114171, '24 h Berlin - Ein Tag im Leben', None), (76047, 'BBC News 24', None), (74238, '24 Hour Quiz', None), (84312, 'BBC News 24: Click', None)]
>>> grab.setOverride((('24',76290),))
>>> grab.searchTitle('24')
((76290, '24', None),)

searchTitle(title, year=None)

Returns a list of tuples containing title, inetref, and year. Results are filtered by year if given. Returns an empty list upon failure.

>>> grab = VideoGrabber('Movie')
>>> grab.searchTitle('The Italian Job')
[(9654, 'The Italian Job', 2003), (10536, 'The Italian Job', 1969)]
>>> grab.searchTitle('The Italian Job',1969)
[(10536, 'The Italian Job', 1969)]

searchEpisode(title, subtitle)

Returns a 2-tuple containing season and episode. Returns a 2-tuple of None upon failure.

>>> grab = VideoGrabber('TV')
>>> grab.searchEpisode('Fringe','Pilot')
(1, 1)

getData(inetref, season=None, episode=None, additional=False)

Returns a tuple containing a data dictionary, lists of cast, genre, and country, and optionally a dictionary of any additional data returned by the grabber. The first dictionary is data directly applicable to a Video object. The second contains any additional data provided by the grabber but not used by the videometadata table.

NetVisionGrabber(name, type, db=None)

searchXML(title, page=1)

treeXML()

setUpdated()

Accessory Objects

MythLog(module='pythonbindings', lstr=None, lbit=None, db=None, logfile=None)

This class implements logging in a similar format to that provided by the various MythTV binaries. Logs are timestamped, and include a module name and message. The module carries a global log level, shared by all instances of the class in the current process. This log level is a bitwise operator, allowing the following named levels: important, general, record, playback, channel, osd, file, schedule, network, commflag, audio, libav, jobqueue, siparser, eit, vbi, database, dsmcc, mheg, upnp, socket, xmltv, dvbcam, media, idle, channelscan, extra, timestamp. A log will be printed only if the log's level matches one in the global level.

The log level can be set either by a string, or an integer. The string follows the same format used by MythTV binaries, a comma separated sequence with levels optionally prepended with 'no', and the integer can be built manually by provided bit values.

from MythTV import MythLog
log = MythLog(lstr='important,general,file')
log = MythLog(lstr='all,nodatabase')
log = MythLog(lbit=MythLog.IMPORTANT|MythLog.SOCKET)

The logfile is an optional input that when used, will send all logging irreversibly to the specified log file

log(level, message, detail=None)

Logging is intended to match that normally found in the frontend and backend logs. The level is the value to be tested against the global log filter, and can contain multiple different levels. If one matches, the log is printed. This method is used if the MythLog object is called directly.

>>> log = MythLog(module='log test', lstr='important,socket')
>>> log.log(MythLog.IMPORTANT, 'test')
2010-03-20 03:35:56.088 log test: test

>>> log(MythLog.IMPORTANT, 'a bit cleaner syntax')
2010-03-20 03:36:07.999 log test: a bit cleaner syntax

>>> log(MythLog.DATABASE, 'this log does not match the filter')
>>> log(MythLog.DATABASE|MythLog.SOCKET, 'but this one does')
2010-03-20 03:36:54.598 log test: but this one does

>>> log(MythLog.DATABASE|MythLog.SOCKET, 'print a log', 'with additional detail')
2010-03-20 03:37:18.262 log test: print a log -- with additional detail

_setlevel(lstr=None, lbit=None)

If you do not want to log anything, but still want to control the level of logging existing in the bindings, this method can be used to set the global filter. The same string and bitwise values as explained before are used. A string of 'none' can be used to squelch all logging.

from MythTV import MythLog
MythLog._setlevel('none')

MythError(*args)

This class accepts a single error string, or an error code followed by additional inputs defined by the error code. An error string is available in both the 'args' attribute as a single item in a tuple and 'message' attribute as a string. The error code is available in 'ecode', and additional attributes may be available dependent on the error code.

Code Numeric Attributes Description
GENERIC 0
SYSTEM 1 retcode, command, stderr
DB_RAW 50 sqlcode, sqlerr
DB_CONNECTION 51 dbconn
DB_CREDENTIALS 52
DB_SETTING 53 setting, hostname
DB_SCHEMAMISMATCH 100 setting, remote, local
PROTO_CONNECTION 101 backend, port
PROTO_ANNOUNCE 102 backend, port, response
PROTO_MISMATCH 50 remote, local
FE_CONNECTION 150 frontend, port
FE_ANNOUNCE 151 frontend, port
FILE_ERROR 200 reason
FILE_FAILED_READ 201 file
FILE_FAILED_WRITE 202 file, reason


This class is duplicated in 'MythDBError', 'MythBEError', 'MythFEError', and 'MythFileError', for further filtering ability.

Advanced Objects