0% found this document useful (0 votes)
24 views15 pages

Full Circle Magazine 'Programming in Python' Series. Volume 8.

Full Circle Magazine 'Programming in Python' series. Volume 8.

Uploaded by

lukyanov
Copyright
© Attribution ShareAlike (BY-SA)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views15 pages

Full Circle Magazine 'Programming in Python' Series. Volume 8.

Full Circle Magazine 'Programming in Python' series. Volume 8.

Uploaded by

lukyanov
Copyright
© Attribution ShareAlike (BY-SA)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Full Circle

THE INDEPENDENT MAGAZINE FOR THE UBUNTU LINUX COMMUNITY

PROGRAMMING SERIES SPECIAL EDITION

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.

full circle magazine


HOW-TO
Written by Greg Walters
Programming In Python: Pt 44
W e are going to take a short
detour this month from our
TVRage program to partially
form that you can drag and drop
controls onto.
good time to save our project.
Name it 'pytest1.ui'. Next, we will
put a button on our form. This will
Property Editor under geometry,
you will see something like this:

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

full circle magazine #73 8 contents ^


HOWTO - PROGRAMMING PYTHON Pt44
at 210,130), and set its The -x parameter says to
objectName property to lblDisplay. include the code to run and display
We will want to make it bigger the UI. The -o parameter says to
than what it is by default, so set its create an output file rather than
size to somewhere around 221 x just display the file in stdout. One
20. In the property editor, scroll important thing to note here. Be
down to the 'Qlabel’ section, and SURE to have everything done in
set the Horizontal alignment to QT4 Designer before you create
'AlignHCenter'. Change the text to the python file. Otherwise, it will
blank. We will set the text in be completely rewritten and you'll
code—when the btnClickMe is have to start over from scratch.
clicked. Now save the project
again. Once you've done this, you will
way to use predefined slots & have your python file. Open it up in
SLOTS & SIGNALS signals. If you press the F4 button your favorite editor.
on the keyboard, you will be in the
This next section might be a bit Edit Signals & Slots mode. (To get The file itself is only about 65
difficult to wrap your head around, out of the Edit Signals & Slots The click signal (event) is linked lines long, including comments. We
especially if you have been with us mode, press F3.) Now, left click and to the Close routine of the main had only a few controls so, it
for a long time and have dealt with hold on the Exit button, and drag window. wouldn't be very long. I'm not
the previous GUI designers. In the slightly up and to the right, off the going to show a great deal of the
other designers, we used events button onto the main form, then For the btnClickMe clicked code. You should be able to follow
that were raised when an object release the click. You will see a signal, we will do that in code. most all of the code by now.
was clicked, like a button. In QT4 dialog pop up that looks However we will be creating and
Designer, events are called Signals, something like that shown above. Save the file one more time. adding to the code in order to put
and the function that is called by Exit QT4 Designer and open a the functionality in to set the label
that signal is called a Slot. So, for This will give us an easy way to terminal. Change to the directory text.
our Exit button, we use the Click connect the clicked signal to the that you saved the file in. Now we
signal to call the Main Window form. Select the first option on the will generate a python file by using The first thing we need to do is
Close slot. Are you totally left which should be 'clicked()'. This the command line tool pyuic4. This copy the signal & slot line and
confused right now? I was when I will enable the right side of the will read the .ui file. The command modify it. Somewhere around line
first dealt with QT, but it begins to window and select the 'close()' will be: 47 should be the following code:
make sense after a while. option from the list, then click
pyuic4 -x pytest1.ui -o QtCore.QObject.connect(self.b
'OK'. You will see something that tnExit,
Fortunately, there is a very easy pytest1.py
looks like this: QtCore.SIGNAL(_fromUtf8("clic

full circle magazine #73 9 contents ^


HOWTO - PROGRAMMING PYTHON Pt44
ked()")), MainWindow.close) example, I'm sure you are
advanced enough to play with QT4
Copy that, and, right below it, Designer and get an idea of the
MY STORY QUICKIE
paste the copy. Then change it to: By Anthony Venable
power of the tool.
QtCore.QObject.connect(self.b
tnClickMe,
QtCore.SIGNAL(_fromUtf8("clic
ked()")), self.SetLabelText)
Next month, we will return
from our detour and start working
T his story begins at the beginning of 2010. I was broke at the
time so I was trying to find a free operating system. I needed
something I could run on my PCs at home. I had searched on the
on the user interface for our
Internet, but found nothing useful for a long time. But one day I
TVRage program.
This will then create the was at Barnes and Noble and I saw a magazine for Linux. (While I
signal/slot connection to our had heard of Linux before, I never thought of it as something I
As always, the code can be
routine that will set the label text. would ever be able to use.) When I asked people who I knew were
found on pastebin at
Under the retranslateUi routine computer professionals, I was told it was for people that were
http://pastebin.com/98fSasdb for
add the following code: experts, and difficult to use. I never heard anything positive about
the .ui code, and
it. I am so amazed that I hadn’t came across it sooner.
http://pastebin.com/yC30B885 for
def SetLabelText(self):
the python code.
self.lblDisplay.setText(_from
When I read the magazine I became exposed to Ubuntu 9.10 -
Utf8("That Tickles!!!")) Karmic Koala. It sounded so good, as if it was exactly what I was
See you next time.
looking for. As a result, I got very excited took it home, and to my
I got the label setText surprise had such an easy time installing it to my PC that I decided
information from the initialization to run it along with Windows XP as a dual boot system. All I did
line in the setupUi routine. was put the live CD in the drive and the instructions were step by
Greg Walters is owner of RainyDay
step you would have to be pretty slow to not get how to set
Solutions, LLC, a consulting company
Now run your code. Everything in Aurora, Colorado, and has been things up.
should work as expected. programming since 1972. He enjoys
cooking, hiking, music, and spending Since then I have been very satisfied with Ubuntu in general
time with his family. His website is
Although this is a VERY simple and I have been able to check out later versions of it such as 10.04
www.thedesignatedgeek.net.
(Maverick Meerkat) and 10.10 Lucid Lynx. I looked forward to
future versiobs for how they integrate multi-touch even more
than 10.04.

This experience just goes to show once again how I manage to


find the coolest stuff by accident.

full circle magazine #73 10 contents ^


HOW-TO
Written by Greg Walters
Programming In Python - Part 45
T his time, we are going to
rework our database program
from the previous few articles
to include another table and
modify the existing data table.
First, we will create our new table
sql = 'CREATE TABLE IF NOT EXISTS Series (
pkid INTEGER PRIMARY KEY AUTOINCREMENT,
SeriesName TEXT,
SeriesID TEXT,
(parts 41, 42 and 43). Then, over called Series. It will hold all the Seasons TEXT,
the next few articles, we will use information about the tv series we StartDate TEXT,
have on our system. The new table Ended TEXT,
QT to create the user interface. OriginCountry TEXT,
will include the following fields: Status TEXT,
First, let's look at how the • Pkid Classification TEXT,
Summary TEXT,
existing application works. Here's a • Series Name Genres TEXT,
gross overview: • TvRage Series ID Runtime TEXT,
• Create a connection to the • Number of seasons Network TEXT,
AirDay TEXT,
database – which creates the • Start Date AirTime TEXT,
database if needed. • Ended Flag Path TEXT);'
• Country of origin cursor.execute(sql)
• Create a cursor to the database.
• Create the table if it doesn't • Status of the series (ended,
current, etc) The SQL statement (“sql = …”) with
exist.
• Classification (scripted, "reality", should be all on one line, but is
• Assign the video folder(s) to a
etc) broken out here for ease of your sqlquery = 'SELECT
variable. count(pkid) as rowcount from
• Summary of the series plot understanding. We’ll leave the
• Walk through the folder(s) series where seriesName =
• Genres modification of the existing table "%s";' % showname
looking for video files.
• Runtime in minutes for later.
• Get the filename, seriesname,
season number, episode number. • Network This (to refresh your memory)
• Day of the week it airs Now we have to modify our will check to see if we have already
• Check to see if the episode exists
• Time of day it airs WalkThePath routine to save the put the series into the table. Now
in the database.
• Path to the series series name and path into the find the two lines that say:
• If it is not there, add it to the
series table.
database with a “-1” as the TvRage
We can use the existing sql = 'INSERT INTO TvShows
ID. (Series,RootPath,Filename,Sea
MakeDataBase routine to create Replace the line that says
• Then walk through the database son,Episode,tvrageid) VALUES
getting show id and status if our new table. Before the existing (?,?,?,?,?,?)'
sqlquery = 'SELECT
needed, and update database. code, add the code shown above count(pkid) as rowcount from cursor.execute(sql,(showname,
right. TvShows where Filename = root,fl,season,episode,-1))
"%s";' % fl
We will redesign the database
full circle magazine #75 8 contents ^
HOWTO - PYTHON PT45
and replace them with seriesname = x[0]
def GetShowData(seriesname,id,pkid):
searchname = tr = TvRage()
sql = 'INSERT INTO Series string.capwords(x[0]," ")
(SeriesName,Path,SeriesID) idcursor = connection.cursor()
VALUES (?,?,?)' dict = tr.GetShowInfo(id)
with
cursor.execute(sql,(showname,
root,-1))
pkid = x[0]
seasons = dict['Seasons']
This will insert the series name seriesname = x[1] startdate = dict['StartDate']
ended = dict['Ended']
(showname), path to the series, searchname = origincountry = dict['Country']
and a “-1” as the TvRage id. We use string.capwords(x[1]," ") status = dict['Status']
the “-1” as a flag to know that we classification = dict['Classification']
summary = dict['Summary']
need the series information from We will use the pkID for the
TvRage. update statement. Next we have
to modify the call to the GetShowData routine (top). We’ll
def
Next we will rework the UpdateDatabase routine to include UpdateDatabase(seriesname,id) grab the information from TvRage
WalkTheDatabase routine to pull the pkid. Change the line :
and insert it into the Series table.
those series that we don’t have any
UpdateDatabase(seriesname,id)
information for (SeriesID = -1) and to
Just as a memory refresher, we
update that record.
to def are creating an instance of the
UpdateDatabase(seriesname,id, TvRage routines and creating a
Change the query string from UpdateDatabase(seriesname,id, pkid):
pkid) dictionary that holds the
sqlstring = "SELECT DISTINCT information on our series. We will
series FROM TvShows WHERE Next, we need to change the then create variables to hold the
and change the line
tvrageid = -1" query string from data for updating the table
GetShowStatus(seriesname,id) (above).
to sqlstring = 'UPDATE tvshows
SET tvrageid = ' + id + '
to WHERE series = "' + Remember that Genres come in
sqlstring = "SELECT seriesname + '"'
pkid,SeriesName FROM Series GetShowData(seriesname,id,pki as subelements and contain one or
WHERE SeriesID = -1" d) many genre listings. Luckily when
to we coded the TvRage routines, we
This will create a result-set that Which will be a new routine we created a string that holds all the
sqlstring = 'UPDATE Series
we can then use to query TvRage will create in a moment. SET SeriesID = ' + id + ' genres, no matter how many are
for each series. Now find/replace WHERE pkID = %d' % pkid returned, so we can just use the
the following two lines Next, change the definition of genre string:
the UpdateDatabase routine from Now we need to create the genres = dict['Genres']
full circle magazine #75 9 contents ^
HOWTO - PYTHON PT45
runtime = dict['Runtime'] database (below).
network = dict['Network']
That is all for this time. Next
airday = dict['Airday'] time, we’ll continue as I laid out at
airtime = dict['Airtime'] the beginning of the article. Until
next time, Enjoy. The Ubuntu Podcast covers all
Finally, we create the query the latest news and issues facing
string to do the update (bottom). Ubuntu Linux users and Free
Again, this should all be on one Software fans in general. The
line, but I’ve broken it up here to show appeals to the newest user
make it easy to understand. and the oldest coder. Our
discussions cover the
The {number} portion (just to development of Ubuntu but
remind you) is similar to the “%s” aren’t overly technical. We are
formatting option. This creates our lucky enough to have some
query string replacing the great guests on the show, telling
{number} with the actual data we us first hand about the latest
want. Since we’ve already defined Greg Walters is owner of RainyDay exciting developments they are
Solutions, LLC, a consulting company working on, in a way that we can
all of these fields as text, we want in Aurora, Colorado, and has been
to use the double quotes to programming since 1972. He enjoys
all understand! We also talk
enclose the data being added. cooking, hiking, music, and spending about the Ubuntu community
time with his family. His website is and what it gets up to.
www.thedesignatedgeek.net.
And lastly, we write to the
The show is presented by
try: members of the UK’s Ubuntu
idcursor.execute(sqlstring) Linux community. Because it is
except: covered by the Ubuntu Code of
print "Error Adding Series Information"
Conduct it is suitable for all.

The show is broadcast live every


sqlstring = 'Update Series SET Seasons = "{0}", StartDate = "{1}", Ended = "{2}", fortnight on a Tuesday evening
OriginCountry = "{3}", Status = "{4}", Classification = "{5}",
Summary = "{6}", Genres = "{7}", Runtime = "{8}", Network = "{9}", (British time) and is available for
AirDay = "{10}",AirTime = "{11}" download the following day.
WHERE pkID ={12}'.format(seasons,startdate,ended,
origincountry,status,classification,summary,
genres,runtime,network,airday,airtime,pkid) podcast.ubuntu-uk.org

full circle magazine #75 10 contents ^


HOW-TO
Written by Greg Walters
Programming In Python - Part 46
U sually, my articles are fairly
long. However, due to some
“A set is an unorderedcollection
with no duplicate elements. Basic
>>> 'orange' in fruit

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.

Next we create a set from the


list that is passed into our routine,
which contains the episode
numbers that we actually have. http://fullcirclemagazine.org/issue-py01/ http://fullcirclemagazine.org/issue-py02/

Now we can create a list using


the set difference operator on the
two sets. We do this so we can sort
it with the list.sort() method. You
Greg Walters is owner of RainyDay
can certainly return the list if you Solutions, LLC, a consulting company
wish, but in this iteration of the in Aurora, Colorado, and has been
routine, we’ll just print it out. programming since 1972. He enjoys
cooking, hiking, music, and spending
time with his family. His website is
Well, that’s all the time in the www.thedesignatedgeek.net. http://fullcirclemagazine.org/python- http://fullcirclemagazine.org/python-
chair in front of the computer that special-edition-issue-three/ special-edition-volume-four/

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/

full circle magazine #76 10 contents ^


HOW-TO
Written by Greg Walters
Programming In Python - Part 47
L ast month, we discussed using
sets to show us missing
episode numbers. Now’s the time
for root, dirs, files in os.walk(filepath,topdown=True):
for file in [f for f in files if f.endswith (('.avi','mkv','mp4','m4v'))]:

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.

The show is broadcast live every


Greg Walters is owner of RainyDay
fortnight on a Tuesday evening
Solutions, LLC, a consulting company
in Aurora, Colorado, and has been (British time) and is available for
programming since 1972. He enjoys download the following day.
cooking, hiking, music, and spending http://fullcirclemagazine.org/python-
http://fullcirclemagazine.org/python-
time with his family. His website is special-edition-volume-six/
podcast.ubuntu-uk.org special-edition-volume-five/
www.thedesignatedgeek.net.

full circle magazine #77 9 contents ^


HOW-TO
Written by Greg Walters
Programming In Python - Part 48
W elcome back. It’s hard to this: to produce an output with a total >>> info =
{"FName":"Fred","LName":"Fark
imagine that it’s been 4 width of five and three decimal el","City":"Denver"}
String a is Hello Python places. Notice that the decimal
years since I began this series. I
thought that I’d shelve the media point takes up one of the places of >>> print('Greetings
%(FName)s %(LName)s of
manager project for a bit and PYTHON 2.X the total width. %(City)s!' % info)
return to some basics of Python
One other thing that you might Greetings Fred Farkel of
programming. Of course you remember the Denver!
simple syntax for the print function not realize is that you can use the
This month, I’ll revisit the print in 2.x uses the variable substitution keys of a dictionary as part of the
The following table shows the
command. It’s one of the most of %s or %d for simple strings or format command.
various possible substitution keys
used (at least in my programming) decimals. But many other and their meanings.
function that never seems to get formatting options are available.
the detail it deserves. There is a lot For example, if you need to format
of things you can do with it outside a number with leading zeros, you
of the standard ‘%s %d’. can do it this way:

Since the print function syntax >>> print("Your value is


%03d" % 4)
is different between Python 2.x Your value is 004
and 3.x, we’ll look at them
separately. Remember, however, In this case, we use the ‘%03d’
you can use the 3.x syntax in formatting command to say,
Python 2.7. Most everything I “Display the number to a width of
present this month will be done 3 characters and if needed, left pad
from the interactive shell. You can with zeros”.
follow along as we go. The code
will look like this: >>> pi = 3.14159

>>> a = "Hello Python" >>> print('PI = %5.3f.' % pi)

>>> print("String a is %s" % PI = 3.142.


a)
Here we use the float
and the output will be in bold, like formatting option. The ‘%5.3f’ says

full circle magazine #78 9 contents ^


HOWTO - PYTHON PT48
This version of Python is something like this:
PYTHON 3.X 3.3.2
>>> d =
With Python 3.x, we have many As they say on the TV ads, “BUT datetime.datetime(2013,10,9,1
0,45,1)
more options (remember we can WAIT… THERE’S MORE”. If we
use these in Python 2.7) when it wanted to do some inline >>> The Ubuntu Podcast covers all
comes to the print function. formatting, we have the following print("{:%m/%d/%y}".format(d)
) the latest news and issues facing
options. 10/09/13 Ubuntu Linux users and Free
To refresh your memory, here’s Software fans in general. The
:<x Left align with a width >>>
a simple example of the 3.x print of x print("{:%H:%M:%S}".format(d) show appeals to the newest user
function. :>x Right align with a width ) and the oldest coder. Our
of x 10:45:01
:^x Center align with a width discussions cover the
>>> print('{0}
{1}'.format("Hello","Python") of x development of Ubuntu but
Printing thousands separator
) aren’t overly technical. We are
Hello Python using a comma (or any other
Here is an example: lucky enough to have some
character) is simple.
>>> print("Python is {0} great guests on the show, telling
cool!".format("WAY")) >>> us first hand about the latest
Python is WAY cool! print("|{:<20}|".format("Left >>> print("This is a big
")) number exciting developments they are
|Left | {:,}".format(7219219281)) working on, in a way that we can
The replacement fields are >>> This is a big number
print("|{:>20}|".format("Righ 7,219,219,281 all understand! We also talk
enclosed within curly brackets “{“ about the Ubuntu community
t"))
“}”. Anything outside of these are | Right| and what it gets up to.
Well, that should give you
considered a literal and will be >>>
print("|{:^20}|".format("Cent enough food for thought for this
printed as is. In the first example, The show is presented by
er")) month. I’ll see you at the start of
we have numbered the | Center | members of the UK’s Ubuntu
the 5th year.
replacement fields 0 and 1. That Linux community. Because it is
tells Python to take the first (0) You can even specify a fill covered by the Ubuntu Code of
value and put it into the field {0} character along with the Conduct it is suitable for all.
and so on. However, you don’t have justification/width.
to use any numbers at all. Using The show is broadcast live every
this option causes the first value to >>> Greg Walters is owner of RainyDay
fortnight on a Tuesday evening
be places in the first set of print("{:*>10}".format(321.40 Solutions, LLC, a consulting company
)) in Aurora, Colorado, and has been (British time) and is available for
brackets and so on. *****321.4 programming since 1972. He enjoys download the following day.
cooking, hiking, music, and spending
>>> print("This version of {} time with his family. His website is
is If you need to format a podcast.ubuntu-uk.org
date/time output, you can do www.thedesignatedgeek.net.
{}".format("Python","3.3.2"))
full circle magazine #78 10 contents ^

You might also like