Learning Python and Kodi Add-on Development - A Journey..
#1
This thread will track my progress in learning Python and eventually lead to development of various Kodi Add-ons.
Image

I'll look into the basics of python and then how it can be used to create Kodi Add-ons. I'll look at the JSON API, database add-ons, programs and services. I may also look into some basic skinning and GUI code. I also want to look into 3rd party tools, and development environments and workflows for things like debugging.

I'll ask questions along the way, and track everything I learn as I go along. The path traveled by many other developers in the past, the difference this time is I will write it down for others to benefit! One thing I have noticed with Kodi, is the develpper documentation is very poor for the new user, this is something I wish to change.

Background
I've been a self taught PHP developer for a few years, I just do it for fun and have learnt off the internet.
I have no experience of writing in python other than seeing a few examples on the wiki and github over the years.

Plan
I'll be learning from scratch so the first things to do is learn the Pyhon language. I'll be using Code Academy (an online code training site) for this.
I'd also like some physical book references, can recommend some good Python books I can buy from Amazon?
I'll then get into the structure of Kodi Add-ons
And then write some example Add-ons
Go through Github usage
Create my own repository repo's
Finally I'll run through how to submit and publish an add-on to the official repository

So let it begin....
Reply
#2
if you ever have a question feel free to ask...

Basic Python tutorials:
https://www.youtube.com/playlist?list=PL...17E1E5C0DA

I personally do not use an IDE for Kodi development.. But I heard this one is good for Kodi, uses pycharm.
http://romanvm.github.io/xbmcstubs/

Kodi Docs:
http://romanvm.github.io/xbmcstubs/docs/index.html

Good luck Smile
Image Lunatixz - Kodi / Beta repository
Image PseudoTV - Forum | Website | Youtube | Help?
Reply
#3
pyCharm is really nice, especially if your a beginner. All jetbrains IDEs are really good correcting or improving your coding skills.
But I'm also planning to try out phils sublime package when I find time. As I learned to love sublime for things like laravel.
Reply
#4
Yeh I'm already a notepad++ user so will probably use that at first.

I find sometimes using the simple tools aids learning and the more advanced tools are useful later on.
Reply
#5
End of Day 1 and I have found out:

- Kodi uses python 2, this is not clear from the wiki so good to know! I'll try to get that updated.
- You can test python on windows by installing from the python website and running the command line client
- Python does not need a symbol such as ; at the end of a line like PHP
- Python has a very simple sytax. Indentation is done with a simple whitespace.

Some starter code examples:

Print Hello world to the screen
PHP Code:
print "Hello World" 

Print calculator
PHP Code:
print 10*

Store the string hello world in a variable and print to screen
PHP Code:
"Hello World!"
print 

Import a module, and assign that to a custom function
PHP Code:
import math
math.floor
x
(18.8

I also created my first Python file using the IDLE program that is installed with Python. It syntax highlights things and you can save the file as a .py to the file system.

Lastly I associated .PY files with the python.exe program, so now I can use any text editor to test python files Wink Just double click on the file to run it in a small window.

Thats enough for today, more tomorrow...
Reply
#6
Actually you should know the big differences between python versions. It's python2.6.x or python2.7.x depending on platform.
Read/follow the forum rules.
For troubleshooting and bug reporting, read this first
Interested in seeing some YouTube videos about Kodi? Go here and subscribe
Reply
#7
Great stuff zag, I wish you luck in your journey. Python is pretty easy to understand and to master if you come from php. Documentation for addon development is not bad at all if you know how to program in python in the first place but I agree it is not great if you don't know how to program in python and want to get started by "learning python for kodi"...like I did. The process of making and debugging an addon can be sometimes quite boring since you don't have any way of executing the code if it uses any of the kodi modules without try, try and try again in kodi itself. I think there is a way to debug it without having it running on kodi but still, you don't know if the code actually works...you just know there isn't any typo.
So basically, notepad++ opened, log file opened, change the code hit return, enter the addon again, check the log for errors. If the code is not giving you errors and it doesn't do what you want it to do, add some prints along the way to understand where it is failing.

As for python versions kodi uses 2.7 in most platforms but uses 2.6 on android (not sure if anything else uses it). This can be tricky if you use modules like datetime since some methods like total_seconds() are not available in python2.6 but are in 2.7. I wouldn't bother with it for now.

A few tips:
-Learn well the basics of python data structures and variables type: https://docs.python.org/2/tutorial/datastructures.html
Then you'll understand easier the code of other addons. They usually just save data to a datastructure and retrieve it later.

A few tips for kodi related stuff:
-Python api documentation is here: http://mirrors.kodi.tv/docs/python-docs/14.x-helix/
You'll find there all the classes and specific functions of each module. Please try to master classes and functions, that will make you understand how python works. As an example, look at 'xbmc' module.
Let's say you want to create an instance of the Player() class and then use the play function of this class. You'd do something like this:

Code:
import xbmc
myplayer = xbmc.Player()
myplayer.play('http://some_internet_video_link')

For functions that don't belong to any class you'll do something like below. For instance, suppose you want to know the inet ip address of your machine using the xbmc module (check the standalone function list on the bottom of xbmc module documentation):

Code:
import xbmc
print "My ip is " + xbmc.getIPAddress()

Concatenation is done using + instead of php . for variables of the same type.

Stuff I wished someone has told me before I started:

1) Trigger actions

Sometimes you want to execute certain functions in kodi that are not exposed to the python api. In this case, if you can't find any method in the documentation you should check:
-XBMC builtin functions (http://kodi.wiki/view/List_of_built-in_functions)
-JSON-RPC API (http://kodi.wiki/view/JSON-RPC_API/v6) (json is more used to retrieve data instead of trigger an action so it's mentioned a bit below).

Simple examples using builtin functions:

Suppose you want to restart the pvr manager. You won't find any way to do this in the python modules. You can do that using a kodi builtin function:

Code:
import xbmc
xbmc.executebuiltin('StartPVRManager')

Suppose you want to take a screenshot of your kodi screen from python:
Code:
import xbmc
xbmc.executebuiltin('TakeScreenshot')

There isn't any way to execute the stuff above without builtin functions.

2) Get information back from kodi
Sometimes you want to get some parameters or settings from kodi and you won't find a way of retrieving this info from the python api. In these cases you should look into:

-JSON-RPC API (http://kodi.wiki/view/JSON-RPC_API/v6)
-Kodi boolean functions (http://kodi.wiki/view/List_of_boolean_conditions)
-Kodi infolabels (http://kodi.wiki/view/InfoLabels)

2.1) JSON - You may want to use the json-rpc api if you want to have in python some very detailed information and there is no other way to grab it. Let's say you want to grab all the channel groups of your pvr (TV channels):

Code:
import xbmc
import json
response = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "PVR.GetChannelGroups", "params": {"channeltype" : "tv"}, "id": 1 }')
response_as_a_python_dictionary = json.loads(response)

This will help you understand why I said in the beginning to understand very well data structures. executeJSONRPC gets the info as simple string. json.loads converts this response into a python dictionary, you can use to retrieve specific information. Look below:

Code:
print type(response)

returns:
<type 'str'>

Code:
print type(response_as_a_python_dictionary)

returns:
<type 'dict'>

Code:
print response_as_a_python_dictionary

returns:
{u'jsonrpc': u'2.0', u'id': 1, u'result': {u'channelgroups': [{u'channeltype': u'tv', u'channelgroupid': 23, u'label': u'All channels'}, {u'channeltype': u'tv', u'channelgroupid': 24, u'label': u'Sport'}, {u'channeltype': u'tv', u'channelgroupid': 25, u'label': u'Entertainment'}, {u'channeltype': u'tv', u'channelgroupid': 26, u'label': u'Documentary'}}}

Getting info from the dictionary is terribly easy! Again to stress you need to understand very well data structures...the overall response_as_a_python_dictionary variable is a python dictionary (see {}) . Dictionaries have keys and values. Those values can be of any type. In the case above, the value for the key 'result' is another dictionary (see {}) . For this this dictionary, the key 'channelgroups' is a list (see [] ), each item in this list is another dictionary (see {}).
So suppose we want to grab a list of all channel group labels (code documented):

Code:
#we start by creating an empty list
my_channellabels = []
#we iterate the items in the list that are the value of 'channelgroups' key that itself is the value of 'result' key of the main dictionary
for sub_dictionary in response_as_a_python_dictionary['result']['channelgroups']:
    #we append the value of the key 'label' to my_channellabels list
    my_channellabels.append(sub_dictionary['label']
#we print the overall list
print my_channellabels

result will be: ['All channels','Sport','Entertainment',''Documentary'']

2.2) Boolean functions
Boolean functions return True of False if a given condition is verified. You usually don't have any way of checking if the user has some property defined in any other way (probably with json you can grab them as well) and it is too simple!

Suppose you want to know if the user is running Windows:
Code:
import xbmc
condition = xbmc.getCondVisibility('System.Platform.Windows')
if condition:
    print "The user is running windows. Virus everywhere..."
else:
    print "The user is not running windows. What is we running?"
    condition = xbmc.getCondVisibility('System.Platform.OSX')
    if condition:
        print "The user is running osx, he has a starbucks free pass"
    else:
        condition = xbmc.getCondVisibility('System.Platform.Linux')
        if condition:
            print "Oh no, another geeky nerd"
        else:
            print "the user is not running windows, not osx, not linux. "


2.3) Infolabels
Infolabels are another way of getting short and specific info from kodi you can use to later execute specific functions or perform some actions. Unlike boolean conditions (true false for a given condition), they return strings. Suppose you want to know title of the media that is playing. In this example we'll mix boolean conditions with infolabels.

Code:
import xbmc
condition = xbmc.getCondVisibility('Player.HasMedia')
if condition:
    print "Kodi is playing something..."
    is_video = xbmc.getCondVisibility('Player.HasVideo')
    if is_video:
        print "Kodi is playing the following video: " + xbmc.getInfoLabel('VideoPlayer.Title')
    else:
        #It is playing music
        print "kodi is playing the following music: " + xbmc.getInfoLabel('MusicPlayer.Title') + ' from ' + xbmc.getInfoLabel('MusicPlayer.Artist') + ' and the album is ' + xbmc.getInfoLabel('MusicPlayer.Album')
else:
    print "Kodi is not playing anything"

Another example, get the user's weather conditions:

Code:
import xbmc
weatherconditions = xbmc.getInfoLabel('Weather.Conditions')
weatherlocation = xbmc.getInfoLabel('Weather.Location')
if 'rain' in weatherconditions and 'London' in weatherlocation:
    print "Oh god...it's raining in London. The world is about to end!"

-----------------------------------
I wish you luck in your journey. The stuff above is pretty simple and just stresses ways of getting data, conditions and perform actions. Usually you see questions in the forum about "how to get this" and "how to get that" and the solution is often the same...infolabels, boolean conditions, json rpc.

Since you are a web developer you could probably create a simple blog to document your journey. Probably we can even get other people to contribute and submit posts. Later with proper tutorials they could be moved to the wiki.

Subscribed the thread, anything you need just ask. I finish by saying I really wished everyone would be like you around these forums...trying to learn, to help others, to document stuff with a lot of detail without keeping the solution for yourself or answer in 2 or 3 words just to stress "how good I am" and how my ego is big.
Cheers
Reply
#8
Hey zag, I'm totally following this thread. Done PHP self ....... other languages. Hope I can get some time to contribute.
Reply
#9
Day 2
Today i learnt about strings, variables and arrays(python calls these sequences).

Strings
Code:
You can add strings to strings
x = "Firstname" + Surname
print x
Just make sure you are adding the same variable type such as a string or a number.

Arrays
You can define an array easily into a variable like so.

Code:
family = ['dad','mum','brother']
print family[0]

Notice that I can print the first element of the array which is always 0. You can also count from the back of the list by using negative numbers.

You can "Slice" through an array using the following code. This lets you extract certain pieces of an array in sequence.

Code:
example=[0,1,2,3,4,5,6,7,8,9]
print example[4:8]

In this example you can grab the numbers 4,5,6,7

Or we can skip the even numbers like this
Code:
example=[0,1,2,3,4,5,6,7,8,9]
print example[1:8:2]

You can also count the elements in an array using
Code:
print len(family)

Searching an array can also be quite useful sometimes

Code:
family = ['dad','mum','brother']
print 'dad' in family
This will return true(which we print for debugging) because 'dad' is in the array

And editing an element of the array is easy enough
Code:
family[1]='Sister'
print family

Or we can delete things from an array
Code:
del family[1]
print family

Arrays are really important because they are how you will store your runtime data in your add-on. This could be user input, or database items or scraped items.
Reply
#10
Just a quick note: Python doesn't have arrays, those are lists. Python tuples are more like arrays in other languages.
Reply
#11
Thanks, that's good to know!

Day 3

Today I learned all about IF statements which are pretty essential for most programs.

The syntax for a python IF statement is like this

Code:
nickname = "zag"
if nickname == "zag":
     print "The Nickname is Zag"
else:
     print "The Nickname is not Zag"

Notice that each if statement uses double == to show its not assigning a variable, also there is a colon : at the end
The text is indented on the next line, to define what happens if the IF statement is true.
You can also use else (or elif) to have an action when the IF statement is false (or if it hits another criteria)

If you want to have multiple IF statements, then you need to nest the statements like this
Code:
if thing == "animal":
    if animal == "cat":
        print "this is a cat"
    else:
        print "i dont know"
else:
    print "i dont know this thing is"

There are also different tests you can perform in IF statements such as:
== (is equal)
< (less than)
> (more than)
<= (less than or equal)
!= (Does not equal)
is (is the same object)
in (search for a string in object)

Lastly for today, lets see how to combine IF statements in 1 check:

Code:
thing = 5

if thing > 3 and thing < 10:
    print "number is between 3 and 10"

You can also use operators such as OR to see if one or the other statement is true.
Reply
#12
As you mentioned elif, heres an improved example:

Code:
if thing == "animal":
    if animal == "cat":
        print "this is a cat"
    elif animal == "dog":
        print "this is a dog"
    else:
        print "i dont know"
else:
    print "i dont know this thing is"

Also a bit advanced, but the shorthand if is quiet useful some times.
So you can do it this way:
Code:
if a > b:
  x = 'a is bigger'
else:
  x = 'b is bigger or equal'

Or use the shorthand
Code:
x = 'a is bigger' if a > b else 'b is bigger or equal'
Reply
#13
Day 4
Quick lesson for today which is Loops! Essential for any program really.

There are 2 main types of loop. "While"(as long as something is true/false) and "For" (Loops through an object or sequence)

Code:
b=1
while b < 10:
    print b
    b +=1

So here you can see we are defining b as 1, then making a loop that goes on until b is less than 10. Each loop we are printing the b and adding +1 each time to the variable b. Pretty simple hopefully! Don't forget the : at the end of the 1st line of a loop, just like we did on the if statement.

Code:
groceries=['bread','milk','meat','beef']
for food in groceries:
    print food

Very simple here, we are just looping though a list of groceries, and assigning each item of the list to a new variable called "food". We then print out each food item to a new line (this seems to be automatic with python).

Code:
ages={'dad':50,'mum':45,'sister':21}
for item in ages:
    print item, ages[item]

Here we are getting slightly more complicated by looping through a dictionary and finding the object name, and the data (in this case the age). Printing the item in brackets means it looks at the data of the dictionary, rather than the object name.

Lastly is sometimes useful to break out of a loop, or infinite loop like below.

Code:
while 1:
    name = raw_input('Enter Name: ')
    if name == 'quit': break

The loop goes on forever, until the user enters "quit" at which point the loop will break and finish. Moving onto the next code in sequence. This reminds me of basic back in the day Smile

That's it for today's tutorials, if anyone else is following them don't forget to check out these videos here which is where i'm getting these exampes from. Its nice and easy to follow.

https://www.youtube.com/watch?v=4Mf0h3Hp...DA&index=1
Reply
#14
Oh and a quick look at my development environment for anyone whos interested.

Image

A customized version of Notepad++ on the left, the python text file script as an icon on the desktop in the center top, and a command line on the right where I just run the python file by typing its name. This allows quick testing of the file, with a nice looking text editor. Other editors I can recomend include sublimetext 3 or good old windows notepad, both should work fine, just make sure you are saving the file as a .py extension.

TIP: You don't have to type the script name in each time, just press up on the keyboard to copy the last line of text you executed in the command prompt.
Reply
#15
For everyone that already knows an other language and wonders.
"for" in python is not really like the for you might know, it's more like "foreach"
Reply

Logout Mark Read Team Forum Stats Members Help
Learning Python and Kodi Add-on Development - A Journey..5