Full Circle Magazine 'Programming in Python' Series. Volume 8.
Full Circle Magazine 'Programming in Python' Series. Volume 8.
PROGRAM
IN PYTHON
Volume Eight
Six
Parts 44
34-43
2-38
Full Circle Magazine is neither ailiated, with nor endorsed by, Canonical Ltd.
Full Circle Magazine Specials
About Full Circle
Full Circle is a free, Find Us
independent, magazine Website:
dedicated to the Ubuntu http://www.fullcirclemagazine.org/
family of Linux operating
systems. Each month, it Forums:
contains helpful how-to http://ubuntuforums.org/
articles and reader- forumdisplay.php?f=270
submitted stories. Welcome to another 'single-topic special' IRC: #fullcirclemagazine on
Full Circle also features a In response to reader requests, we are assembling the chat.freenode.net
companion podcast, the Full content of some of our serialised articles into dedicated Editorial Team
Circle Podcast which covers
editions. Editor: Ronnie Tucker
the magazine, along with
other news of interest. For now, this is a straight reprint of the series (aka: RonnieTucker)
'Programming in Python', Parts 44-48 from issues #73 [email protected]
Please note: this Special through #78, allowing peerless Python professor Gregg Webmaster: Rob Keria
Edition is provided with Walters #74 as time of for good behaviour. (aka: admin / linuxgeekery-
absolutely no warranty [email protected]
Please bear in mind the original publication date; current
whatsoever; neither the Editing & Proofreading
contributors nor Full Circle versions of hardware and software may difer from those
Mike Kennedy, Lucas Westermann,
Magazine accept any illustrated, so check your hardware and software versions Gord Campbell, Robert Orsino,
responsibility or liability for before attempting to emulate the tutorials in these special Josh Hertel, Bert Jerred
loss or damage resulting from editions. You may have later versions of software installed
readers choosing to apply this Our thanks go to Canonical and the
or available in your distributions' repositories.
content to theirs or others many translation teams around the
computers and equipment. Enjoy! world.
The articles contained in this magazine are released under the Creative Commons Attribution-Share Alike 3.0
Unported license. This means you can adapt, copy, distribute and transmit the articles but only under the following conditions:
You must attribute the work to the original author in some way (at least a name, email or URL) and to this magazine by name ('full circle magazine') and
the URL www.fullcirclemagazine.org (but not attribute the article(s) in any way that suggests that they endorse you or your use of the work). If you alter,
transform, or build upon this work, you must distribute the resulting work under the same, similar or a compatible license.
Full Circle Magazine is entirely independent of Canonical, the sponsor of Ubuntu projects and the views and opinions in the magazine should in
no way be assumed to have Canonical endorsement.
The first thing we want to do is be an exit button to end the test [(200,260), 97x27]
answer a question from a reader. I
was asked to talk about QT resize the main window. Make it program. On the left side of the
Creator, and how to use it to about 500x300. You can tell how designer window you will see all of In the parentheses are the X
design user interfaces for Python big it is by looking at the Property the controls that are available. Find and Y positions of the object
programs. Editor under the geometry the 'Buttons' section and drag and (push-button in this case) on the
property on the right side of the drop the 'Push Button' control form, followed by its width and
Unfortunately, from what I can designer window. Now, scroll down onto the form. Unlike the GUI height. I moved mine to 200,260.
tell, the support for QT Creator on the property editor list box until designers we have used in the
isn't ready yet for Python. It IS you see 'windowTitle'. Change the past, you don't have to create grids Just above that is the
being worked on, but is not “ready text from 'MainWindow' to 'Python to contain your controls when you objectName property—which, by
for prime time” quite yet. Test1'. You should see the title bar use QT4 Designer. Move the default, is set to 'pushButton'.
of our design window change to button to near center-bottom of Change that to 'btnExit'. Now
So, in an effort to get us ready 'Python Test1 – untitled*'. Now is a the form. If you look at the scroll down on the Property Editor
for that future article, we will work list to the 'QAbstractButton'
with QT4 Designer. You will need section, and set the 'text' property
to install (if they aren't already) to 'Exit'. You can see on our form
python-qt4, qt4-dev-tools, python- that the text on the button has
qt4-dev, pyqt4-dev-tools and changed.
libqt4-dev.
Now, add another button and
Once that is done, you can find position it at 200,200. Change its
QT4 Designer under Applications | objectName property to
Programming. Go ahead and start 'btnClickMe,' and set the text to
it up. You should be presented 'Click Me!'.
with something like the following:
Next add a label. You will find it
Make sure that 'Main Window' in the toolbox on the left under
is selected, and click the 'Create' 'DisplayWidgets'. Put it close to
button. Now you will have a blank the center of the form (I put mine
True
We create our two lists,
shoppinglist for what we need and
medical issues, this will be a fairly uses include membership testing and basket for what we have. We
short article (in the grand scheme eliminating duplicate entries. Set >>> 'kiwi' in fruit assign each to a set and then use
of things) this month. However, we objects also support mathematical False the set difference operator (the
will push through and continue our operations like union, intersection, minus sign) to give us the items
series on the media manager difference, andsymmetric >>>
that are in the shopping list but
program. difference.” not in the basket.
That's pretty simple and,
One of the things our program I'll continue to use the example hopefully, you are beginning to see Now, using the same logic, we
will do for us is let us know if we from the documentation page to where all this is going. Let's say we will create a routine (next page,
have any missing episodes from illustrate the process. have a shopping list that has a bottom left) that will deal with our
any given series in the database. bunch of fruit in it, and, as we go missing episodes. We will call our
Here's the scenario. We have a >>> Basket = through the store, we want to routine “FindMissing” and pass it
series, we'll call it “That 80's ['apple','orange','apple','pe check what we are missing –
ar','orange','banana'] two variables. The first is an
Show”, that ran for three seasons. basically the items in the shopping integer that is set to the number of
In season 2, there were 15 >>> fruit = set(basket) list but not in our basket. We can episodes in that season and the
episodes. However, we have only start like this.
>>> fruit second is a list containing the
13 of them in our library. How do episode numbers that we have for
set(['orange','pear','apple', >>> shoppinglist =
we find which episodes are missing ['orange','apple','pear','ban that season.
'banana'])
– programmatically? ana','kiwi','grapes']
Notice that in the original list >>> basket = The routine, when you run it,
The simplest way is to use lists ['apple','kiwi','banana'] prints out [5, 8, 15], which is
that was assigned to the basket
and sets. We have already used correct. Now let's look at the code.
variable, apple and orange were >>> sl = set(shoppinglist)
lists in a number of the articles The first line creates a set called
put in twice, but, when we
over the last four years, but Sets >>> b = set(basket) EpisodesNeeded using a list of
assigned it to a set, the duplicates
are a new data type to this series, integers created using the range
were discarded. Now, to use the >>> sl-b
so we'll examine them for a while. function. We need to give the
set that we just created, we can
According to the “official set(['orange', 'pear', range function the start value and
check to see if an item of fruit (or 'grapes'])
documentation” for Python end value. We add 1 to the range
something else) is in the set. We
(docs.python.org), here is the >>> high value to give us the correct
can use the “in” operator.
definition of a set: list of values from 1 to 15.
full circle magazine #76 9 contents ^
HOWTO - PYTHON PT46
Remember the range function is my body can stand, so I’ll leave you
actually 0 based, so when we give for this month, wondering how we PYTHON SPECIAL EDITIONS:
it 16 (expected (15) + 1), the actual are going to use this in our media
list that range creates is 0 to 15. manager.
We tell the range function to start
at 1, so even though the range is 0 Have a good month and see you
to 15 which is 16 values, we want soon.
15 starting at 1.
def FindMissing(expected,have):
#===================================
# ‘expected’ is the number of episodes we should have
# ‘have’ is a list of episodes that we do have
# returns a sorted list of missing episode numbers
#===================================
EpisodesNeeded = set(range(1,expected+1))
EpisodesHave = set(have)
StillNeed = list(EpisodesNeeded - EpisodesHave)
StillNeed.sort()
print StillNeed
http://fullcirclemagazine.org/python- http://fullcirclemagazine.org/python-
FindMissing(15,[1,2,3,4,6,7,9,10,11,12,13,14]) special-edition-volume-five/ special-edition-volume-six/
to put the rough code we We will use the list to hold the # Combine path and filename to create a single variable.
presented into practice. episode numbers (hence the elist fn = join(root,file)
OriginalFilename,ext = os.path.splitext(file)
name). fl = file
We’ll modify one routine and isok,data = GetSeasonEpisode(fl)
write one routine. We’ll do the Let’s take a quick look and
modification first. In the working freshen our memory (above) about
file that you’ve been using the last what we’re doing in the existing returned to us. the files and the highest numbered
few months, find the routine before we modify any episode is the latest one available.
WalkThePath(filepath) routine. The further. Here (below) we are simply As we discussed last month, we
fourth and fifth lines should be: assigning the data passed back can then create a set that is
The first two lines here set from GetSeasonEpisode and numbered from 1 to the last
efile = things up for the walk-the-path putting them into separate episode, and convert the list to a
open('errors.log',"w") variables that we can play with. set and pull a difference. While
routine where we start at a given
for root, dirs, files in folder in the file system and Now that we know where we were, that is great in theory, there is a bit
os.walk(filepath,topdown=True recursively visit each folder below, let’s talk about where we are of a “hitch in our git-a-long” when
): going. it comes down to actual practice.
and check for files that have the
file extension of .avi, .mkv, .mp4 or We don’t actually get a nice and
In between these two lines, we We want to get the episode neat indication as to when we are
will insert the following code: .m4v. If there are any, we then
iterate through the list of those number of each file and put it into done with any particular folder.
lastroot = '' filenames. the elist list. Once we are done What we do have though, is the
with all the files within the folder knowledge that when we get done
elist = [] we are currently in, we can then with each file, the code right after
In the line above right, we call
currentshow = '' the GetSeasonEpisode routine to make the assumption that we have the “for file in [...” gets run. If we
pull the series name, season been pretty much keeping up with know the name of the last folder
currentseason = ''
number and episode number from
the filename. If everything parses if isok:
By now, you should recognize showname = data[0]
that all we’re doing here is correctly, the variable isok is set to season = data[1]
initializing variables. There are true, and the data we are looking episode = data[2]
for is placed into a list and then print("Season {0} Episode {1}".format(season,episode))
three string variables and one list.
full circle magazine #77 7 contents ^
HOWTO - PYTHON PT47
visited, and the current folder
for file in [f for f in files if f.endswith (('.avi','mkv','mp4','m4v'))]:
name, we can compare the two # Combine path and filename to create a single variable.
and, if they are different, we have if lastroot != root:
finished a folder and our episode lastroot = root
if len(elist) > 0:
list should be complete. That’s Missing(elist,max(elist),currentseason,currentshow)
what the ‘lastroot’ variable is for. elist = []
currentshow = ''
currentseason = ''
Just after the ‘for file in[‘ line is fn = join(root,file)
where we’ll put the majority of our
new code. It’s only seven lines. current show name, and the isok,data = GetSeasonEpisode(fl)
Here are the seven lines. (The current season, and we move on as if isok:
black lines are the existing lines for we did before.
currentshow = showname = data[0]
your convenience.) currentseason = season = data[1]
episode = data[2]
Next we have to change two elist.append(int(episode))
Line by line of the new code, else:
lines and add one line of code into
here is the logic: the if isok: code, a few lines down. We are done with this portion passing the episode list (eplist),
Again, right, the black lines are the
First, we check to see if the of the code. Now, all we have to do the number of episodes we should
existing code:
variable lastroot has the same is add the Missing routine. Just expect (shouldhave) which is the
value as root (the current folder after the WalkThePath routine, highest episode number in the
Here, we have just come back
name). If so, we are in the same we’ll add the following code. episode list, the season number
from the GetSeasonEpisode
folder, so we don’t run any of the (season), and the show name
routine. If we had a parsable file
code. If not, we then assign the Again, it is a very simple set of (showname).
name, we want to get the show
current folder name to the lastroot code and we pretty much went
name and season number, and add
variable. Next, we check to see if over it last month, but we’ll walk Next, we create a set that
the current episode into the list.
the episode list (elist) has any through it just in case you missed contains a list of numbers using
Notice, we are converting the
entries (len(elist) > 0). This is to it. the range built-in function, starting
episode number to an integer
make sure we weren’t in an empty with 1 and going to the value in
before we add it to the list.
directory. If we have items in the We define the function and set shouldhave + 1. We then call the
list, then we call the Missing up four parameters. We will be difference function – on this set
routine. We pass the episode list,
#----------------------------------
the highest episode number, the def Missing(eplist,shouldhave,season,showname):
current season number, and the temp = set(range(1,shouldhave+1))
name of the season, so we can ret = list(temp-set(eplist))
if len(ret) > 0:
print that out later on. The last print('Missing Episodes for {0} Season {1} - {2}'.format(showname,season,ret))
three lines clear the list, the
full circle magazine #77 8 contents ^
HOWTO - PYTHON PT47
and a converted set from the
episode list (temp-set(eplist)) – PYTHON SPECIAL EDITIONS:
and convert it back to a list. We
then check to see if there is
anything in the list – so we don’t
print a line with an empty list, and The Ubuntu Podcast covers all
if there’s anything there, we print the latest news and issues facing
it out. Ubuntu Linux users and Free
Software fans in general. The
That’s it. The one flaw in this show appeals to the newest user
logic is that by doing things this and the oldest coder. Our
way, we don’t know if there are discussions cover the
any new episodes that we don’t development of Ubuntu but http://fullcirclemagazine.org/issue-py01/ http://fullcirclemagazine.org/issue-py02/
have. aren’t overly technical. We are
lucky enough to have some
I’ve put the two routines up on great guests on the show, telling
pastebin for you if you just want to us first hand about the latest
do a quick replace into your exciting developments they are
working code. You can find it at working on, in a way that we can
http://pastebin.com/XHTRv2dQ. all understand! We also talk
about the Ubuntu community
Have a good month and we’ll and what it gets up to.
see you soon. http://fullcirclemagazine.org/python- http://fullcirclemagazine.org/python-
The show is presented by special-edition-issue-three/ special-edition-volume-four/
members of the UK’s Ubuntu
Linux community. Because it is
covered by the Ubuntu Code of
Conduct it is suitable for all.