Está en la página 1de 132
Python The Complete Manual The essential handbook for Python users acaeam = bexdwt =* jist 2a Un # along with ree a ] xy Pp — Welcome to Python The Complete Manual Python is a versatile language and its rise in popularity is, certainly no surprise. Its similarity to everyday language has made it a perfect companion for the Raspberry Pi, which is often a first step into practical programming, But dent be fooled by its beginner-friencly credentials - Python has plenty of more advanced functions. in this new edition, you will learn how to program in Python, discover amazing projects to improve your understanding, and find ways to use Python to enhance your experience of computing, Youll also create fun projects including programming a Space invaders clone and teaching your Raspberry Pi to multi-task. Let's get coding! @ Python The Complete Manual Editorial Editor Dan Poel Desiane” Steve Dacombe senior art altor Andy Downes Photography _Allcopyrights and teacemarea are racagnied and respactec Advertising Media packs sreavallabie on request ‘dare doveg@uturenetcom International Head of Print Licensing Rachel Shaw Teensingg@tuturenetcom Circulation oad of Newstada Tim Mathers Production Heodtof Prosustion Mark Constance Proctction Project Manager Clare Seatt tong Production Manager Jeanne Crosby Distal Editons Controle Jason Hudson reduction Mangers Keely Miler, Nola Cokely Vivienne Calvert Fran Twentyman, Management Chet Content Ofcer Aaron Asad Commarea Finance Drecrar Dan Jeteham Head of ft & Design Greg Whitaker Printed by Wiliam Gibbons, 26 Pianetary Ross ville West Midland WATS Xt Distributed by Marketfore,S Chutchil Place, Canary Wharf Landon E12 SHU preinartetonce cou Tel C203 787 9001 Python The Complete Manual Eighth Ealtion Recycled 8 Masterclass Discover the basics of Python e Get started © Pyttin Introducing Python Create with Python Use Python with Pi 26 Makewebapps 80 Tictactoe with Kivy 100 Using Python on Pi Master this starter project, Programa simple game Optimise yourcode 86 Makea Pong clone 106 Use Python in Minecraft Enhance your game skills Produce fantastic creations 110 Handle multiple task Learn to multi-task with gi yout Raspberry i 32 Buildanapp for Android i ‘Take your appson the move id ea arene 40 50 Python tips 88 Programa Space Use Python-VRZero Aselection of handy tips Invaders clone 120 Findandcheck Have fun with Pivaders your phone Work with Python 94 Space Invaders done 2 Discover and log Continue making Pivaders Bluetooth devices 50 Replace your shell Say goodbye to Bash 58 Scientificcomputing Discover NumPy’s power 64 Python for system admins How to tweak yoursettings 72. Scrape Wikipedia Start using Beautiful Soup Python is a great programming language for both beginners and experts It is designed with code readability in mind, making it an excellent choice for beginners who are stil getting used to various programming concepts. ‘The language is popular and has plenty of libraries available, allowing programmers to get a lot done with relatively little code. You can make all kinds of applications in Python: you could use the Pygame framework to write simple 2D games, you could use the GTK lioraries to create a windowed application, or you could try something a little more ambitious like an app such as creating one using Python's Bluetooth and Input libraries to capture the input from a USB keyboard and relay the input events to an Android phone. For this tutorial we're going to be using Python 2x since that is the version that is most likely to be installed on your Linux distribution, 4 In the following tutorials, you'll leam how to create popular games using € Python programming, Welll also show you how to add sound and Al to these games Get started with Python Getting started Hello World Lets get stuck in, and what better way than with the programmer's best ffiend, the ‘Hello World’ application! Start by opening a terminal Its current working directory will be your home directory. I's probably a good idea to make a directory for the files that welll be creating in this tutorial,rather than having them loose in your home directory. You can cteate a directory called Python using the command mkdir Python. Youll then want to change into that directory using the command cd Python. The next step is to create an empty file using the command ‘touch’ followed by the filename. Qur expert used the command touch hello_worldipy. The final and most important part of setting up the file is making it executable. This allows us to run code inside the hello_ world py file. We do this with the command chmod +x hello_world. py. Now that we have our file set up, we can go ahead and open it up in nano, oralternatively any text editor of your choice. Gedit is a great editor with syntax highlighting support that should be available on any distribution, You'll be able to install it using your package manager if you don't have it already. Bf Cliametiam-taptop ~Js mkdir Python Llian@liam-laptop ~JS ed Python/ Bf Ciiametiam-taptop Pythoris touch hello_world.py I Liianetian-laptop Pythons chmod +x hello_world.py I (iiametiamtaptop Python]$ nano hello_world.py Our Hello World program is very simple, tonly needs two lines. The first line begins with a ‘shebang’ (the symbol #!- also known Get started with Python {asa hashbang) followed by the path to the Python interpreter. The program loader uses this line to work out what the rest ofthe lines need to be interpreted with. youre running this in an IDE like IDLE, you don't necessarily need to do this. “The code that is actually read by the Python interpreter is only a single line, Were passing the value Hello World to the print function by placing it in brackets immediately after weve called the print function, Hello World is enclosed in quotation marks to indicate that itis a iteral value end should not be interpreted as source code. As we would expect, the print function in Python prints any value that gets passed to tfrom the console, You can save the changes you've just made to the file in nano using the key combination Ctrl+0, followed by Enter. Use Cirl+X to exitnano. I #1vusrvbinvenv python2 I print¢Hello World”) You can tun the Hello World program by prefixing its filename with / in this case you'd type: Jhello_worldpy. Bf criametian-laptop Python]s ./nello_world.py H tet10 Worid Variables and data types A variable is a name in source code that is associated with an area in memory that you can use to store data, which is then called upon throughout the code. The data can be one of many types, including: eon Ce Set ere Cee eMart Storesa collection of characters emer) String Au “A variable is associated with an area in memory that you can use to store data” Getting started Getting started rs Get started with Python ‘As well as these main data types, there are sequence types technically, a string is sequence type but s so commonly used we've classed it as a main data type} rd Contains a collection of da brary Contains a collection immutable data in a specific Cres ‘tuple would be used for something like a co-ordinate, containing anxand y value stored as a single variable, whereas a lst is typically used to store larger collections. The data stored in a tuple is immutable because you aren't able to change values of individual elements in a tuple, However, you can do so ina list. Iwill aso be useful to know about Pythons dictionary type. A dictionary is a mapped data type. It stores data in key-value pairs. This means that you access values stored in the dictionary using that value's corresponding key, which is different to how you would do it with a list. Ina list, you would access an element of the list using that ‘element's index (a number representing where the element is placed in the list). Lets work on a program we can use to demonstrate how to use variables and different data types. I's worth noting at this point that ‘you don't always have to specify data types in Python. Feel free to create this file in any editor you like, Everything will work just fine as long as you remember to make the file executable. We're going to call cours variablespy. Interpreted vs compiled languages race] raat cel ani ty Te rare ene oe ea Full code listing The following line creates, an integer variable called hello_int with the # value of 21, Notice how itdoesnit need to goin {quotation marks The same principals true of Boolean values We create a tuple the following way ‘And alist in this way You could also create the samelistin the following way Get started with Python Getting started al/usr/bin/env python2 #We create. variable by writing the name of the Variable we want followed# by an equals sign, hich is followed by the value we want to store in the# variable. For example, the following line creates a variable called hello_str, containing the string Hello World hello_str = “Hello World” hello_int = 21 hello_bool = True hello_tuple = (21, 32) hello_list = ["Hello,”, “this”, “is”, “a”, List") # This listnow contains 5 strings. Notice that there are no spacest between these strings sof you were to join them up so make a sentence # yould have to add a space between each element. hello_list = list) hello_list.append(“Hello,”) hello_list.append(“this”) hello_List.append(“is") hello_list.append(“a”) holo_list.append(“List Bo r 2 of the list type to add elements to the with strings you know of in any warning ¢ Getting started Get started with Python We might as well as wel are using the same variable name as the create a dictionary previous lst. while we're ati Notice how we've hello_dict = ( “first_name” : “Liam”, aligned the colons “last_name” below to make the “Fraser”, code “eye_colour” : “Blue” } # Let's access some elements inside our collections We'll start by changing the value Of the last string in ourhello_list and add an exclamation markto the end, The'list” string is the 5th element # in the list. However, indexes in Python ate zero-based, which means the # first element has an index of 0 Notice that there will now be two exclamation marks print(hello_list(4]) hello_list(4] += “! cee # The above line is the same as eee the element hello_listL#] = hello_listL4] + “1” print(hello_listt4]) Remember that tuples are [ print(str(hello_tuple[0))) immutable, +We can't change the value of those elements although we like we just did with thelist can access the ‘Notice the use of the str function above to elements of them explicitly convert the integer Ike so # value inside the tuple toa string before printing it Lets create a sentence using the detain our print(hello_dict("first_name"] +°" + hello_ hello_dict dlict("last_name"] +" has + — hello_dictt’eye colour'] +" eyes”) Amuch tidier way of doing this would betouse Python's print(‘{0} (1) has 2} eyes"formatihello_ siring formatter dict(*first_name’], a hello_dictl"Iast_name"] et hello_dictl'eye_colour’)) Get started with Python Getting started Indentation in detail ection Mu ateec meanest nelle Teens the level ofindentation indentation i Control structures In programming, a control structure is any kind of statement that can change the path that the code execution takes. For example, a control structure that decided to end the program ifa number was less than 5 would look something like this: #1/usr/bin/env python? import sys # Used for the sys.exit function int_condition = 5 if int_condition < 6: sys.exit(“int_condition must be >= 6") else print(“int_condition was >= 6 - continuing”) The path that the code takes will depend on the value of the integer int_concition. The code in the ‘if block willonly be ‘executed if the condition is true. The import statement is used to load the Python system lbrary;the latter provides the ext function, allowing you to exit the program, printing an error message. Notice that indentation (in this case four spaces per indent) is used to indicate =a which statement a block of code belongs to. 'f statements are probably the most commonly used control structures, Other control “The path the code takes will depend on the value of the integer int_condition” Getting started Get started with Python structures include: the following items, which you should be aware of when using Python: + For statements, which allow you to iterate over items in collections, or to repeat a piece of code again a certain number oftimes; + While statements, a loop that continues while the condition istrue, We're going to write a program that accepts user input from the userto demonstrate how control structures work. Wete caling ft constructpy. The ‘for loop is using a local copy of the current value, which means any changes inside the loop won't make any changes affecting the list. On the other hand however, the ‘while’ loop is directly accessing elements in the lis, so you could change the list there should you want to do so, Wwe will tak about variable scope in some more detail ater on in the artice. The output from the above program is as follows: [Liaméliam-laptop Python]s ./ construct.py How many integers? acd You must enter an integer [liameliam-laptop Python]s ./ construct.py How many integers? 3 Please enter integer 1: t You must enter an integer Please enter integer 1: 5 Please enter integer 2: 2 Please enter integer 3: 6 Using a for loop 5 2 6 Using a while loop 5 2 6 “The ‘for’ loop uses a local copy, so changes in the loop won't affect the list” Get started with Python Getting started Full code listing #1/ust/bin/env python2 # We're going to write a program that will ask the User to input an arbitrary # number of integers, store them in acollection, and then demonstrate how the Thenumber of # collection would be used with various control integers we want in the lst structures. import sys # Used for the sys.exit function target_int = raw_input(“How many integers? “) # By now, the variable target_int contains a string representation of # whatever the user typed. We need to try and convert that to an integer but # be ready to # deal with the error ifits not. Otherwise the program will # crash, try: Alistto store the ‘target_int = int(target_int) integers ‘except ValueError: sys.exit(“You must enter an integer”) —L ints = List These are used ‘to keep track of how many integers we currently have Getting started Get started with Python Ifthe above succeeds then isint willbe set totue:isint By now, the user has given uporwe have alist filed with integers, We can loop through these in a couple of ways. The frst iswith aforloop # Keep asking for an integer until we have the required number while count < target_int: new_int = raw_input(“Please enter integer {0}: “.format(count + 1)) isint = False = int(new.int) except: print¢"You must enter an integer") # Only carry on if we havean integer. Ifnot, ‘well Joop again # Notice below lus = The single equals isan # assignment operator whereas the double ‘equals isa comparison operator which is different from if isint == True: # Add the integer to the collection ints.append(new_int) 4 Increment the count by 1 count += 1 print("Using a for loop”) for value in ints: print(str(value)) #Orwith a while loop: print(‘Using a while loop” We already have the total above, but knowing Get started with Python Getting started the len function is very f useful total = len(ints) count = 0 while count < total: print(str(ints{count))) count += 1 More about a Python list ython lis imilar to we recommend th y store data Functions and variable scope Functions are used in programming to break processes down into smaller chunks. This often makes code much easier to read. Functions can also be reusable if designed in a certain way. Functions can have variables passed to them. Variables in Python are always passed by value, which means that a copy of the variable is passed to the function that is only valid in the scope of the function. Any. changes made to the original variable inside the function will be discarded, However, functions can also return values, so this isn’t an issue. Functions are defined with the keyword def followed by the name of the function. Any variables that can be passed through are put in brackets following the function's name. Multiple variables are separated by commas. The names given to the variables in these L brackets are the ones that they will have in the scope of the function, regardless of what the variable that's passed to the function is called, SS Let see this in action. The output from the program opposite is as follows: “Functions are defined with the keyword def then the name of the function” Getting started Get started with Python We ate now ourtsice of the scope of the modify stiing function, as we have reduced the level oF entation 1 L he test string won't be changed in this code rf However, we ancall the function like this ‘#Vust/bin/env python? # Below is a function called modify_ string, which accepts a variable # that willbe called original in the scope of the function. Anything # indented with 4 spaces Under the function definition i in the f scope. def modify_string(original): original += “ that has been modified.” # Atthe moment, only the local copy of this string has been modified def modify_string_return(original): original += * that has been modified.” # However, we can return our local copy to the ‘aller. The functions ends as soon as the return statement is used, regardless of where it # isin the function, return original test_string = “This is a test string” modify_string(test_string) print(test_string) test_string = modify_string_ return(test_string) print(test_string) #The function's return value is stored in the variable test string, # overwriting the original and therefore changing the value that is # printed, {llameliam-laptop Python]$ /functions_and_ scope py This isa test string This isa test string that has been modified. Scope is an important thing to get the hang of otherwise it can get you into some bad habits. Let's write @ quick program to demonstrate this ts going to have a Boolean variable called cont, which will decide ifa number will be assigned to a variable in an if statement. However, the variable hasn't been defined anywhere apart from in the scope of the ifstatement. Well finish off by trying to print the variable. Get started with Python ‘l/usr/bin/env python2 cont = False ifcont var = 1234 printivar) In the section of code above, Python will convert the integer to a string before printing it. However, it’s aways a good idea to explicitly convert things to strings — especially when it comes to concatenating strings together Ifyou try to use the + operator on a string and an integer, there will be an error because itS not explicitly clear what needs to happen. The + operator would usually add two integers together Having said thet, Python's string formatter that we demonstrated earlier is a cleaner way of doing that. Can you see the problem? Var has only been defined in the scope of the ifstatemeent. This means that we get a very nasty error when we try to access var. Wan Traceback (mast recent call last: File"/scope.py’ line 8, in print var Namefrror: name'var’ isnot defined laptop Python|s /scope,py if contis set to True, then the variable will be created and we can ‘access it ust fine, However this sa bad way to do things. The correct way is to intialise the variable outside of the scope of the ifstatement. ‘#l/usr/bin/eny python2 cont = False var=0 ifcont var = 1234 ifvari=0 print(var) Getting started Getting started Get started with Python The variable var is defined in a wider scope than the ifstatement, and can still be accessed by the if staternent. Any changes made to var inside the if statement are changing the variable defined in the larger scope. This example doesrit really do anything useful apart from illustrate the potential problem, but the wor se scenario has gone frorn the program crashing to printing a zero, Even that doesn't happen because we've added an extra construct to test the value of var before printing it “Google, or any other search engine, is very helpful if you are stuck with anything, or have an error message you can't work out how to fix” Comparison fo elaroky aeons cient ec ee anurans [<[acwienten ote Get started with Python = Getting started Coding style It’s worth taking a little time to talk about coding style. I's simple to write tidy code. The key is consistency. For example, you should always. name your variables in the same manner. it doesn’t matter if you want To use camelCase or use underscores as we have. One crucial thing is to use self-documenting identifiers for variables. You shouldn't have ‘to guess what a variable does. The other thing that goes with this is to ‘always comment your code. This will help anyone else who reads your ‘code, and yourself in the future. it's also useful to put a brief summary at the top of a code file describing what the application does, or a part ‘ofthe application ifit’s made up of multiple files. Summary This article should have introduced you to the basics of programming in Python. Hopefully you are getting used to the syntax, indentation and general look and feel ofa Python program. The next step is to learn how to come up with a problem that you want to solve, and break it down into small steps that you can implement in a programming language, Google, or any other search engine, is very helpful Ifyou are stuck with anything, or have an error message you can't work out how to fix, stick it into Google and you should be a lot closer to solving your problem. For example, if we Google ‘play mp3 file with python, the fist link takes us to a Stack Overflow thread with a bunch of useful replies. Dont be afraid to get stuck in — the real fun cof programming is solving problems one manageable chunk at a time. Introducing Python Python essentials Lay the foundations and build your knowledge Now that you've taken the first steps with Python, it’s time seodorerel AMVC aoa ode seers he ul esata MMM eters storucicke it} systems (p.32) and the worldwide web (p.26). These easy-to- follow tutorials will help you to cement the Python language that you've learned, while developing a skill that is very helpful in the current technology market. We'll finish up by giving you Ere eu eR Mee S og as es} ability in no time. Introducing Python What you'll need... Python 2.7: releses7 Django version 1.4: Make web apps with Python Make web apps with Python ython pro’ plications, in us it to bul Jes quick anc judi a feature Python is known for its simplicity and capabilities. At this point itis, so advanced that there is nothing you cannot do with Python, and conquering the web is one of the possibilities. When you are using Python for web development you get access to a huge catalogue of modules and community support ~ make the most of them, Web development in Python can be done in many different ways, right from using the plain old CGI modules to utilising fully groomed web frameworks. Using the latter is the most populer method of building web applications with Python, since it allows you to build applications without worrying about all that low-level implementation stuff There are many web frameworks available for Python, such as Django, TurboGears and Web2Py, For this tutorial we will be using our current preferred option, Django. The Django Project portable and can be integrated with magazine issue tracker other Django sites with very ite effort. IE's django-admin.py startproject ludIssueTracker Osten fle is used tocreate new Django projects Lets crete one for our issue tracker project here. Ih Django, a project represents the site andits settings, An application, on the other hand, represents a specific feature ofthe site ike blogging or tagging, The benefit of this approach s that your Django application becomes A project directory willbe created, This will also act as the rootof your development web server that comes with Django, Under the project directory you wil find the following items managepy: Python script to work with your project. ludissustracker: A python package directory with _init__py ile) for your project. This package is the one Containing your project’ settings and configuration data ludissueTracker/settings.py: This file contains all the configuration options forthe project, ludissucTracker/us py: This fle contains various URL mappings. ‘wsgi.py: An entry-point for WSG- Compatible web servers to serve your project. Only useful when you are deploying your project. For this tutorial we won't be needing it Configuring the Django project 02 Before we start working ‘on the application, lets configure the Django project a per our requirements. EnitludissueTracker/settings py 5 follows (only parts requiting modification are shown Database Settings: We wil be Using SOL ite3 2s our database system here. NOTE: Red text indicates new code or Updated code. ‘default’: { I “ENGINE? “diango.db.backends. sqlites’, ‘NAME’: ‘udsite. db3, Path settings Django requites an absolute path fordirectory settings But we want tobe able to passin the lative directory references. In order to do that ‘we will add a helper Python function. Insert the folowing code atthe top ofthe settings file import os I def getabspatheen: return 08.path.joingos. path.abspath(os.path. Make web apps with Python dirname(_file_)), *%) Now undate the path options: Bl eode BE TevPLaTe_oirs = ¢ IE gctabspath(‘templates’) BE mepta_roor = getabspath(‘media’) B epra_ur. = ‘/medias’ Now we will need to enable the admin interface for our Django site. This is aneat feature of Django which allows automatic creation of ‘an admin interface ofthe ste based on the data model, Theadrin interface can be used to add and manage content for a Django site Uncomment the folowing ine: BE INSTALLED_APPS = ( “¢jango.contrib.auth’, “django.contrib. contenttypes', ‘django.contrib.sessions’, ‘django.contrib.sites’, ‘django.contrib.messages’, ‘django.contrib. staticfiles’, HB ‘django.contrib.admin’, EB # ‘django.contrib, Creating ludissues app 0: In this step we will create the primary app for ours called ludissues. To do that, we will use the managepy script: Is python manage.py startapp “When you are using Python for web Introducing Python ludissues ‘We will need to enable this app in the config le as welt BE INSTALLED_apps = ( BH ‘django.contrib.admin’, TH studissues’, > Creating the data model Thisis the part where we 04 iinet move {or our app. Please see the inline comments to understand what is happening here. From django.db import modes: I # We are importing the user authentication module so that wo use the built I # in authentication model in this app I from cjango.contrib.auth. models import User I # We would also create an ‘admin interface for our app from django.contrib import ‘admin 4A Tuple to hold the multi choice char fields. I # First represents the field name the second one repersents the display nane ISSUE_STATUS_CHOICES = ( (new, ‘New’, accepted’, Accepted’ (reviewed, Reviewed"), Cstarted’,’Started’), (closed! "Closed, development you get access to a huge catalogue of modules and support" Introducing Python [class Issue(nodels.Model): Be # onner will be a foreign key to the User model which is already built in Django owner = models.Foreignke y(User,nul1=True,blank=True) HB # muttichoice with defaulting to “new" status = models. CharFieLd(rax_ length=25,choices=ISSUE_ STATUS CHOICES default='new') summary = models. TextField # date time Field which will be set to the date time when the record is created ‘opened_on = models. DateTimeField‘date opened’, auto_now_add=True) mnodified_on = models. DateTimeField(‘date modified’, auito_now=True) def name(self): return self.summary. split(“\n’,1)[0] Il Adnin front end for the app. ve are also configuring sone of the IP buitt in attributes for the admin interface on I how to display the List, how it will be sorted Pb wit are the search fields etc. class IssueAdmin(admin. Model): date_hierarchy = ‘opened’ list_filter = (‘status’,’owner’) ist display ame’,’status’,'owner’,'modifii ‘ed_on’) search_fields = (idescrintion,’status'] I & register our site with the Django adinin interface adnin.site. Make web apps with Python register(Issue,Issuednin) Tohave the created data model reflected in the database, run the following command: $ python manage.py syncdb Youll be also asked to createa superuser for it You just installed Django’s auth system, which means you don’t have any superusers defined Would you like to create one now? (yes/no): yes Enabling the admin site Ob meneseesteey enabled, but we needto enable itin the utspy fle — this contains the regax-based URL mapping fiom ‘mode! to view. Update the urlspy fle asfollows I from django.conf.urls import patterns, include, url I fron django.contrib import admin adinin.autediscover HI uripatterns = patterns(”, url@r'*adnin/*, §nclude(adnin.site.url9), d Starting the Django web server Django includes a builtin web server which is very handy to debug and test Dango applications. Let's startit to see how ur admin interface works. To start the web server: Is python manage.py runserver Ifyou do not have any errors in your code, the server should be available on port 8000. To launch the admin interface, navigate your browser t0 bnttp:Mlocalhost80o/admin, ‘You willbe asked to log in here. Enter the username and password that you created while you were syncing the database, ‘After logging in, you will notice that allthe appsinstaled in your project are avaliable here. We are only interested in the Auth and Ludissues app. You can clckthe +Add to adda record, Cick the Add button next to Users and add a few users to the site, ‘Once you have the uses inside the system, you can now add a few issues to the system, owner rmeeza allen danwest Summary: ee Click the Ad loutton next to Issues. Here you wil notice that you can enter (Quiner, Status and Summary forthe issue, But what about the opened_on and mocified_on field that we “It’s great that the owner field is automatically populated with details of the users inside the site” Make web apps with Python Introducing Python Recent Actions Somes badd Change | My Actions Users Add Change None avalable Issues Add 7Change Sites Add ZCharge Select issue to change rom ey ——— 2013 feonaey) Forany 16 Fear 20 yams 1 cl tor as one meth arr sey Sard samtiter fa 200, 14am defined while modeling the app? They are not here because they are not supposed to be entered bythe user,opened_on wil automatically set tothe date time itis created and modified_on will autornatically set to the date time on which an issue ismoditied. ‘Another coo! thing is that the owner fields automatically populated with all the users inside the site ‘We have defined our list view to show ID name. status, owner and ‘modified or’in the model. You can get to this view by navigating tohttpy/localhost800W/admin/ ludissues/issuer Creating the public user interface for ludissues O7 Seezn teen interface is working, But weneed a way to display the ata that we have added using the admin interface But thereis, 10 pubic interface. Let's create itmow, ‘We will have to begin by editing the main urs ay udlssueTracker/urls.py). Hurlpatterns = patterns’, (r'*,include(‘ludissues. urls"), (e*adnin’”, include(adnin.site.urls)), > This ensures that all the requests willbe processed by lucissuesurs first Creating ludissues.url Gestea wispy flein the app directory Vucissuess/ls by) with the following content EE from django.conf.urls import patterns, include, url BE # use ludissues model I from nodels import ludissues I # dictionary with all the Introducing Python objects in ludissues info = { ‘queryset’ ludissues. objects.all(, + I To save us writing lots of python code Be ve are using the list. detail generic view BI list detail is the name of view we are using B uripatterns = patterns(‘django.views.generic. List_detail’, I #issue-List and issue-detail are the template nanes I fenich will be looked in the default template #directories HB urierss' fobject_ List’ info,nane="issue-list’), HB urler@pcobject_ id\d8/S" object detail’ info,nane="issue-detail’), > To display an issue list and deta, we ate using a Django feature called (generic views. n this case we are Using views called lst and details This allow us to create an issue list view and issue detall view. These views are then applied using the issue_lsthtm| and issue_detal html template. In the following steps we wil create the template files. Setting up template and media directories In this step we will create the template and media directories. We have already mentioned the template directory as TEVPLATE_DIRS = ( getabspath(‘templates’) > Make web apps with Python Which translates to lucssueTracked ludlssueTracker/templatesé Since ‘we il be accessing the templates fiom the ludissues app, the complete directory path would be ludissueTracker/ludissueTracked templates/udisues, Create these folders in your project folder, ‘Ako, ceate the directory ludissucTracker/ludssucTracke/mecia/ for holding the CSS fle. Copy the style «ssfle from the resources diectory of the code folder. To serve files rom this foldes, make it available publicly. (Open settingspyand add these fines in ludissuetracker/ludissuelracker/urspy: I from django.conf.urls import patterns, include, url I from django.conf import settings TH Uncomment the next two ines to enable the admin: I from django.contrib import adinin ‘admin. autodiscover() T urlpatterns = patterns(”, (P°™,ineludeC-Iudissues. urls’), (r'"adnin/’, include(@dnin. siteurls)), ('tnedia/ CP spath>.s)$",’django.views. static.serve’, {document root’:settings. NEDIA ROOT) ) Creating the template files TO wrest ses from the ludssueTracker luclssucTiecker/templates cectory. In Django, we start with the ludssueliacter/ludlssuetiackey templates/basehtmal template. Thinkot itasthe master template which can be inherited by slave ones. ludisuetiecker/ludlssucTracke/ templates/basebtml BE 1 LuD ssue Tracker 1
View Issues 1
  • Admin Siteya
    • 1
    i
    1 {% block content %}{% endblock %}
    “To display an issue list and details here, we are using a Django feature called generic views" Make web apps with Python Introducing Python lud is: EE) Admin site IES pre SCC mmen ng 1 There is a problem in that module, new max 2 Intemet is not able to connect on the mars server. accepted ana 3 galactic federation has some issues with Star Wars accuracy started ‘samfisher 4 Moving sais are stuck again, This i the third time it ha stared dumbledore 5 Three cells are missing from splinter cell torch started samfisher {(variablename }} represents a issue.name }}
    ho Django varable. (96 block title 9%) represents blocks. Contents ofa black are evaluated by Dango and are displayed. These blocks can be replaced by the child templates. Nowwe need to create the issue_st. html ternplte. This ternplte is responsible for displaying all the issues available in the system, ludssucTiacker/udlssucTracked! templates/Iudissues/issue_list html {% extends ‘base.html’ %} HG block title %View Issues {% endblock %} (% block content %} I I std>({ ({_ issue, status h/t t {{_ issue. owner}} I 6 endfor %) B BG endblock % Here we ae inherting the base, hime that we created eater Bo for isuein object_lst 9) runs on the object sentby the urispy. Then we ‘xe iterating on the object_tst for issueid and fsuename, Now we will create istue_detal horn. This tempiate is responsible for cisplaying the detal view of case. ludlsuetiackevtudlssueTiacker! templates/udissues/ssue_detal him HE & extends ‘base.html’ x} BG block title s)Issue #{( object.id }} - {% endblock %} B(x block content 2 B charissue #{{ object.id {{ object.status }} B
    i

    Informations/ I

    Last modified {{ object.modified_on BD ago

    1
    8nbspi
    I

    ({ object.ouner }}

    t
    8nbsp;
    Sumnary

    (( object.sunmary })

    HG endblock %} ‘And that’s everything! The issue tracker app isnow complete and ready touse. You can now point your browser at localhost 8000 to stat using the app. Introducing Python Build an app for Android with Python Build an app for The great thing about Kivy is there are loads of directions we could take it in to do some pretty fancy things. But, were going to make a beeline for one of Kivy’s coolest features - the ability it affords you to easily run your programs on Android. Welll approach this by frst showing how to make a new app, this time a dynamic Breakout-style game. We'll then be able to compile this straight to.an Android APK that you can use ju other, Of course, mastered the basic techniques like ans nce you have you aren't limited to using any particular kind of app, as even on Android you can make use ofall your favourite Python libraries Android with rm app! to make any sort of program you like. Once you've mastered Kivy, your imagination is the only limit. youte pretty new to Kivy, don't worry, we wor’t assume that you have any pre-existing knowledge. As long as you have mastered some of the Python in this book so far, and have a fairly good understanding of the language, you shouldn't have any problems following along with this Before anything else let's throw together a basic Kivy app (Fig, 01). We've pre-imported the widget types we'll be using, which this time are just three: the basic Widget with no special behaviour, the ModealView with Python a pop-up behaviour as used last time, and the FloatLayout as we will explain later. Kivy has many other pre-built widgets for creating GUIs, but ths time we're going to focus on drawing the whole GUI ftom scratch using Kivy's graphics instructions. These comprise either vertex instructions tocteate shapes (including rectangles, ines, meshes, and s0.0n) oF contextual graphics changes (such as translation, rotation, scaling, 0), and are able tobe drawn anywhere on your screen and on any widget type Before we can do any ofthis well need a class for each kind of game object, which we're going to pre-populate with some of the properties that well need later to control them. Remember from last time, Kivy properties are special attributes declared at class level, which (among other things) can be modified via kv language and dispatch events when they are modified, The Game class will be one big widget containing the entire game, Weve specifically Build an app for Android with Python made ita subclass of FloatLayout because this special layout is able 10 position and size its children in proportion to its own position and size — so ne matter where we run itor how much we resize the window, it will place all the game objects appropriately. Next we can use Kivy’s graphics instructions to draw various shapes on our widgets. Wellljust demonstrate simple rectangles to show their locations, though there are many more advanced options you might lke to investigate. In ‘Python file we can apply any instruction by declaring it on the canvas of any widget, an example cof which is shown in Fig. 03. This would draw a red rectangle with the same position and size as the player at its moment of instantiation — but this presents a problem, unfortunately, because the drawing is static. When we later go on to move the player widget, the red rectangle will stay in the same place, while the widget will be invisible when itis in its real position, We could fix this by keeping references to our canvas instructions and repeatedly updating their properties to track the player, but there's actually an easier way to do all of this- we ‘can use the Kivy language we introduced last time. Ithhas a special syntax for drawing on the widget canvas, which we canuse here to draw each of our widget shapes: Player: Rectangle: pos: self.pos size: self.size rgb: 1, 0.55, 0 Rectangle: pos: self.pos size: self.size : canvas: Color: rgb: self.colour # ‘operty we predefined above Rectangle: pos: self.pos size: self.size Colo rgb: 0.1, 0.1, 0.1 li rectangle: [self.x, self-y, self.vidth, self. height] The canvas declaration is special, undemeath it we can waite any canvas instructions we |ike. Don't get confused, canvas is not a widget and nor are graphics instructions like Line. This isjust a special syntax that is unique to the canvas. Instructions all have Introducing Python different properties that can be set, like the pos and size of the rectangle, and you can check the Kivy documentation online for all the different possibilities. The biggest advantage is that although we still declare simple canvas instructions, kv language is able to detect what Kivy properties we have referred to and automatically track them, so when they are updated (the widget moves or is resized) the canvas instructions move to follow this! from kivy.app import App from kivy.uix.widget import Widget fron _kivy.uix.floatlayout import FloatLayout from kivy.uix.modalview import ModalView version = ‘0.1 Us ater Andre conpi during class BreakoutApp(\pp): pass Breakoutapp().runQ) from kivy.proper ties import (ListProperty, NumericProperty, ObjectProperty, StringProperty) Introducing Python ss Game(Floatlayout): # Will contain everything blocks = ListProperty(1) player = ObjectProperty() # The ayer instance ball = ObjectProperty() # The game's Ball instance game's © Player(Wideet): i paddle position = NumericProperty(2.5) direction = StringProperty(‘none') class Ball(Widget): # A buncing ball s_hints pos_hint_x = Numer icProperty(?.5) pos_hint_y = Numer icProperty(2.3) proper_size = NumericProperty(2.) velocity = ListProperty([2.1, @.5]) loss. Block(iidget): destroy colour = ListProperty([i, ®, 0) from kivy.graphics.context_ instructions import Color from kivy.graphics. vertex_instructions import Rectangle cles Player(ilideet): Build an app for Android with Python def _init_Gelf, seekwargs): super Player, self), init__(eskwargs) with self. canvas: Color(i, 2, 0 #r, g, b, a> red Rectangle(pos=self.pos, size=self.size) or without 1 with —sye asad ‘Above Running the ap shows ur eoloures blocks onthe Seren. but they a ove! We ccanfitnateasy You probably noticed we had one of the Block's Color’ instructions refer to its colour property. This means that we can change the property any time to update the colour of the block, or in this case to give each blocka random colour Fig, 04, Now that each of our widgets has a graphical representation, let's now tell our Game where to place them, so that we can start up the app and actually see something there. class Game(Float|ayout): def setup_blocks(self): for yjump in range for x_jump in range(10): block = Block(pos_ hint={ 0.05 + 0.09%x_ Jump, 'y' 0.05 + 0.09%y_ jump)) self.blocks. append(block) self.add_ widget(block) loss BreakoutApp('e): def build(self): g = Game() g.setup_blocks() return Here we create the widgets we want then use adc_widget to add them to the graphics tree, Our root widget on the screen is an instance of Game and every block is added to that to be displayed The only new thing in there is that every Block has been given a pos_hint All widgets have this special property, and itis used by FloatLayouts ike our Game to set their position proportionately to the layout, The dictionary is able to handle various parameters, but in this case and 'y’ give xand y Block position as a relative fraction of the parent width and height. You can un the app now, and this time itwill add 50 blocks to the Game before displaying it on the screen, Each should have one of the thiee possible randorn colours and be positioned in a atid, but you'll now notice their sizes haven't been manually set so they al overlap. We can fix this by setting their size_hint properties — and let's also Build an app for Android with Python take this opportunity to do the same for the other widgets as well Fig. 05) ‘This takes care of keeping all our game widgets positioned and sized in proportion to the Game containing them, Notice that the Player and Ball use references to the properties we set earlier so well be able to move them by Just setting these properties and letting kv language automatically update their positions. “The Ball also uses an extra property to remain square rather than rectanguiar, just because the alternative would likely looka ttle bitodd, We've now almost finished the basic graphics of our app! ll that remains is to.add a Balland a Player widget to the Game. : ball: the_ball player: the_player Ball: the_ball Player: cd: the_player You can run the game again now, and should be able to see all the graphics working propetly. Nothing moves yet, but thanks t0 the FloatLayout everything should remain in proportion ifyou resize the game/vindow. Now we just have to add the game mechanics. Fora game Ike this you usually want to run some update function many times per second, updating the widget positions and carrying out game logic —in this case collisions with the ball (Fig. 06. The Clock can schedule any function at any time, either once or repeatedly. A function scheduled at interval automatically receives the time since its last call (tt here), which welve passed through to the bell and player va the references we created in kv language. I's good practice to scale the update (eg ball distance moved) by this dt, so things remain stable even if something interrupts the clock and updates don’t meet the regular /60s you want. Atthis point we have also added the first steps toward handling keyboard input, by binding to the kivy Window to calla method of the Player every timea key is pressed We can then finish off the Player class by adding this key handler along with touctvmouse input. class Player(Wideet): ef on_touch_down(self, touch): self.direction = ( ‘right! if touch.x > self.parent. —center_x else "left’) ef on_touch_up(self, touch): self.direction = ‘none’ def on_key_down(self, keypress, =scancode, *args): Introducing Python if scancode self.direction 205: self.direction else: self.direction = ‘none’ ce? on_key_up(self, *args): self.direction = ‘none’ def updateGelf, dt): dirdict = ('right’: 1, "left': -1, ‘none’: 0} self position = (0.5 * dt * dir ~dict(self. direction) These on_touch_functions are Kivy's general method for interacting with touch or mouse input, they are automatically called when the input is detected and you can do anything you like in response to the touches you receive. In this case we set the Player's direction property in response to either keyboard and touch/mouse input, and use this direction to move the Player when its update method is called. We can also add the right behaviour for the ball Fig. 07) This makes the ball bounce off every wall by forcing its velocity to point back into the Game, as well as bouncing from the player paddle - but with an extra kick just to let the ball speed change. It doesn't yet handle any interaction with the blocks or any wirvlose conditions, but it does try to call Gamelose0 ifthe Introducing Python ball hts the bottom of the player's screen, solet's now add in some game end code to handle all ofthis (Fig, 08). And then add the code in Fig, 0910 your oreakoutky fle This should fully handle the loss or win, opening a pop-up with an appropriate message and providing a button to try again. Finally we have to handle destroying blocks when the ball hits them (Fig. 10. This fully covers these last conditions, checking collision via Kivy's builtin collide_wilget method that compares their bounding boxes (pos and size). The bounce direction will depend on how far the ball has penetrated, as this willtell us how it first collided with the Black. So there we have it, you can run the code to play your simple Breakout game. Obviously its very simple right now, but hopefully you can see lots of different ways toadd whatever extra behaviour you Ike — you could acd different types of blocks and power-ups, a lives system, more sophisticated paddle/ball interaction, or even build a full game interface with a menu and settings screen as well \We'e just going to finish showing one coo! thing that you can already do ~ compile your geme for Android! Generally speaking you can take any Kivy app and tum it straight into an Android APK that will un on any 36 Build an app for Android with Python of your Android devices. You can even access the normal Android AP|to access hardware or OS features such as vibration, sensors ‘OF native notifications. Well build for Android using the Bulldozer tool, anda Kivy sister project wrapping other build tools to create packages on different systems. Ths takes care of downloading and running the Android build tools SDK, NDK, ete) and Kivy’s Python for- Android tools that create the APK. import random Block(Widget): def _init_Gelf, aekwargs): super Block, self)._init__¢skwargs) self.colour = random.choice({ @.78, 0.28, 0.28), 0.25, 30.28, 0.63, 0.28, 0.78))) Fig 05 : size_hint: 0.1, 0.025 {xi self. all>: pos_hi hint, 'y': 2 Cx'r self.pos_ self.pos_hint_y} None, None proper_siz (@.03*self.parent. height, 0.02self.parent.width) size: self.proper_size, self.proper_size canv from kivy.clock import Clock from kivy.core.window import Window from kivy.utils import platform class Game(FloatLayout); lef update(self, dt): self.ball. update(dt) # Not defined yet self player. update(dt) # Not defined yet ‘ef start(self, xargs): Clock. schedule interval(self.update, 1./50.) cel stopGelf): Clock. unschedule(self.update) cel reset(elf): for block in self.blocks: self.remove_ widget(block) self.blocks = [] self. setup_ blocks() self.ball velocity = [random.random(), 2.5] self player. position = 0.5 loss Breakoutapp(po): def build(self): Build an app for Android with Python 2 = Game() if platform() != ‘android’: Window. bind(on_key_down=g.player. ‘on_key_down) Window, player.on_ bind(on_key_up= key_up) g.reset() Clock.schedule_ once(g.start, 0) return g class Ball (Widget) def update(self, dt): self.pos_hint_x += self.velocityla] * dt self.pos_hint_y += self.velocityfi] * dt if self.right > self.parent.right: # Bounce from right self. velocity[2] = -1 * sbs(self. velocity(?) if self.x < self. parent.x: # Bounce from left self. velocity(2] = —abs(self. velocity(?)) if self-top > selfiparent.top: # Bounce from top self. velocity[i] = -1 * sbsGelf. velocityfi]) if selfy < self. parenty: # Lose at bottom self parent, lose() # Not implenented yet self. bounce_from_ player(self.parent.player) # bounce_ from_player(self, player): if self. collide_widget(player): self. velocity(I] = abs(self. velocity(i]) self, velocity{2] += ( @1 * — (Gelf.centerx = player.center_x) / player.width)) GameEndPopup(oda View): message StringProperty() game = ObjectProperty() class Game(Widge def loseGelf): self.stopQ Game€ndPopup( message="[color=iff0000]You lose! /color]’, game=self).open() def win(self): # Not called but we'll ne it later self.stopQ) GameEndPopup( message="[color=#00ff00]You win!(/color]’, game=self).open() Introducing Python : size_hint: 0.8, 0.8 False auto_dismis: "te close if Clicks outside BoxLayout: orientation: ‘vertical’ Label: text: root. message font_size: 60 markup: True halign: ‘center’ Button: size_hint_y: None height: sp(82) text: ‘Play again?’ font_size: 60 on_release: root.game.start(); root. dismiss() Here you will be needing some basic dependencies, which can be installed with ease just by using your distro’s normal repositories. The main ones to use are Open JDK7,zlip, an up-to-date Gython, and Git. If you are using a 64-bit distro you will also be in need of 32-bit compatibility libraries for zlib, libstdc++, as well as lingce. You can then go on and download and install Buildozer: Introducing Python Putting your APK dar ely cee Deccan arr MU? Der rae 2.apk Build an app for Android with Python “Check through the whole file just to see what's available, but most of the default settings will be fine” git clone git://github.con/ kivy/buildozer cd buildozer sudo python2.7 setup.py install When youte done with that part you can then go on and navigate toyour Kivy app, and youll have toname the main code file main. py, this is the access point that the ‘Andioid APK will expect. Then: buildozer init This creates a ‘buildozerspec file, a settings file containing all the information that Bulldozer needs to create your APK, from the name and version to the specific Android build options. We suggest that you check through the whole file just to see what's available but most of the default settings will be fine, the only thing we suggest changing is (Fig. 11), There are various other options you will often want to set, but none are really all that vital right now, so youre able to immediately tell Buildazer to build your APK and get going! buildozer android debug This will take some time, so be patient and it will work out fine. When you first run it, it will download both the Android SDK and NDK, which are large (at least hundreds of megabytes) but vital to the build It will also take time to build these and to compile the Python components of your APK. Alot of this only needs to be done once, as future builds will take a couple of minutes if you change the buildozerspec, or justa few seconds if youve only changed your code The APK produced is a debug APK, and you can install and use it There are extra steps if you want to digitally sign itso that it can be posted on the Play store. This isn't hard, and Buildazer can do some of the work, but check the documentation online for full details, Assuming everything goes fine (it should!), your Android ‘APK will be in a newly created ‘bin’ directory with the name “KivyBreakout-0.1-debugapk’, You can send it to your phone any way you like (eg emai), though you may need to enable application installation from unknown sources in your Settings before you can instal it Build an app for Android with Python self.parent.do_ layout() self.parent.destroy_ blocks(self) loss Game() 4 ball): for i, block in ‘o(Gelf.blocks): if ball, collide_widget(block): y-overlap ball. top - blocky if ball velocity] > 0 else block.top - bally) / block. size_hint_y x_overlap ball. right - block.x if ball. velocityl”] > 0 else block.right - ballx) / block.size_hint_x if x overlap < y_overlap: ball.velocity(2] = else: ball.velocity[i] = self. remove_widget(block) self.blocks. pop(i) Introducing Python if lenGelf. Fae blocks) oon eg self. een wind eter) return title = Kivy Breakout package.name = breakout fullscreen = log_level = 2 Above Your game shouldrun on any modern Andrid device. you can even bud 2 release \vesion and pubshto an app store! Introducing Python — 50 Python tips Python is a programming language that lets you work more quickly and integrate your systems more effectively. Today, Python is one of the most popular programming languages in the open source space, Look around and you will find it running everywhere, from various configuration tools to XML parsing. Here 50 Python tips s the collection of 50 gems to make your Python experience worthwhile. Basics Running Python scripts 0 On most of the UNIX systems, youcan run Python scripts from, the command line. I$ python mypyprog.py Running Python programs from Python interpreter 0 The Python interactive interpreter makes it easy to ‘vy your fist steps in programming and using all Python commands. ‘You just issue each command at the. ‘command prompt (>>>), one by ‘one, and the answer is immediate. Python interpreter can be started with the command: I$ python I kunal@ubuntu:~$ python H Python 2.6.2 (release26- maint, Apr 19 2009, 01:56:41) (GCC 4.3.3] on Linux2 Type “help”, “copyright”, “credits” or “License” for more information. >>> In this article, all the code starting at the >>> symbolisto begivenat the Python prompt. Itis aso important to remember that Python takes tabs very seriously —so if youare recehing any emor that ‘mentions tabs correct the tab spacing, Dynamic typing 03: In Java, Gt+and other statically typed languages, you must specify the data type othe function return value and each function argument.On the other hand, Python isa dynamically typed language.in Python you will never have to explicitly specify the deta type of anything you use. Based on what value you assian, Python will automatically keep track of the data type internally Python statements Python uses cariage returns 10 separate statements, and ‘colon and indentation to separate code blocks. Most ofthe compiled programming languages, such as C and C+, use semicolons to separate statements and curly brackets 10 separate code blocks. and = operators 0! Python uses for ‘comparison and "for assignment. Python does not suppor inline assignment, so there's no chance of accidentally assigning the value ‘when youactually want to compare Concatenating strings 06222" err" stings Bh > print skun’¥al’ kunal The __init__method O7 ecttcmtosiannes soonas an object of a cassis instantiated. The method's useful todo any intalzation you want to do with your object. The —_intt__method isanalogous toa constructor in CH, Ct or lava Example: I class Person: def _init_(self, name) BL selfiname = name I cer saytivselt): print ‘Hello, my name self.name Bp = Person(‘Kunal”) BH p.saytiio. Output: I Grsre/python $: python initmethod.py Hello, my name is Kunal Modules 0 To keep your programs manageable as they grow in size youmay want to make them into several les. Python allows you to put multiple function definitions into fle and use them asa module that can be imported. These files must havea py extension however, Example: I # file my function.py HE def minmax(a,b): ifacb: B min, max B else: Bin, max = b, a return min, max B vodule usage BE inport my_function 1b Module defined names OQ Een The built-in function di! can bbe used 0 find out which names module defines t retusa sorted lst ofstiings, > import time B >> dirctimey (doc, “file, ‘ame’, ‘_package.. ‘accept2dyear’, ‘altzone’, ‘asctine’, ‘clock’, ‘ctine', ‘daylight’, ‘gmtine’, ‘localtine’, ‘mktine’, ‘sleep’, ‘strftine’, ‘strptime’, ‘struct_time’, ‘time’, ‘timezone’, “tznane’, “tzset’IFile"] Module internal documentation 1 ox can see the internal socumentation if available) of amedule name by looking at __doc_. Example: >> import tine >> print tine.clock._doc_ H clock() -> floating 50 Python tips point number This example retums the CPU time or realtime since the start ofthe process orsince the fist call to dock). This has just as much precision as the system records do. Passing arguments toa Python script Python lets you access whatever 1 you have passed toa script while calling it The command line! ‘contents stored in the sys.argy list import sys H print sys.arey Loading modules or commands at startup [Drees redetres modules or ‘commands at the startup of any Python script by using the environment variable SPYTHONSTARTUP. Youcan Set envionment variable SPYTHONSTARTUP to a fle which contains the instructions load necessary modules or commands Converting a string to date object TZ eicnustetecton DateTime’ to convertastting toa cate object. Example: I fron DateTime import DateTime I dateobj = Datetime(string) Converting a string to date object 1 ‘You can convert.a list to string in the following ways. ‘Istmethod: >> nylist = ('span’, ‘han’, Introducing Python ‘eges'] B >> print ‘, ‘join(mylist) B span, han, eggs 2nd method: [>> print ‘Wn’ join(nylisty Bi span B ham Beggs Tab completion in Python interpreter s Lye achieve auto completion inside Python interpreter by adding these lines to your pythonre fl (or your filefor Python to read on startup) import rlcompleter, readline Il readline.parse_and_bind(‘tab: complete’) This will make Python complete partially typed function, method and variable names when you press the Tab key Python documentation tool 1 You can pop up a graphical interface for searching the Python documentation using the command: B's pycoc - ‘You will need python-tk package for this to work, “Today, Python is certainly one of the most popular rogrammins languages to be found in the open source space” ry Introducing Python Accessing the Python documentation server Teste sve on the given port an the local machine. This will give you @ nice-looking access to all Python documentation, including third-party module documentation Is pydoc -p Python development software TQ incxneny of tools to help with Python development. Here are a few important ones IDLE: The Python built-in IDE, with autocompletion, function signature popup help, and fle editing IPython: Another enhanced Python shell with tab-completion and other features Eric3: A GU Python IDE with autocompletion, class browser buittin shell and debugger, WingIDE: Commercial Python IDE with free licence avalable to open- source developers everywhere, Built-in modules Executing at Python interpreter termination [Qe nye see mosdew execute functions atthe tine of Python interpreter termination, Example: B def sumo: prints) IH def messageO: i print(‘Executing Now") import atexit I atexit.register(sum B atexit register (message) ‘Output: I Executing Now 9 50 Python tips Converting from integer to binary and more 20: Python provides easy-to-use functions — bind, hex) and ctl) 10 corwer from inteaer'o binary, >> bins) ‘ebi1000" Bo hexc2) Bons" H >> oct(24 HE ‘030° Converting any charset to UTF-8 D1 eesctetoning function to convertany charset toUIF8 I data.decode(“input_charset_ here”).encode('utf-8") Removing duplicates from lists 2 Ifyou wantto remove dupicates froma ist just putevery element into a dict as akey for example with one! asvalue) and then check cictheys0 I from operator import setiten H def distinct): 4=0 napGetiten, G,)len(1, 1, 0) return d.keysQ Do-while loops DZ srehrtonhascadonhie ‘or do-unt loop constructs et you can use the following method to achiove similar results B white true: TH do-something HF condition: t break Detecting system platform QQ eerie ton spect functions itis very useful to be able to detect the platform on which the Python interpreter is running, You can use ‘sysplatform to find out the current platform Example: On Ubuntu Linux: >> import sys >> sys.platform BE tinue’ ‘On Mac OS X Snow Leopard > import sys Disabling and enabling garbage collection DB sareimennouinay ‘want to enable or disable the gatbage collector function atruntime. You can use the ‘gc’ module to enable or disable the garbage collection. Example: >>> import gc > gc.enable >> ge.disable BE ctuilt-in function disable> Using Cbased modules for better performance DWE rer rntenmosies chip with counterpart Cradles. Using these C modules will ea significant performance boost in your complex applications. Example: [ cPickle instead of Pickle, eStringlO instead of Stringto Calculating maximum, minimum and sum Qe use the folowing but in functions, maxs Returns the largest elementin thelist min: Returns the smallest element in thelist. ‘sum: This function returns the sum ‘of all elements in the Ist. accepts an ‘optional second argument: the value to start with when summing (defaults 100). Representing fractional numbers QQ retenrsance canbe created in Python using the following constructor I Fraction(inunerator [,denominator]]) Performing math operations 2Q Mermst medi prvdes a plethora of mathematical functions. These functions work on integer and float numbers, except complex numbers. For complex numbers, 2 separate module is used, called ‘omath. For example: B nath.acos(): Return are cosine of x. B nath.cos(9: Returns cosine of x [ math.factorial) : Returns x factorial. Working with arrays 3 The ‘array’ module provides an efficient way to use arrays in your programs. The ‘aay’ module defines the following type: I array(typecode [, 50 Python tips initializer) ‘Once you have created an array object, say myarray, you can apply ‘bunch of methods toit. Here are afew important ones B myarray.count(x): Returns the number of occurrences of x ina. [ myarray.extend(x): Appends x at the end of the array. [ myarray.reverse(): Reverse the order of the array. Sorting items Bete mete ates it very easy tokeep lists in any possible order. You can use the following functions to order Iss. E bisect.insort(ist, item [, Jow [, hight) Inserts tem into lst in sorted order. f itern i akeady in thelist, the new entry is inserted tothe right of any existing entries there I bisect.insort_lert(list, item Clow C, hight) Inserts item into list in sorted order, IFitem is already within thelist, the. pew entry's inserted to the left of any existing entries. Using regular expression-based search BDMe rs mace matesiver easy to use regup-based searches. You can use the function ‘tesearch0) with aregexp-based ‘expression. Check out the example included below. Example: H >> inport re >> s = “Kunal is a bad boy” [>> if research", 9): print “Match!” # char Literal B ratcht [>> if re.search(*[@aZI", 5): print “Match!” # char class I... # match either at-sign or Introducing Python copital letter B Matcht >> if re.search(Ad", s): print “Match!” # digits class Working with bzip2 (bz2) compression format BZ rouse terocute2 10 read and wie data Using the bzip2 compression algorithm, B bz2.compress() : For bz2 ‘compression Hb22.deconpress() decompression Example: Bf # Fite: bz2-example.py import bz2 B messace = “Kunal is a bad boy” T conpressed_nessage = bz2. ‘compress(MESSAGE) I decompressed_nessage = bz2. decompress (compressed_nessage) [ print “original:”, repr (MESSAGE) print “compressed messzge:”, repr(compressed_ message) [ print “decompressed message:”, repr(deconpressed message) Output: [ Césre/python $3 python b22- exanple.py original: ‘Kunal is 2 bad boy’ T compressed message: “BZMOUAYESY\xCAAWOFEAXBBN x00\ ¥00\x02\x15\x80\00\x00\x084% ¥8a\X00"\XG0\2C\XBAVNXO3C\ xaZ\xbO xd6S\x25\xb3\X19\X00\XF xbb\x92)\xc2\x84\x86 z<\xc0" [ decompressed message: ‘Kunal is a bad boy’ For bz2 “There are tools to help develop with Python” Introducing Python Using SQLite database with Python. JG sic tet beconing very ‘popular embedded database because of the zero configuration that is needed, and ts superior levels of performance. You can use the module ‘sqite3'in order to work with these SQite databases. Example: H >>> import sqlites >> connection = sqlite. connect(‘test.db) >> curs = connection. cursor B >> curs.execute(‘"create table item IL... Gd integer primary key, itenno text unique, . scancode text, deser text, price real)’”") H Working with zip files 35 ‘You can use the module Zipie towork with zips. IB zipfile.zZiprile(filenane [, mode [, compression Callowip64I1)) Open azip fle, where the fle can be eithera path toa file (a sting) or a fle- tke object. I zipfite.ctoseot Close the archive fl, You must cal ‘close() before exiting your program or essential records wil not be writen, B zipfile.extract(nenberL, path(, pud]) Extract a member fiom the archive to the current working diectory, ‘member must be is fullname fora Zipinfo objects file information is extracted as accurately as possible. ‘path’ specifies acifferent directory to extract ta'member can bea flename ora zipinto abject. pwed'is the password used for encrypted les. 50 Python tips Using wildcards to search for filenames BG Ceremonies t0indallthe pathnames ‘matching a pattern according to the rules used by the UNX< shell *,?,and character ranges expressed with [] wil be matched Example: I >>> import glob >> glob.gloo(./1e-91.") Deir, 72.txt7 >>> glob.glod(‘*.gif”) Tigi’, ‘card.gif" > glob.glob(‘?.gif") Bevgiry Performing basic file operations QZ uses ttemarkie sat to perform basic file operation ata high level. This module works with your regular files and so wall not work ‘with special files like named pipes, block devices, and so on. I shutil.copy(src,dst) Copies the il src to the fle or directory dst. EE shutil.copymode(sre,dst) Copies the file permissions from src tod I shutil.move(sre,dst) Moves a file or directory to dst. T shutit.copytreetsre, dst, symlinks [,ignoreJ]) Recussively copy an entive directory ats BE shutil.rmtree(path [, ignore_ errors [, onerror]]) Deletes an entire directory. Executing UNIX commands from Python 38 modile Jcommands to execute UNIX commands. This snot avaliable in Python 3— instead, inthis you will need to use the module subprocess. Example: >> import. commands >> commands. getoutput(‘Is") BE ‘bz2-example.py\ntest. py’ Reading environment variables 30% use the module os to gather up some operating- system specific information: Example: >> import os >> os.path >>>_os.environ {'LANG': ‘en_IN’, “TERM: “xterm ‘Ioin/bash’, ‘LESSCLOSE’ I ‘usr/vin/lesspipe %s %s’, 'XDG_SESSION_COOKIE’: 925c4644597¢7 9170465635400 °56d65- 257673132.347986-1177792325", ssa: 11, ‘SSHTTY: ‘/dev/ pts/2’, ‘PAD’: 7 home/kunal’, LESSOPEN': “|, usr/bin H lesspipe oo B >> os.name ‘posix’ BE > os.linesep Iw “Look around and you will find Python everywhere, from various configuration tools to XML parsing” Sending email ‘You can use the module AO irc tosercemal using an SMTP (Simple Mall Transfer Protocol) lent interface. smtplib.SMTPCChost [, port) Example (send an email using Google Mail SMTP server): Bl import smtplib Bl # Use your oun to and from fenail address IE fromaddr = ‘kunaldeo@email.con’ Hl toaddrs = ‘toemailégmail.con’ Bnsg = ‘T am a Python geek. Here is the proof!’ I # Credentials I # Use your oun Google Mail credentials while running the progran B usernane = ‘kunaldeo@gnail con HE password = ‘xxxxxxxx’ Bl # The actual mail send server = smtplib.S¥TPC smtp, sgnail.con;587") I # Google Mail uses secure connection for SMTP connections B server-starttls() I server. login(username, password) IE server.sendmai l(fromaddr, toaddrs, msg) B server.quito, Accessing FTP server QL tet a tytecgedcient FTP module for Python. To establish an FTP connection, you can Use the following function: smtplib.SMTP(Chost C, port) Example (send an email using Google Mail SMTP server): BH ftplib.FtP(Chost [, user [, passwd [, acct [, timeout]] 101) Example: H host Bl username B password con” [ inport Ftplib Binport uriiite I Ftp_serv = Ftplib. 50 Python tips FTPChost, username, password) I # Download the file Bu = urllib2urlopen ¢“Ftp:// Ftp.rechat.com/ pub/redhat/ ‘Linux/README”) I + Print the file contents B print (read) Output: I Cisre/python $:1 python Ftpclient.py (Older versions of Red Hat Linux have been moved to the folowing location ftpvarchivedownload redhatcom/ pub/redhavfinux/ Launching a webpage with the web browser QD Te weronser module provides a corvenient way to launch webpages using the default web browser Example (launch google.co.uk with system’s default web browser): >>> import webbrowser >>> uebbrowser-openChttp:// google.co.uk’) True Creating secure hashes The ‘hashiib’ module AB ssonsa paso secure hash algorithms including SHAI, SHA224, SHA256, SHA384, SHASI2 and MDS. Example (create hex digest of the given text): [> iinport hashlib I # shat bigest Bh >> hashlib.shancras Classified Information 00?" hextigestO. I sezatoisiaFzzsccachassaiehsee3 BI revorbaoces" I & shears Digest Bh >> hashlib.shazes Classified I ‘infomation 007") hextigest() Introducing Python “scele2Fraleoebac2t0e 482" 90567007 II Tesebts990e08355e200" I sha256 Digest >> hashlib shavse(MI6 Classified I information 007 hexdigestO ID 2fodesrsarsdmberarcnaarasaaicas I vasserorcbracsaase fob33bIc19825e" Di shax84 Digest I >> hashlib sha384¢ M06 Classified I information 007") hexcigest() ‘ScfotelgoftadbdlelddSecle Mods I ccis2ecc138aatToszsz08R2tsedaafSHabe [I senesefcadiaoscabsssasrad Dx shasi2 Digest >>> hashlib sha5l2CMI Classified Information @07") hescigest() | ‘aac ScbeF6e823457E462aT AB adZH025, 2e822d1F4973#49b850222edec0290089077 BacaB7aGaéeesF Fabb18565140667 af I] aideitFis2febc7iza2" I # 105 digest Hf >> hashlib.ndS@MI6 Classified I Information 007") hexdigest() I ‘se2ficszacis6f1a99¢9670c826F7126" Seeding random numbers. 4 You can use the module ‘random’ to generate a wide variety of random numbers. The most used one's Yendomseed(. It intalises the basic random number generator. Ifx is omitted or None, the current system time is used; the ‘current system time is also used to initiaise the generator when the module is fist imported, “Programming in Python lets you work more quickly and integrate your systems much more effectively” Introducing Python Working with CSV files A iiarsveypopatn for data exchange over the web. Using the module ‘sv, you can read and write CSV les, Example: import csv f write stocks data as cconna- separated values B writer = csv. writer(open(‘stocks.csv’, ‘wb’, buffering=0)) Bi writer.writerous(t BE (-c00c", ‘Google, Inc.’, 505.24, 0.47, 8.09), BE cvi00", “Yahoo! Inc.’, 38, 0.33, 1.22), TE CCNEr’, ‘CNET Networks, Ine.’, 8.62, 0.13, -1.49) | I # read stocks data, print status messages I stocks = csv reader(open(‘stocks.csv’, rb") I status labels = (1: ‘down’, @: ‘unchanged’, 1: ‘up") I for ticker, name, price, change, pct in stock: status = status_ abel sfemp(float(change), 0.0)] print “ts is %s (4st) % (name, status, pct) Installing third-party modules using setuptools A672 isa Python package which letsyou download, build, install, upgrade and uninstall packages very easly. To use the ‘setuptools’ 50 Python tips package you will need to install these from your dstribution’s package manager. Alter installation you can use the commend ‘easy_install to perform any Python package management tasks that are necessary at that point. Example (installing simplejson using setuptools): B kunaleubuntu:-$ sudo easy_ install simplejson T Searching for simplejson TE Reading http://pypi. python.org/simole/ simplejson/ I Reading http://undefined. org/python/#sinplejson best match: simplejson 20.9 B bounloading http:// pypi.python.org/packages/ ‘source/s/simplejson/ sinplejson-2.0.9.tar.g2#md5 =af5e67238¢a34085634110357 esdse47 Trrocessing sinplejson- 2.0.9.tar.gz TH Running simplejson-2.0.9/ setup.py -q bdist_ege —dist-dir /tmo/ easy_install-FiyfNL/ sinplejson-2.0.9/egg-dist- ‘tmp-3¥Wsc¥ Adding simplejson 2.0.9 to easy-install.pth file [ installed /usr/local/Lib/ python2.6/dist-packages/ ‘simplejson-2.6.9-py2.6- 1inux-i686.c8g I Processing dependencies for simplejson I Finished processing dependencies for simplejson “You can use the module ‘random’ to generate a wide variety of random numbers with the basic generator” Logging to system log QT Weacsnuss theese ‘syslog! to write to system og ‘syslog’ acts as an interface to UNIX syslog library routines. Example: import. syslog I syslog. syslog¢‘mygeekapp: started logging’) B for a in Ca’, “br, 077: IE» = ‘nygeekapp: I found letter ‘+a I syslog. syslog(b) IE syslog. syslog(‘mygeekapp: ‘the script goes to sleep now, bye, bye!) Output: $ python mylog.py Is tail -F /var/log/nessages Nov 17:18:34 ubuntu ~~ MARK T Nov 8 17:22:34 ubuntu python: mygeekepp: started logging Dov 8 17:22:34 ubuntu python nygeekapp: I found letter a B)Nov 8 17:22:24 ubuntu python: nnygeekepp: I found letter b Wxov 8 17:22:34 ubuntu python: mygeekapp: I found letter c nov 8 17:22:34 ubuntu python: mygeekapp: the script goes to sleep now, bye,bye! Third-party modules Generating PDF documents AQ Tens save popular module for PDF generation fiom Python. Perform the foll toinstall ReportLab Bs wget http://w. reportlab.org/ftp/ steps ReportLab_2_3.tare2 Ibs tar xvfz ReportLab_23. tare ccd ReportLab_2_3 I's sudo python setup.py install. Fora successful installation, you should seea similar message: I nessesneenmasuonny INFORR RARER Dl sesteepeeniienemnnnenenate enenens I sattempting install of _rl_ accel, sgnlop & pytinj I #extensions from ‘/home/ kunal/python/ ReportLab_2_3/ src/rl_addons/rl_accel’ I nesteeneennernenenanenane serene I #attempting install of renderPH extensions from ‘/home/ kunal/python/ ReportLab_2_3/ src/rl_addons/renderP" Is installing with freetype version 21 I sereesnennonnsmnvinemnvane senenenee Example: >>> from report1ab.pdfgen. canvas import Canvas I # Select the canvas of letter page size [>>> from reportlab.1ib. pagesizes inport letter Bl >> pdf = Canvas(“bond.pd™, pagesize = letter) If inport units [>> from reportlab.Lib.units import cm, mm, inch, pica Bl >> paf.setFont¢“courier”, 69) I >> pdf.setFilicolorrssc1, 0, 0) Bi > pat. 50 Python tips dravCentredstring(let ter[6] 12, inch * 6, “MI6 CLASSIFIED”) I >> paf-setFont(‘Courier”, 40) B >> paf. drawCentredstring(letter[@] / 2, Inch * 5, “For 007's Eyes only”) I= Close the drawing for current page I >> paf.showPageO I save the pdf page B >>> paf-saveQ) Output: BE eimage:pdf.png B etitie: POF Output Using Twitter API QQ reucsncorneeto Te easily using the Python Twitter’ module. Perform the following steps to install Python-Twitter: I$ wget http://python- ‘twitter. googlecode.con/files/ python-tuitter-0.6.tar.gz Bs tar xvfz python-twitters IS cd python-twitter« I$ sudo python setup.py install Example (fetching followers list): [>> import twitter # Use you own twitter account here [>>> mytwi = twitter-spicus ername='kunaldeo’,passnord="x 0008x") E> friends = mytwi. GetFriends( [>> print Gu.nane for u in friends) “There are plenty of services such as [Python and IDLE available to users to help them with Python development” Introducing Python BE Gate Legend Gennell’, urjono wells’, u'The YON Big Blog’, u’Manish Mandal’, U'iHBsndw', u'TndiarVideoGaner. com’, u'FakeAaron Hillegass’, u’ChaosCode’, u’nileshp’, u’Frank Jennings’, Doing Yahoo! news search 50° use the Yahoo! search SOK to access ‘Yahoo! search APIs from Python. Perform the following steps install it: I suzet http://developer. vyahoo.com/dounload/Files/ Yyus- 2.12.2ip Bs unzip ywse S cd ywst/Python/ plsearchs/ Is sudo python setup.py install Example: HL # Importing news search APL Bl >>> from yahoo.search. news import NewsSearch B >>> srch = NewsSearch(“YahooDemo’, query="London’) Hl # Fetch Results I >> info = srch.parse_ results() I > info.total_results_ available 41640 I >> info.total_results_ returned Hie >> for result in info. results: - print “%s', from %s” % (result{'Title’], result{'NewsSource’)) “afghan Handover to Be Planned at London Conference, Brown Says’, from Bloomberg a7 Work with Python Practical Python tips and projects [em Sat poner hiy PROM et nore culm Practical Python tips and projects v ft Work with Python What you'll need... Replace your shell with Python Replace your shell with Pytnon langua your primary but did shell? it programm an even repl We all use shell on a daily basis. For most of us, shellis the gateway into our Linux system. For years and even today, Bash has been the default shell for Linux Butt is getting a bit long in the tooth No need to be offendec we still believe Bash isthe best shell out there when compared to some other UNIX shells such as Korn Shell (KSH), Shell (CSH) or even TCSH. This tutorial is not about Bash being incapable, but itis about how to breathe completely new life into the shell 0 do old things conveniently and new things which were previously not possible, even byalong shot. So, without further delay, le’ jump in While the Python programming language may require you to write longer commands to accomplish a task (due to the way Python's modules are organised), this s not something to be particularly concerned about. You can easily write aliases to the equivalent of the Bash comimand that you intend to replace. Most of the time there will be more than one way to do a thing, but you will need to decide which way works best for you. Python provides support for executing system commands directly (ia the os or subprocess module) but where possible we will focus on Python-native implementations here, as this allows us to develop portable code. SECTION 1: Completing basic shell tasks in Python 1. File management The Python module shutil provides support for file and directory operations. It provides support for file attributes, directory copying, archiving etc. Let’s lok at some of its important functions. shutil module Replace your shell with Python copy (sre,dst): Copy the src file to the destination directory. In this mode permissions bits are copied but metadata is not copied. copy2 (sre,dst): Same as copy() but also copies the metadata copytree(src, dstl, symlinks=False[, ignore=None]]): Thisis similar to cp-r,itallows you to copy an entire directory. ignore_patterns («patterns): ignore_patteins isan interesting function that can be used as a callable for copytree(, it allows you to ignore files and directories specified by the glob-style patterns. rmtree(path[, ignore_errors{, onerror]]):rmtree()is used to delete an entire directory. move(sre,dst): Similar to my command it allows you to recessively move a file or directory to a new location Example: I from shutil import copytree, ignore_patterns Il copytree(source, destination, ignore=ignore_patterns(‘*. pyc’, ‘tmp*")) make_archive(base_name, format(, root_dir(, base_dir(, verbose, dry_runf, owner, groupl, logger] JJ: Think of this as a replacement for tay, zip, bzip etc. make_archive( creates an archive file in the given format such as zip, beta, tar, qztar Archive support can be extended via Python modules. Example: I from shutil import make_archive I import os I archive_name = os.path.expanduser(os.path.join(‘~’, “ludarchive’)) I root_dir = os.path.expanduser(os.path.join(‘~’, ‘.ssh’)) B make_archive(archive_name, ‘gztar’, root_dir) ‘/Users/kunal /ludarchive. tar.gz’ 2. Interfacing operating system & subprocesses Python provides two modules to interface with the OS and to manage processes, called os and subprocess, These modules let you interact with the core operating system shell, and work with the environment, processes, users and file descriptors, The subprocess module was introduced to support better management of subprocesses (paalready Work with Python ‘Above Youmay never need 1ouse Bash ‘again, th some deaentes Python modules athand Work with Python Replace your shell with Python in Python andis aimed to replace os system, osspawn?, ospopen, popen2* and commands* modules. os module environ: environment represents the OS environment variables in a string object. Example: import os B os.environ {‘VERSTONER_PYTHON_PREFER_32_BIT’: ‘no’, ‘LC_CTYPE’: ‘UTF- 8’, ‘TERM_PROGRAM_VERSION’: ‘297’, ‘LOGNAME’: ‘kunaldeo’, ‘USER’: ‘kunaldeo’, ‘PATH’: ‘/Systen/Library/Frameworks/ Python. framework/Versions/2.7/bin: /Users/kunaldeo/narvhal/ bin: /opt/Local/sbin: /usr/local /bin:/usr/bin:/bin:/usr/sbin:/ ':/usr/local /bin:/usr/X11/bin:/opt/local/bin:/Applications/ MOTODEV_Studio_For_Android_2.0.0_x86/android_sdk/tools:/ AppLications/MOTODEV_Studio_For_Android_2.0.0_x86/android_sdk/ platform-tools:/Volumes/CyanogerModWorkspace/bin’, ‘HOME’: ‘Nsers/kunaldeo', PSI’: \\D\e[0;32mi\ Wu NeGN\] \ [ef i;34mi\ NANCE NOELIA NS AD NeLAANT (\e(1;37m\\]", ‘NARWHAL ENGINE’: ‘jc’, ‘DISPLAY: ‘/tmp/launch- saLUfa/org.x:@’, ‘TERM_PROGRAM’: ‘Apple Terminal’, ‘TERM’: “xterm-color’, ‘Applle_PubSub_Socket_Render’: ‘/tmp/launch- kOulsP/Render’, ‘VERSIONER_PYTHON_VERSION’: ‘2.7', ‘SHLVL’: ‘SECURITYSESSIONID’: '186a5", ‘ANDROID_SOX’: ‘/Applications/ MOTODEV_Studio_For_Android_2.0.0_x86/android_sdk’,’_’: ‘/Systew/ Library/Frameworks/Python framework/Ver sions/2.7/bin/python’, “TERM_SESSION_ID': ‘ACFE2492-BB5C-418E-804F-84E9CF638506", ‘SSH_AUTH_SOCK’: ‘/tmp/launch-djé"ka/Listeners’, ‘SHELL’: ‘/bin/ bash’, ‘TMPOIR': ‘/var/folders/6s/pgknm&b118737mb§psz8x4z80000 gr/T/’, ‘LSCOLORS': ‘ExFxCxDxBxegedabagacad’, ‘CLICOLOR’: ‘1’, ‘_CF USER TEXTENCODING’: ‘@x1F5:0:0", ‘PWD’: ‘/Users/kunaldeo’, ‘COMMAND MODE’: ‘unix2008"} You can also find out the value for an environment value: Bi os.environt‘HoME"] ‘JUsers/kunaldeo’ Replace your shell with Python putenv(varname,value) : Adds or sets an environment variable with the given variable name and value. getuid() :Retuin the current process's user id getlogin() : Returns the username of currently logged in user getpid(pid) : Retumns the process group id of given pid. When used without any parameters it simply returns the current process id getcwd() : Return the path of the current working directory chdir (path) : Change the current working directory to the given path Listdir(path) : Similar tol, returns list with the content of directories and fle available on the given path. Example: B 0s.1istair(yhomeshomer”) ['.gnome2’, ‘pulse’, ‘.gconf’, ‘.gconfd’, ‘.beagle’, ‘.gnome2_private’, ‘.gksu.lock’, ‘Public’, ‘.ICEauthority’, “bash_history’, ‘compiz’, ‘gvfs’, ‘.update-notifier’, ‘cache’, ‘Desktop’, ‘Videos’, ‘.profile’, ‘config’, ‘esd_ auth’, ‘.viminfo’, ‘.sudo_as_admin_successful’, ‘mbox’, “.xsession-errors’, ‘bashrc’, ‘Music’, ‘dbus’, ‘.local’, ‘.gstreamer-@.10", ‘Documents’, ‘.gtk-bookmarks’, ‘Downloads’, ‘Pictures’, ‘.pulse-cookie’, ‘nautilus’, ‘examples.desktop’, ‘Templates’, ‘.bash_logout’] mkdir(path{, model) : Creates a directory with the given path with the numeric code mode, The default mode is 077, makedirs(path{, model) :Creates aiven path (inclusive ofall its itectories recursively, The default mode is 0777. Example: I import os path = “/home/kunal/greatdir” Hl os.makedirs( path, 0755 ); rename (0ld,new) :The file or directory ‘old"s renamed to “new’ If ‘new isa ditectory, an error willbe raised. On Unix and Linux, new” exists ands afl, it will be replaced silently ifthe user has permission, renames (old,new) : Similar to rename but also creates any directories recessively if necessary. Work with Python Above A screenshot of the Python Gt ‘concale vith cUl oped Work with Python [Above Python previously offereda ‘notebook feature, enabling users to create HL documents where mages code ‘nd mathematical formulae were correct formate Thihassncebeen spt of nt separate but ight hegyate) sevice alle upyter Replace your shell with Python rmdir (path) : Remove directory ftom the path mentioned. lf the path already has files you will need!to use shutilrmatreed) subprocess: call(popenargs, **kwargs) : Runs the command with arguments. (On process completion it returns the returncode attribute. Example: import subprocess [ print subprocess.call(C1s""-1"1) total 3684688 dnx——+ 5 kunaldeo staff 170 Aug 19 01:37 Desktop drve———+ 10 kunaldeo staff 40 Jul 26 08:30 Documents: drve-——+ 5 kunaldeo staff 1700 Aug 19 12:50 Downloads drwe-——@ 127 kunaldeo staff 4318 Aug 19 @1:48 Dropbox drwe———@ 42 kunaldeo staff — 1428 Aug 12 15:17 Library drv———@ 3 kunaldeo staff 102 Jul 3 23:23 Movies dr——+ 4 kunaldeo staff 136 Jul 6 08:32 Music dr———+ 5 kunaldeo staff 170 Aug 12 11:26 Pictures dnrarxt 5 kunaldeo staff 170 Jul 3 23:23 Public -rwxr-xr-x 1 kunaldeo staff 1886555648 Aug 16 21:02 androidsdk. tar drwrxr-x 5 kunaldeo staff 170 Aug 16 21:05 sdk drwr-xr-x 19 kunaldeo staff 646 Aug 19 O1:47 sre rer 1 root staff 367 Aug 16 20:36 unbrel1a@.log ‘STD_INPUT_HANDLE: The standard input device. Initially this is the console input butter. STD_OUTPUT_HANDLE: The standard output device. Initially this is the active console screen buffer. ‘STD_ERROR_HANDLE: The standard error device. Infially this is the active console screen buffer Replace your shell with Python : Work with Python SECTION 2: IPython: a ready-made Python system shell replacement In section 1 we have introduced you to the Python modules which allow you to do system shell related tasks very easily using vanilla Python, Using the same features, you can build a fully featured shell and remove a lot of Python boilerplate code along the way. However, if you are kind of person who wants everything ready-made, you are in luck. Python provides a powerful and interactive Python shell which you-can use as your primary shell. IPython supports Python 2.6 to 27 and 311 to 32. Itsupports two type of Python shells: Terminal based and Qt based. Just to reiterate, Python is purely implemented in Python and provides a 100% Python-compliant shell interface, so everything that you have leamt in section 1 so far can be run inside IPython without any problems. [Python is already available in most Linux distributions. Search your distro’s repositories to look for it In case you are not able to find it, you can also install it using easy_install or PyPl [Python provides a lot of interesting features which makes it a great shell replacement... Tab completion: Tab completion provides an excellent way to explore any Python object that you are working with. tt also helps you to avoid making typos. Example: In [3]: import o {hit tab} ‘obje opcode operator optparse 0s osdemxpath In [3]: import os In [4]: os.p {hit tab} os.pardir —os.pathconf_names _0s.popen _—_ os popen4 ‘os.path os.pathsep_ ‘os.popen2 —_os.putenv os.pathconf os.pipe 0s,popen3 Built In Object Explorer: You can add ? after any Python object to view its details such as Type, Base Class, String Form, Namespace, Fle and Doestring. Work with Python Replace your shell with Python Example: In [28]: 0s.path? Type: module Base Class: String Form: Namespace: Interactive File: ‘/Systen/Library/Frameworks/Python.framework/ Versions/2.1/Lib/python2.7/posixpath.py Docstring: Common operations on POSIX pathnames. Instead of importing this module directly, import os and refer to this module as os,path. The ‘os.path’ name is an alias for this module on POSIX systems; on other systems (eg Mac, Windows), os,path provides the same operations in a manner specific to that platform, and is an alias to another module (eg macpath, ntpath). Some of thiscan actually be useful on non-POSX systems 100, eg for manipulation of the pathname component of URLs. You can also use double question marks (22) to view the source code for the relevant object. Magic functions: Python comes with a set of predefined ‘magic functions’ that you can call with a commane/-line-style syntax. Python ‘magic’ commands are conventionally prefaced by %, but ifthe flag Sbautomagic is set to on, then you can call magic commands without the %, To view a list of available magic functions, use ‘magic function 9élsmagic. They include functions that work with code such as 96run, %edit, Yomnacro, %recall etc; functions that affect shell such as %colors, Sixmode, %autoindent etc and others such as Goreset, 9atimeit, Sepaste etc. Most cool features of [Python are powered using magic functions. Example: In [45]: SSlsmagic Available magic functions: alias Yeutocall ‘autoindent Xautomagic bookmark od Yeolors ‘%cpaste Ydebug %dhist %dirs Xdoctest_mode ted Yedit Yen Yui %hist history ‘%install_default_config %install_profiles ‘load_ext Xloadpy logoff %dogon Glogstart Wogstate Yogstop xlsmagic %nacro Ynagic Replace your shell with Python page paste Ypastebin Ypdb Ydef %pdoc %file %pinfo %pinfo2 Ypopd %print %precision %profile %prun Ypsearch Y%psource %pushd ud Spycat Ypylab YquickreF recall Yehashx %reload_ext rep rerun %reset freset_selective trun Ysave Ysc Ysx Mtb wine xtimeit unalias %unload_ext %ixho %ho_ls hos %xdel mode Automagic is OFF, % prefix S needed for magic functions. To view help ‘on any Magic Function, call %6somemagic? to read its docstring, Python script execution and runtime code editing: You can use run torunany Python script. You can aso controlrun the Python script with pdb debugger using -d, or pdn profiler using-p. You can also edit a Python script using the 9éedit command which opens the given Python script in the editor defined by the SEDITOR environment variable. Shell. command support To just run a shell command, prefix the command with ! Example: In [5 tps PID TTY TIME CMD 4508 ttysee 0:00.07 -bash 84275 ttys@0L 0:00.03 -bash 17958 ttys@02 0:00.18 -bash In [8]: !clang prog.c -o prog 5 warning: type specifier missing, defaults to ‘int’ E-Wimplicit-int] main() 1 warning generated. Qt console : Python comes with a Qt-based console. This provides features only available in a GUI, lke inline figures, multiline editing with syntax highlighting, and graphical calltips. Start the Qt console with: Is ipython qtconsole FFyou get entors about missing modules, ensure that you have installed dependent packages ~ PyOt, pygments, pyexpect and ZeroMO. Work with Python Conclusion tear Work with Python What you'll need... NumPy SciPy wuwwiicipyorg Matplotib Scientific computing with NumPy Scientific computing with NumPy erful calculations with NumPy, NumPy i the primary Python package for performing scientific computing It has a powerful N-dimensional array object, tools forintegrating C/C++ and Fortran code, linear algebra, Fourier transform, and random number capabilities, among other things. NumPy alo supports broadcasting, which isa clever way for universal functions to deal in a meaningful way with inputs that do not have exactly the same form. Apart from its capabilites, the other advantage of NumPy is that it an be integrated into Python programs. In other words, you may get your data from a database, the output ofanother program, an external file or an HTML page and then process it using NumPy, This article will show you how to instal NumPy, make calculations, plot data, read and write extemal files, and it wil introduce you to some Matplotlip and SciPy packages that work well with NumPy, NumPy also works with Pygame, a Python package for creating games, though explaining its use is unfortunately beyond of the scope of this article. Itis considered good practice to try the various NumPy commands inside the Python shel before putting them into Python programs. The examples in this article use either Python shell or Python. “Apart from its capabilities, the other advantage of NumPy is that it can be integrated into Python programs” Scientific computing with NumPy, Work with Python ‘Asimple Python Matploti program for generated output Polynomial Fitting Abython script Finding help ‘that uses SciPyto iseasy processan image Installing Num I> 1 B33), 9" mPy 1. 1-85.41, Notonly haveyoufoundthenumey if ion ) 0 Most Linux dstiibutions have a ready t0-install package you can Use. After installation, you can find out the NumPy version you are using by executing the following: Is python Python 2.7.3 (default, Mar 13 2014, 11:08:55) BH (ccc 4.7.2) on Linuxe ype “help”, “conyrii “credits” or “License” for mmore information. >>> numpy.version.version B traceback (most recent call last): Fille “”, Line 1, in [ Nametrror: name ‘nunpy’ isnot defined [>>> import numpy > numpy.version.version B62 version but you also know that NumPy is properly installed. About NumPy OD Dee tssmistenare NumPyis apowerful Python package thatis mainly for working with araysand matrices. There ae many ways to create an array but the simplest ones to make use ofthe array function B >> one = array(t1,2,3,40) The aforementioned command creates a one-dimensional array. |f you want to create a two-dimensional aay you can use the aray0 function as follows: [>> too = array(€ [1,2,3), You can also create arrays with some more dimensions. Making simple calculations using NumPy OZ emerson Yyou can find the minimum and) ‘maximum valuesin itby executing the following commands >>> myArray.minQ) BE > nyarray.maxQ) Should you wish to find the mean value ofall aay elements, yourcan un the nextcommand BH >> mydrray.meanQ) Simian youcan find the median ofthe Work with Python array by running the following Python commends H > mediantnyarray) ‘The median value of asetis an element that divides the data set into two subsets (eft and right subsets) with the seme number of elements. the data set has antodd number of elements, then the mecian is part of the deta ser. On the other side, ifthe data set has an even number of elements, then the medianis the mean value ofthe two centre elements ofthe sortad data set. Using arrays with NumPy O4erer:: ‘only embraces the indexing methods used in typical Python for strings and lists but alo extends them. Ifyou want t0 select a given element from an array, you can use the following notation: BH >>> twodft,21 You can abo select a part of anarray @ slice) using the following notation: B>>> two0E1,1:3] Finally, you can convert an array into a Python list using the tolist@ function, Scientific computing with NumPy Reading files OS earesyontonenst extracted information from an Apache log file using AWK andl you now want to go and process the text file using NumPy. The following AWK code finds out the total number of requests per hour: Is cat access.log | cut dl ~f2 | cut -d] -fl | awk -F: print $2Y | sort -n | unig -c | awk ‘{print $2, $1}' > time. txt “The format ofthe tex file timeN.b«t) with the datais the following: B00 191 Bot 25 Boa iz Hos 104 Reading the timeNoxtfile and assigning itto a new erray variable can bedone as follows: Baa = np.loadtxt(“timeN.txt”) Writing to files 0 Writing variables toa file is largely similar to reading “When you apply a function to an array, the function is automatically applied to all of the array elements” a file. If you have an array variable named ail, you can easily save its contents into a file called al txt by Using the following command: Bn a7: aal) np-savetxt(“aal.txt”, AAs you can easily imagine, you can read the contents of aaltxt later by Using the load) function. Common functions OZ Mrezsneetsmeny numerical and statistical functions. When you apply a function to an array, the function is then automatically applied to all of the array elements When working with matrices, you Can find the inverse of a matrix AR by typing “AAI”. You can also find its eigenvalues by typing ‘np linalg, eigvals(AAy" and its eigenvector by typing ‘np inala.eig(®B’ Working with matrices 08% special subtype of @ twwo- dimensional NumPy array is a matrix, A matixis like an array except that matrix multiplication repiaces element-by-element multiplication. Matrices are generated using the matrix or mat function as follows: Win (2): Aa ayia. np.mat(@ 1 1; 1 Scientific computing with NumPy, Work with Python imtsouk — mtsouk@mail; ~/docs/article/working/NumPY.LUD/var — ssh — 9045 | mtsouk@mait:~|__mtsouk@omail ~./NumPY.LUD /var Perec anr bers correaet ree rset trae Cerra EYAC rere trp rsoes Perrine eens eer Die aCir nie MTom Ce uci blt fonts-lyx gir1.2-glib-2.0 Libgirepository-1.0-1 Libglade2-0 python-cairo DRS he a aie ee sae gies ee need Siro itrat sets ciesy cine tr ei rons ar rae Err crs eee ee net a ee staan eer eens ge ae eet ise ear iey eceeet ted imc a a catceet Mn stem coer eet Mets Sotto Est ere eer acca eG Met A Re etc me emcee Myint) Sete ete tte estes rer saat) Seat ere eles re ele et eee re eran ied @ upgraded, 17 newly installed, @ to remove and @ not upgraded. Ree eoiere Cea eget After this operation, 31.3 MB of additional disk space will be used. Do you want to continue [¥/n]? Y CSUs eee CI Osean ay Un eee eee Sere ery Ree eS an 7 Ue artes eee RSE RST Rae eC Sea ren STURT erence eer eer cecl Ca) COM see ROS oS Wary LUN eee eee ee ere ee Cerne Ree ean esr at ee Umer eer eee ee http://ftp-us.debian.org/debian/ wheezy/main python-cairo and64 1.8.8-1+b2 [84.2 kB] Perna. Re SPUR ICY SPL an rev rine ena ne a Recerca) DSA UU OSA oun ee aL eee ay Rt ag Re CSU CSCW aa en es eee ee eee CLE a’ OS a OS CUR CSCW oyun Lee ee SES Coe a Tc OCU OSes un ue eae ee Cae) kB) CaaS ae a CSCO Seas Un ie coat ee ee a] Caren eT Ae Cu Loe oun Te Cate ee ae eee io ac CaN Coe Tae SC Oca ue es eee Ie eas aa) Cee eRe CoC OCA un eee eo tros e} CSRs Wace OCU LE Sea un Lue aL eee es Cag md or} Get:17 http://ftp-us-debian.org/debian/ wheezy/nain python-tk and64 2.7.3-1 [50-9 kB] You can add matrices named AA anc 2pendencies that you should: FeO A Ee rt itamenowtopceapamema "THY the various Plotting with Matplotiib —frsnungiwawge ™* ~— NumPy polyremilaethe folowing commands inside QO rictorcatmapons — inort numy as op the Python shell” Asyoucan see, Matplotits has many ‘It import matplotlib.pyplot Work with Python as plt H nyPely = np.polytd(n. array(3, -1, 1). astype(Float)) Ix = np.linspacecs, 5, 120) By = mpoly B ptt.xtabel('x values’) B ple ylabel(‘f@) values’) I xticks = np.arangeCs, 5, 10) Hyticks = np.arange@, 100, 10) B plt.xticks(xticks) I plt.yticks(yticks) B plt-grid(true) B pit plote.») ‘The variable that holds the polynomial is myPoly. The range of values that will be plotted for xis, defined using *x = nplinspace-5, 5, 100)" The other important variable sy, which calculates and holds the values off foreach x value. Itis important that you start python using the ipython —pylab=ot" parameters in order to see the output on your screen. Ifyou are interested in plotting polynomial functions, you should ‘experiment more, as NumPy can also calculate the derivatives of a function and plot multiple functions in the same output. About SciPy 1 SciPy is built on top of NumPy ands significantly more advanced than NumPy. It supports numerical integration, optimisations, signal processing image and audio processing, and statistics. For reference, the example below uses just “For plotting polynomial functions, experiment more” Scientific computing with NumPy cone small part ofthe scipystats package about statistics, I in (361: from scipy.stats import poisson, lognorm Hin (37): mysh = 10; Hin (381: mytu = 10; Bin (39): In = Jognorm(mySh) Din [42]: p = poisson(myMu) Bin Gu: Inrvs(cie,)) Bout: H array(l_9.20303114e- 02, 1.18957e68er21, 9.78411983e+01, 8, 263707346~ er, §.644514410~-03, 4.617440550-29, 4.98471222e~ 6, 1.45947948e102, 9, 25502862e-06, 5,87353720e-02)) Bin 02%: parvscce,y Houta: orrayit12, 11, 9, % 9 1, 9 4, 13, 8) Bin (23): In.paf(3) BE ovtraai: 6.013218067177522842 The example uses two statistics distributions and may be difficult to understand, but itis presented in order to give you a better taste of ScPy commands Using SciPy for image processing 1 Now we will show you how ‘to process and transform a PNG image using SciPy. The most important part of the code is the following line Bi image = np.array(Inage. open(‘SA.png').convert(L")) This ine allows you to read a usual PNG fle and convert into a NumPy array for adcitional processing. The program wil also seperate the output into four parts and displays a cifferent image for each of these four parts. Other useful functions 12 [tis very useful to be able to find out the data type of the elements in an arrayrit can be done Using the dtype( function. Similarly, the ndim( function returns the number of dimensions of an array. When reading data from external files, you can save their data columns into separate variables using the following method: With (ie): aat,aa2 = Scientific computing with NumPy Work with Python ° . . . . alolol+|+| | ‘Above iting Proms np.loadtxt(“timeN.txt”,, usecols=(@,1), unpack=True) ‘The Python script uses afithdegree should know thataray broadcasting polynomial, but ifyou want to use a thas a rule:in order for two arrays to ‘The aforementioned command saves _different degree instead then you only _be considered for array broadcasting, column 1 into variable aal and column into variable aa2. The “unpack=True” allows the data to be assigned 10 two different variables, Please note that the numbering of columns starts with 0. Fitting to polynomials 1 ‘The NumPy polyfit() function tries to fit a set of data points t0.a polynomial The data was found from the timeNtaxt file, created earlier have to change the following line: I coefficients = np.polyfit(aat, 202, 5) Array broadcasting in NumPy TA ecosveniakror about ‘array broadcasting because it isavery useful characteristic. Fist, you “the size ofthe talling axes for both arraysin an operation must either be the same size or one of them must be one” Put simply, array broadcasting allows NumPy to change" the dimensions of an array by filing it with data in order to be able to do calculations with another array. Nevertheless, you cannot stretch ‘both dimensions of an array to do your jab. Work with Python What you'll need... hon-devel Python development libraries required fercompiingthed party Python setuptools Setuptoolsallowsyou to download, build install, upgrade, and uninstall Python packages ith ease Python for system administrators Python for system administrators Learn how Python can help by daring to replace the usual shell scripting ‘System administration is an important part of our computing environment. It does not matter whether you are managing systems at your work ourhome. Linux, being a UND-based operating system, already has everything a system administrator needs, such as the world-class shells (hot just one but many including Bash, sh, sh etc), handy tools, and many other features which make the Linux system an administrators dream. So why do we need Python when Linux already has everything builtin? Being a dynamic scripting language, Python is very easy to read and learn. That's just not us saying that, but many Linux distributions actually use Python in core administrative parts. For example, Rec Hat (and Fedora) system setup tool Anaconda fs written in Python (tead this line again, got the snake connection?) Also, tools ike GNU Maman, CompizConfig Settings Manager (CCSM) and hundreds of tity GUI and non-GUI configuration tools are writen using Python Python does not limit you on the choice of user interface to follow — you can build command-line, GUI and web apps using Python. This way, it has got covered almost al the possible interfaces. Here we will ook into executing sysadmin-telated tasks using Python. Parsing configuration files Configuration files provide a way for applications to store various settings. In order to write a script that allows you to modify settings of a particular application, you should be able to parse the configuration file of the application. In this section we learn how to parse INbstyle configuration fils. Although old, the INI fle format is very popular with much modem open source software, such as PHP and MySQL. Excerpt for php.ini configuration file: Lr 1 engine = On Python for system administrators I] zend.ze1_compatibility_mode = off short_open_tag = On I asp_tags = off precision = 14 I yak_compliance = on I output_buffering = 4096 joutput_handler = I ziib.output_compression = off Boys I]; Atiow or prevent persistent Links. I mysql.allow_persistent = On I mysqi.max_persistent = 20 mysql.max_links = -1 Bl mysql.default_port mmysql.default_socket I nysql.default_host = localhost B mysql.connect_timeout = 62 I mysql.trace_mode = off 3306 Python provides @ builtin module caled CConfigParser (known as configparser in Python 300) You can use this module to parse and create configuration files. @coder witeconfigpy @description: The folowing demonstrates adding MySQL section to the phpinifie @warning: Do not use this script with the actual ohp. ini file, as it’s not designed to handle all aspects ofa complete phpini file I import configParser Il config = ConfigParser.RawConfigParser() I config.add_section(‘MysQv’) config. set(‘MySQL;,’mysql.trace_mode’,’OfF") T contig. setmysqu’mysql.connect_ timeout’,’60") E contig. setmysgu’,’mysql.default_ Work with Python host?, localhost’) I config. set (‘MySQl’,’mysql.default_ port,'3326") I config. set(‘MySQU,’nysql.allow_persistent’, ‘On’ ) B contig. set MysQu,’mysal max persistent’,’20") ‘ith open(‘php.ini’, ‘ap") as configfile: I config.write(configfile) HE output:php.ini B oysaa mysql.max_persistent = 20 | mysql.allow_persistent = On mysql.default_port = 3306 I nysqi.default_host = localhost I nysal.trace_node = off H nysqi.connect_timeout = 69 I exode: parseconfig.py I exescription: Parsing and updating the config file I inport configrarser sonfig = ConfigParser.ConfigParser() I config.read¢‘php.ini’) I print config values E print config. get(mysgv, mysql .default_ host’) [print config.get(mysqu,’mysal.default_, port’) I config. remove_option('MysQU’mysql.trace_ mode’) [with open¢php.ini’, ‘wb’) as configfile: config.write(configfile) Parsing JSON data JSON (also known as JavaScript Object Notation) isa lightweight moder data-interchange format. JSON is an open standard under ECMA262. Is a text format Work with Python and is completely language-independent. JSON is ‘also used as the configuration file format for modem applications such as Mazila Firefox and Google Chrome. JSON is also very popular with modem ‘web services such as Facebook, Twitter, Amazon EC2 etc In this section we will use the Python module ‘simplejson’ to access Yahoo Search (using the Yahoo Web Services AP), which outputs JSON data. To use this section, you should have the following: 1. Python module: simplejson. Note: You can install Python modules using the command ‘easy_instal module narne>! This command assumes that you have @ working internet connection. 2.Yahoo App ID: ‘The Yahoo App ID can be created from httpsi/ developerappsyahoocom/dashboard/createkey. html The Yahoo Apo ID willbe generated on the next page. See the screenshot below for detals. simplejson is very easy to use.In the following example we will use the capability of mapping JSON data structures ditectly to Python data types. ‘This gives us direct access o the SON data without developing any XML parsing code. JSON PYTHON DATA MAPPING number (real) Python for system administrators For this section we will use the simplejson load function, which allows us to deserialize a JSON object into a Python object. Il ecode: LuDsearch.py I import simplejson, urllib BD app_ip = ‘xxxxxxxx’ # Change this to your APP ID II searcH_Base = ‘http://search-yahooapis. com/WebSearchSer vice/VI/webSearch? Il class YahooSearchError(Exception): BD pass I def search(query, results=20, start-1, #+kwargs): kwargs.update({ ‘appid’: APP_ID, ‘query’: query, ‘results’: results, ‘start’: start, ‘output’: ‘json’ I I I D I url = SEARCH_BASE + ‘2’ + urllib. urlencode(kwargs) I result = simplejson.load(urllib. urlopen(url)) I if ‘Error’ in result: I # An error occurred; raise an exception I raise YahooSearchérror, result{'Error’] return result(‘ResultSet"] Let's use the code lsted aboove fiom the Python shell to see how it works. Change to the directory where you have saved the LUDYSearchppy and open a Python shell Bl code: Python Shell Output. Lines Python for system administrators Work with Python So, you want to use some Yahoo! APIs... ‘About your application Appicton Mame: CUDPYSSGRR rang ot appueation Description content = Te - ig "Abo demonstra te JSON parsing usig Pyro 200 charactors ess Favicon URL: [ip Ten sta Son ROTA GT Optra sp0cfy @ URL 08 10:16 JPG, PNG or GIF og, Security & Privacy ‘Yahoo! APIs use the OAuth protec er secure valkoton of AI usage and and ser aunenticaton needed ‘Access Scopes: @ Ths app wiley access ple APs, Web Services, or RSS feds. {© Ths aon roqites access to pve ser data Contact information Justin case someting comes up and we ned ogo hol of you») Terms of Use: fave rod ns apo tthe Vahoo! Devetpar Network Tem of Ube. tances [love Generating the Yahoo App starting with ‘>>>’ indicate input I >> exectilec-Lupysearch.py”) I >> results = search(‘Linux User and Developer”) I >> resultsf‘totalResultsavailable’] I 123000000 I] >> results(‘totalResultsReturned’] 20 I >> items = results{'Result’] >>> for Result in items: print Result{‘Title’],Result(‘Url’] Linux User hrtpy/wwwlinuxuser.co.uk/ Linux User and Developer - Wikipedia, the free encyclopedia http/enwikipediacrg/wiki/Linux User_and_Developer Linux User &amp; Developer | Linux User httpx// wowwdlinunauser fin lope Gathering system information An important job fora system administrator is gathering system information, Here we will use the SIGAR (System Information Gatherer And Reporter) API to demonstrate how we can gather system information using Python. SIGAR is a very complete AP! and can provide lots of information, including: 1.System memory, swap, CPU, load average, uptime, logins. Work with Python 2.Per process memory, CPU, credential info, state arguments, environment, open files. 3.File system detection and metrics. 4, Network interface detection, configuration info and metrics. 5.TCP and UDP connection tables. 6.Networkroute table. Installing SIGAR The first step is to build and install SIGAR. SIGAR is hosted at GitHub, so make sure that you have Git installed in your system. Then perform the following steps to install SIGAR and its Python bindings: Is git clone git://github.com/hyperic/ sigar.git sigar.git Is cd sigar.git/pindings/python I$ sudo python setup.py install Atthe end you should see @ output similar to the following \Witing /us/1oca\/ibpython26/dlist packages/ pysigar-O.1.egg-info SIGARisa very eesy-to-use library and can be used to get information on almost every aspect ofa system. The next example shows you how to do this. The following code shows the memory and the fle system information, I ecode: Pysysinfo.py I import os I import sigar sg = sigar.open() B mem = sg.mem() sg.swapQ) 3g.file_system_listQ —=======sMemory I print “\tTotal\tusec\tFree” B print “em:\t”\ Python for system administrators I (mem.total() / 1024), \ (nem.used() / 1024, \ Bs @emsreeQ / 1024) B print “Swat, \ EB — Gwap.totalQ / 1024), \ BH Gvap.usedQ / 1024), \ (swap.freeQ) / 1024) B print rant”, mem.ramo, “¥8” I return sigar.format_size(size * 1024) I print ‘Filesystemtsize\tUsed\tavail\ tUse&\tMounted on\tType\n’ I for fs in fslist: dir_name = fs.dir_name() BH usage = sg.file_systemusage(dir_ name) ‘total = usage.total() used = total - usage.free() avail = usage.avail() pct = usage.use_percent() * 100 if pet = 00: pet =~ print fs.dev nameQ, format_ size(total), format_size(used), format_ size(vail),\ pet, dir_name, fs.sys_type_ name(), ‘/’, fs.type_name() B eoutput snory Information I Total Used 8388608 6061884 2326724 131072 16048 115024 8192 MB =File System Free Informatic DFitesysten Size Used. Avail Use% Mounted on Type Python for system administrators I /dev/disk@s2 300G 175G 1246 59.0 / hfs / local Hdevfs 191k 191k 0 none - /dev devfs / Accessing Secure Shell (SSH) services SSH Gecure Shell is a moder replacement for an cold remote shell system called Telnet. It allows data to be exchanged using a secure channel between two networked devices. System administrators frequently Use SSH to administrate networked systems. In addition to providing remote shell, SSH is also used for secure file transfer (using SSH File Transfer Protocol, cor SFTP) and remote X server forwarding (allows you to use SSH clients as X server). In this section we will eam how to use the SSH protocol from Python using a Python module called parariko, which implements the SSH2 protecol for Python. paramiko can be installed using the following steps: Is git clone https://¢ithub.com/robey/ paramiko.git $ cd paramiko I $ sudo python setup.py install To the core of paramiko is the SSHClient class. This dass wraps L{Transport}, L{Channe}, and LISFTPClient ‘to handle most of the aspects of SSH. You can use. SSHClient as: Hl client = ssHclientQ. client Joad_system_host_keys() II client.connect(‘some.host.com’) II stdin, stdout, stderr = client.exec command(‘dir?) The following example demonstrates a full SSH cient written using the pararmiko module. I ecode: pyssiclient.py Work with Python IL import base64, getpass, os, socket, sys, socket, traceback I import paramiko I import interactive Is setup logging E paramiko.util.log_to_file(‘demo_sinple. Jog’) Bs get hostname hostname = sys.argv(1] if hostname.find(‘@’) >= @ username, hostname = hostname. split(‘e") else: hostname = raw_input(‘Hostname: *) if len(hostname) print ‘%* Hostname required.’ sys.exit(1) port = 22 if hostname.find(':’) >= hostname, portstr split(’:” port = int(portstr) get username I 1 I I I ! I if username = ! I I I I default_username = getpass.getuser() username = raw_input(‘Username [%s]: ‘ % default_username) if len(username) == @: username = default_username password = getpass.getpass(‘Password for %s@%s: ‘ % (username, hostname) # now, connect and use paramiko Client. 1 to negotiate SSH2 across the connection try: client = paramiko.SsHClient() HB client.toad_system_host_keys() I client.set_missing_host_key_ policy(paramiko.WarningPolicy) Work with Python print ‘ee Connectiny client.connect(hostname, port, username, password) chan = client.invoke_shellQ) print repr(client.get_transport) print ‘t% SSH Server Connected! wee! print interactive.interactive_shel1(chan) chan.close() client.close() except Exception, e: print ‘% Caught exception: %s: %s' % (@._-class__, © ‘traceback.print_exc() try: client.close() except: pass sys.exit(1) Torunthis code you will so need a custom Python class interactivepy which implements the interactive shell for the SSH session. Look fortis file on FileSio and copyit ito the same folder where you have created PySSHClientpy. B ecode_utput BE kunateubuntu-vm-kdeo:~/sre/paramiko/ demos$ python demo_simple.py B Hostname: 192.168.1.2 BI Username [kunal]: luduser I password for luduser@192.168.1.2: IJ «« connecting... I me ssh Server Connected! s+ B Last login: thu Jan 13 @2:01:06 2011 from 192.168.1.9 Python for system administrators Besa ifthe host key for the SSH server is not added to your SHOME/Ssh/known_hosts file, the client wil throw the folowing error I +++ caught exception: : unbound method missing_ host_key() must be called with WarningPolicy instance as first argument (got SSHClient instance instead) This means that the client cannot verify the authenticity of the server you are connected to. To ‘add the host key to known_hosts, you can use the ssh command, Its important to remember that this isnot the ideal way to add the host key; instead you should use ssh-keygen. But for simplicity sake we are using the ssh dient. I kunateubuntu-vm-kdeo:~/.ssh$ ssh luduser @192.168.1.2 I the authenticity of host ‘192.168.1.2 (192.168.1.2)" can’t be established. Hl Rss key fingerprint is be:01:76:6a:b9:bb:6 9:64:€3:dc:37:00:24:36:33:d1. Dare you sure you want to continue connecting (yes/no)? yes [ Warning: Permanently added ‘192.168.1.2° (RSA) to the List of known hosts. So now youve seen just how easy it can be to carry cout the complex sysadmin tasks using Python's versatile language. Asis the case with all Python coding, the code that is presented here can fairly easly be adopted into your GUI application (using software such as PyGTK (or PyQ) ora web application (using a framework such as Django or Grok) Python for system administrators Writing a user interface using Python Re ere een ere tn ne eee Meee eg rns etvere rere tetera Ceyet aay er eee eet seed ee eee a peers. area eee a eee re tie en ea eee entre a application and will use the Python module snack 'to facta geste ee Lene eli ecoa aes) CC reetnig ened ae eee xdingand wrting grubpy. GRUS Config Fle Qrubconf Parse eee eae a at See Meera eee cin Cmca eet en Mey et) eet Cea | eo Ree eo From grub inport (readBootD8, writeBootFile) | Chane ee uc OES mE sr Coon tomer Seem eed Prey ears | eee) | nor 0) | toner tee i Peers) i eteteee ee mer) returéxit= ee ccacey en Prune) Sect Coote) ace Tea) ec acorn enon Toe O)) CeCe a cram) perssl ares aCe Dy Work with Python Fern Peery erence) Fee ON Perey} poe On) Perera) peer re) if bbbuttonPressediresult) = ‘cancel Seeatae) Rant) Crd Camo EEC 0) oy Cer ccren ota) break Eee atesae coats Cece pour) Roe arte) cone) See tc wali} tee a Le anny Work with Python What you'll need... Beautiful Soup Beoutfusoup! HTMLSLib tris python Python 2.6+ & WikiParser. zip Six ital Lan CS Scrape Wikipedia with Beautiful Soup Scrape Wikipedia with Beautiful Soup Use the Beautiful Soup Python library to parse Wikipedia's HTML and store it for offline reading In this tutorial well use the popular Python library Beautiful Soup to scrape Wikipedia for inks to articles and then save those pages for offline reading, This s ideal for when travelling or in a location with a poor internet connection. ‘The plan is simple: using Beautiful Soup with the HTMLSLib Parser, wee going to load a Wikipedia page, remove all of the GUI and unrelated content, search the content for links to other Wikipecia articles, and then, after a tiny bit of modification, write them toa file. Even though it's now the de facto knowledge base of the world, \Wikipecia isn't great when it comes to DOM consistency — thats IDs and classes are sometimes quite loose in their usage. Because of this, we will also cover how to handle all of the excess bits and bobs of the Wikipedia GUI that we don't need, as well as the various erroneous links that won't be of much use to us. You can find the CSS stylings sheet and a Python script pertaining to this tutorial at http//bit ly/T9MibBy, Install Beautiful Soup & HTMLSLib OTe en atinting cede weed totale tare vel be ng for the program (Beautiful Soup, HTMLSLI5, Six). The installation pxocessis fatty standart grab the libraries from thelr respective links, then unzip them. in the terminal, enter the unzipped directory and run python setup.py instal for each library. They will now be ready for use “Wikipedia isn't great when it comes to DOM consistency” Scrape Wikipedia with Beautiful Soup Work with Python Full code listing | Importtibraries inport 0s, sys, urllibe, argparse, detetine, atexit ‘These ae the fron bs4 import BeautifulSoup Iibrares we are ~ aairesses = 0 going to be using ddeepestiddresses = (1 forthisprogram axtevel = 1 Storefolder = “Wikistore “ + str(@atetine.datetine.now().strfeine(“KY kart th:tt9) undesirables = { {‘elenent™ : “table", “atte” : ('class’ : ‘infobox'} }, (element “table”, “attr” : (‘class' : ‘vertical-navbox')}, {“element” : “span, “attr” : {‘class’ + tmi-eGitsection')}, {‘elenent™ : “civ", “attr” : (class! : ‘thunb"}}, (elenent” Sup", “attr” + (lass! : ‘reference'}}, {elenent” 1 "div", “attr® : Class’ ‘eeflist'Wh, (lelenent” : “table”, “attr” + (‘elass" 1 ‘nowraplinks')), Celenent™ + 2Setup variables stable’, “atte” + {'elass" + ‘anbor-Refimprove'y}, (Celement™ : "ing", “atte” + None, ‘These ae some Creamen 5 script, att : Norm, Clement”: table Stir”: Clase ‘ “nbox-snall’)) , (Celenont” : “span”, “aetr” + (4id” 1 “coordinates*)), Celenent” + vaileswetie | ato sate «(eelos™ = “anbor-phar, feleeen= vy are Cela: puackofthe ——L snsinarticle”)), Celenent” : Hone, “attr” : {*id" : "References" 1 scripts progress Foor init. Parser = argperse.ArgunentParser(description="iandle the starting page and nunber of levels we're going to scrape") parser.add_argument('-UR’, dest~'link’, action-'store’, help-'The Wikipedia page from which we will start screping") parser.add_argunent(‘“levels', dest-"levels", action-'store’, help-'How many levels deep should the scraping 50") args = parser-porse.aras%) 3 Intialisation Thisistheintislisng Nleresdevels t= yon function that we slobal maxLeve an maxLevel = int(args.levels) theinputcoming sf (orgs. Link = Nene) from the user Drint(*You need to pass a link with the -URL flag S98 045200) else Lf not 08.path.exists(storerolder): os. nakedirs(storeFalder) srabPage(oras.link, 0, args Link spit(*wiki/91.strip@. replace", * 9) Latexit.resister(cteanvs) def isValidL ink(hink): if “/wiki/" In Link and “:" aot in Link and “http://" not in Link and “Wikibooks” ot in link and “a” not in link and *wikiquote” not in Link and “wiktionary” not in Link and “wikiversity” not in Link and “wikivoyage” not in Link and “wikisource” not Jn Link and “wikinews” not in Link and “wikiversity” not in Link and “wikidata” not in link: return True else: return False def grabPage(URL, level, name): ‘opener = urllib?.build_opener() ‘opener.addheaders = [CUser-ayent', “Mozilla/5.0")] req = opener.open(URL) Work with Python Fn Scrape Wikipedia with Beautiful Soup Creating some useful variables 0: These vatablesilleentackof the inks weve acess while the cpt has been running: addresses is alist containing every ink we've accessed deepestfddresses are the links of the pages that were the furthest down the link tree from cur starting point; storeFoderis where we will ave the HTML files we create and mast evel isthe maximum depth that we can follow the links to from our starting page. Handling the user's input 03 Inthe frst few lines ofthis function, wete just creatinga helper statement Afterwards, we'e parsing ary arguments passed into the program on ts ‘execution and looking for a-URL flag anda -levels flag, The -levels flag is optional as wealresdy have a preset depth thet well folow the links to, but we need alink to start fromm so if the -URL flag missing, well prompt the user and exit. five have link, thenwe quickly check whether or notwe have a directory to storefles in— which \well create if we donit—anc then well fe off the function fo get that page. Finally, we register handler for when the script tres to ext. Well gett thatit later. Retrieving the page f from the URL. 0. Here we'e using URLLib? to request the page the the user has asked for ‘and then, once we've received that page, we're going to pass the content through to Beautiful Soup with the soup variable. This gives us access to the methods weite going to call as we parse the document. Trimming the fat 0 Wkneda has alot of nodes that we dort want to parse. The content vatiable allows us to straight away ignore most of Wikipedias GUI, but there are sil lots of elements that we don't want to parse. We remedy this by iterating through the ist ‘undesirables’ that we created earlier on in the document, For each different divsection/node that we don't want, we call Beautiful Soup's find_all) method and use the extract() method to remove that node from the document. At the end of the undesirables loop, most of the content we don't \want any more will be gone. We also look for the ‘also’ element in the Wiki page. Generally, everything after this dlv is of no use to us. By calling the find_all_next0) ‘method on the also node, we can geta lst of every other element we can remove fiom that point on. “The HTML page uses builtin browser styles when rendering the page” Scrape Wikipedia with Beautiful Soup : Work with Python “Wikipedia has so many different services that interlink with 4Get the page Herene gab the page we wont to stove and remove the bitsofthe ocument we onitrees 5 Check links. Then wee iterate through allof the
    tagsand check ifthere’sa vali ink ooanepoe OS wean grab, and tweak them for our own use @ each other; we don't want to grab those pages” page = req.read) req.close() soup = BeautifulSoup(page, “hemlSlib”, fromencoding="UTF-8") content = soup.find(id="nm-content-text”) if hasattr(content, “find_all"). global undesirables for notWanted in undesirables: removal = content.find_all(notWanted[‘element'], notWantedt'attr']) AF Len(renoval) > 2: for el in renoval: el.extract0) also = content.find(ide"See. also ifG@lso I= None): also.extract() tail = also.find_all_nextO) sf(len(tail) > ©: for element. in tail: elenent.extract() for Link in content.Find_all(‘a') href = Linkt*href") if isValidLinkchref), Tee 7 hea if Level < masLevel: stored = False; for addr in addresses: if addr == Link.get(*hre' ‘stored = True iffstored == False): title = Link. get(‘hret’).replaceC/wiki/”, °") addresses.append(str(title » “htnl")) erabPageChttp://en wikipedia.org” + link.get(hret’), level + 4, title) print title Link(‘href"] = Linkthref".replace(’/wiki/, ") + “hemi” fileName = str(name) if level == maxLevel: deepes taddresses.append(FileNane.replace(’/’, FA Work with Python Scrape Wikipedia with Beautiful Soup Beautiful Soup Documentation ‘ew ct ar a ng hart san hea tg hone. at cane) Getting help ‘te aonb So ion. err comin pos fmsmminna peg ANT rer a nt Quick Start wean} seme engage oi onset ate a Ae nH eof Soup tO Grabbing the links 06” calling content find_all(a) we get a lst of every in the document. We can iterate through this and check whether or not there isa valid Wikipedia link in the 's href. tthe link sa valid link, we Quickly check how far down the link tree we are from the original page. If we've reached the maximum depth we can go, welll store this page and call it quits, othenwise well start looking for links that we can grab within it For every page we request, we append its URL to the addresses lst; to make sure we don't call the same page twice for each link we find, we check if we've already stored it. If we have, then well skip over the rest ofthe loop, but if \welve not then well add itto the lst of URLs that we've requested and fire off 4 request, Once that check is done, We then do @ quick stting replace on that link so that it points to the local directory, not to the subfolder /wiki/ that it’s looking for. Writing to file Now we create. fil to store the newly parsed document in for later 0 reading, We change any "in the flename to _'so the script doesn't try and write to a random folder. We also do a quick check to see how many links weve followed since the first page. if i's the max level, welladd it to the deepestAddresses lst, We'll use this a litte it late. Scrape Wikipedia with Beautiful Soup Tying up loose ends. 0 After ourscript has iterated through every link on every page to the maximum level of depth that can, it will try to exit. On line 34 of the cade (on the asc and online) in the int function, we registered the function ” 6 Copytofile After that, We take head = “chead>” + fileName + “” L Fclose() "en\">" + head + “” + fileName + “ 1 or ‘:' in link Gel deeptinksChee) nf = open(storeFotder +" + deepPage, ‘w’) rorite(eseenseup) weclosed inition Lprintconptet This is how we will Af _-name_ vitae ousoigt GEL ing Create with Python Have fun with programming Mirae Mee hauler unis e ey De Reno Ec ert eee Aiea See ac Mesue(S MU Moa Sc making a Space Invaders inspired game complete with retro grap (ee Reon mea etme sa od iy PMR ini el Have fun with programming aking a playable game is not ; Ge itee inch Vee Sante AUnia Create with Python What you'll need... Build tic-tac-toe with Kivy Build tictac-toe with Kivy Kivyisa highly cross-platform graphical fiamework for Python, designed forthe creation of innovative user interfaces like multitouch apps. Its applications can run not only on the traditional desktop platforms of Linux, 0S X and Windows, but also Android and 10S, plus devices like the Raspberry Pi That means you can develop ctoss platform apps using Python libraries such as Requests, SQL Alchemy or even NumPy. You can even access native mobile APIs straight from Python using sorne of Kivys sister projects, Another great feat re is the Gython-optimised OpenGL. graphics pipeline, allowing advanced GPU effects even though the basic Python APIis very simple. Kivyisa set of Python/Gython modules that can easly be installed via pip, but youll need a few dependencies. It uses Pygame as a rendering backend (though its APIs not exposed), Cython for compilation of the speedy graphics compiler internals, and GStreamer for multimedia. These should all be available through your distro repostories,or via pip where applicable. With these dependencies satisfied. you should be able install Kiyy with thenormal pip incantation. The current version is 180, and the same codebase supports both python2 and python3, The code in ths tutorial is also version-agnostic, running in python27 and python33. pip install kivy If you have any problems with pip, you can use easy_instll via easy__ instal kivy There are also packages or repositories available for several popular distros, You can find more information on Kivy’s website. A kivy application is started by instantiting and running an ‘App’ class. This what initialses our pp's window, interfaces with the OS, and provides an Build tic-tac-toe with Kivy entry point for the creation of our GUL We can start by making the simplest Kivy app possible: from kivy.app import App class TicTacToeApp(pp): pass if _name__ == “_main_”: TicTacToeApp().run() You can already run this, your app wil start up and youll geta plain black window. Exciting! \We can build our own GUI out of Kivy widgets Each isa simple graphics element with some specific behaviour ofits own ranging from standard GUI functionality (eg the Button, Label of Textinput),to those that impose positioning on their child widgets (eg the BoxLayout, FloatLayout or GridLayout),to those abstracting a more involved task tke interacting with hardware (eq the FlleChoosey, Camera or VideoPlayer), Most importantly Kivy’s widgets are designed to be easily combined - rather than including a widget for every need imaginable, widgets are kept simple but are easy to oin to invent new interfaces, Welll see some of that in this tutorial Since Helo Word! is basicaly compulsory in any programming tutorial, let's get itover with by using a simple Label widget to display the text from kivy.uix.label import Label \Well display the Label by retuming itas our apps root wiciget, Every app hasa single root widget, the top level ofits widget tree, and it will automatically be sized to fil the window. Well see later how to constructa full GUI by addling more widgets for this one, but for now its enough to set the root widget by adding a new method to the App: Create with Python ‘Above The game with inalations making the grid square and extending te interface def build(elf): return Label(text=Hello World!’, font_size=100, color=9, 1, % D) The ‘buile! methods called when the Apps run, and whatever widget is returned automaticaly becornes the root widget ofthat App. In our case that’sa Label and we've set several properties -the ‘text "font_size and ‘color. Allwidgets have different properties controling aspects of their behaviour, which can be dynamically updated to alter their appearance later, though here we set them just once upon instantiation. Note that these properties are not ust Python attributes but instead Kivy properties, These are accessed like normal attributes but provide extra functionality by hooking into Kivy’s event system. \Welll see examples of creating properties shortly, and you should do the same if you want to use your variables with Kivy’s event or binding functionality. That’sal you need to show some simple text, so run the program again to check that this does work, You can experiment with the parameters ifits unclear what any of them are doing, Create with Python Our own widget: tictactoe Since Kivy doesn't have a tictac-toe widget, we'll have to make our own! It's natural to create a new widget ass o contain this behaviour: from kivy.uix.gridlayout import GridLayout less TicTadToeGrid(Gri¢l ayout): pass Now this obviously doesnit do anything yet, except that it inherits all the behaviour of the Kivy GridLayout widget - that is, well need to tell it how: many columns to have, but then itwill automaticaly arrange any child widgets to fit nicely with as many rows as necessary. Tictactoe requires three columns and nine children. Here we introduce the Kivy language (kv), special domain-specific language for making rules describing Kivy widget trees. It's very simple but removesa lot of necessary boilerplate for manipulating the Gul with Python code -as a loose analogy you might think oft as the HTML/CSS to Python’ JavaScript. Python gives us the dynamic power todo anything, but all that power gets in the way if we just want to declare the basic structure, ‘of our GUL Note that you never need kv language, you can always do the same thing in Python alone, but the rest of the example may show why Kivy programmers usual like to use ky, Kivy comes with al the tool needed to use kv language; the simplest way is to write it in a file with a name based on our App class. That is, we should place the following in a file named ‘tictactoekv: : cols: 3 Thisis the basic syntax of kv language; for each widget type we may write a rule defining its behaviour, including setting its properties and adding Build tic-tac-toe with Kivy child widgets. This example demonstrates the formey, creating a rule for the TiclacloeGrid! widget by declaring that every TicTacToeGrid’ instantiated should have its ‘cols’ property set to 3, \Welll use some more kv language features later, but fornow let's go back to Python to create the buttons thatwillbe the entries in our tictactoe grid. from kivy.uix.button import Button from kivy.properties import ListProperty less GridEntry(@ut tor): coords = ListProperty((2, @) This inherits from Kivy's ‘Button’ widget, which interacts with mouse or touch input, dispatching events when interactions toggle it. We can hook into these events to call our own functions when a user presses the button, and can set the button's ‘text’ property to display the % or We also created anew Kivy property for our widget, coords’ — well show how thisis useful later on. It's almost identical to making a normal Python attrioute by writing ‘sel coords = [0, Of in ‘GridEntry__init_ Aswith the TiclacloeGrid, we'll style our new class with kv language, but this time we get to seea more interesting feature. : font_size: self.height As before this syntax defines a rule forhow a ‘GridEntry widget should be constructed, this time setting the font_size’ property that controls the size of the text in the button's label. The extra magic is thatkv language automatically detects that we've referenced the Button’s own height and will create a binding to update this relationship — when a ‘GridEnuy’ widget’s height changes, its font_size’ ‘will change so the text fits perfectly. We could have Build tic-tac-toe with Kivy made these bindings straight from Python (another Usage of the bind’ method used later or), but that’s rarely as convenient as referencing the property we went to bind to, Let's now populate our TicTacToeGrid! with ‘Gridéntry widgets. class TicfacToeGrid(GridL ayout): def __init_Gelf, *args, *«wargs): Super (TiclacToeGrid, self)._init_ args, wakwargs) for row in ranze@): for colum in range): gridentry = Gridentry( coords=(row, column) grid_entry.bind(on_release=self button pressed) self.add_widget(grid_entry) def button_pressed(self, instance): print(‘(} button clicked!’.format(instance. coords) This introduces a few new concepts: When we instantiated our Gridntry’ widgets, we were able to set their coords’ property by simply passing itn as a kwarg. Thisis a minor feature that is automaticaly handled by Kivy properties. We used the ‘bind method to call the arid ‘button_pressed’ method whenever the "GridEntry widget dispatches an ‘on_release’ event. This is automatically handled by its Button’ superclass, and will occur whenever a user presses, then releases a ‘GridEntry button, We could abo bind to ‘on_press, which is dispatched when the button i fist clicked, orto any Kivy property of the button, dispatched dynamically when the property is modified. We added each 'GridEniry’ widget to our Grid via the ‘ade_widget’ method. That means each one isa child widget of the TicTacToeGri! and so itwill Create with Python display them and knowsit should autornatically arrange them into a grid with the number of columns we set eater. Now all we have to do s replace our root widget (returned from ‘App.build) with a TiclacToeGrid’ and we cen see what our app looks like. def build(elf): return TicTacToeGridQ) With this complete you can run your main Python file again and enjoy your new program. All being well, the single Labelis replaced by a grid of nine buttons, each of which you can click (twill automatically change colour) and release (youll see the printed ‘output information from our binding). We could customise the appearance by modifying ‘other properties of the Button, but for now welll leave them as they are. Has anyone won yet? Well want to keep track of the state ofthe board to check if anyone has won, which we can do with a couple more Kivy properties: from kivy.properties import (ListProperty, NumericProperty) class TicTacToeGrid(Gr idLayout): status = ListProperty(l2, % 0, 0, 2 % ® 2 a current_player = NumericProperty(1) Thisadds an internal status lst representing who has played where, and anumber to represent the curent player (1 for’, 1 for), Byplacing these numbers in ourstatus ist, well know if somebody wins because the sum ofa row, columnor ciagonal willbe +-3, Now wecan update our graphical atid when a move played. Create with Python def button_pressedi(self, button): player = {1: ‘0’, l: %} colours = {I: (, % % D, 1: @ 1, 2% #626 a row, column = button.coords status_index = 2+row + column already_played = self.status{status_index] if not already played: self.status[status_index] = self. current_player button.text = {I: 0’, (Status[:%]), sun(status[3: sun(status[5: sun(status[): sun@tatusL! sun(statusl?: son@tatusiD), sun(tatus[?:-2:2)] if 3 in sums: print(‘Os win!”) elif -3 in sums: print('Xs win!”) elif @ not in self.status: print(‘Draw!”) This covers the basic detection of awon or drawn board, but it only prints the result to stdout. At this stage we probably want to reset the board so that the players can try again, along with displaying a graphical indicator ofthe result def reset(elf, *args): self.status = [@ for _ in ranee@] for child in self.children: child.text = ” child.background_color = (1, 1, 1, ) self.current_player = 1 Finally, we can modify the ‘on_status method to both reset the board and display the winner ina’Modalview widget. from kivy.uix.modalview import ModalView Build tic-tac-toe with Kivy This isa pop-up widget that craws itseffon top of everything else rather than as part of the normal widget tre, Italso automatically closes when the user clicks or taps outside it winner = None if -3 in suns: winner = ‘Xs win!” elif 3 in sums: winner = ‘Os win!’ elif 0 not in self.status: winner = ‘Oraw...nobody wins!” if winner: popup = ModalView(size_hint=0.75, 0.5)) victory_label = Label(text=winner, font_size=52) popup.add_widget(victory_label) popup.bind(on_ciismiss=self.reset) popup.open() This mostly uses the same ideas we already covered, adding the ‘Label’ widget to the ‘ModalView’ then letting the ModalView’ take care of drawing itself andi chilaren on top of everything else, We also Use another binding: this time to ‘on_cismiss which isan event dispatched by the ModalView’ when itis closed. Finally, we made use ofthe ‘size_hint’ property common to all widgets, which in this case isused to set the ModalView’size proportional to the window —whilea ModaMiew is open you can resize the window to see it dynamically resize, always maintaining these proportions. This is another trick made possible by a binding with the ‘size_hint’ Kivy property, this time managed internally by Kivy ‘That’ ita finished program! We can now not only play tictactoe, but our program automatically tls us when somebody has won, and resets the board so we can play again. Simply run your program and enjoy hours offun! Create with Python ems Above Atictactoe rd now acepting input adding nan © orX alternately each 99 Time to experiment This has been a quick tour through some of Kivy’s features, but hopefully it demonstrates how to think about building a Kivy application. Our programs are built from individual Kivy widgets, interacting by having Python code run when their properties change (eg our‘on_status' method) or when they dispatch events (eg ‘Button’ ‘on_release") We also briefly sav ky language and experienced how it can automatically create bindings between properties You can find a copy of the full program on FileSibo, reference this to check you've followed everything comrectly, We've also added an extra widget, the ‘interface, with a structure coded entirely in kv language that demonstrates how to add child widgets. Test it by uncommenting the return, Interfaces) line in TicTacToeGrid build: It doesn't, do anything fundamentally different to what we already covered, but it does make extensive use of ky language’ binding ability to automatically update label showing the current player, and to resize the TicTacToeGrid so its always square to fit within its parent. You can play with the settings to see how it fits together, or try swepping out the different widget types to see how other widgets behave Create with Python What you'll need... Latest Raspbian Image ‘naasobemrp\oraidounicads Pillow rspvttnulbcomiython smasing/ Pow ‘SimpleGUITk bnupsvathubcomidholn/sinpleauit, Below TuxforTwo! bageat le Pongclone using te beloved Linux maseat Tux dnthecenteaf the action Make a Pong clone with Python Make a Pong clone with Python The Raspberry Piisa fantastic way to start learning how to code One area that can be very rewarding for amateur coders is game programming, allowing for a more interactive result and a greater sense of accomplishment. Game programming can alo teach improvisation and advanced mathematics skis for code. Well be using the fantastic SimpleGUITk module in Python, a very straightforward way of creating graphical interfaces based on Tkinter, Python module preparation 01 Head to the he source fi then install the following psites wee lstedin What youll need’ and download a zip of es fromm the GitHub pages, Update your Raspbian packages and I$ sudo apt-get install python-dev python-setuptools tk8.5-dev tel8.5-dev Install the modules 0 (Open the terminal and use ca tomoveto theexttacted Pilow folder. Once there type: IES sudo python setup.py install (Once that's complete, moveto the simpleguitk folder and use the same commend toinstal that as ell, Set up the game 4 Recireticseogeundbesinare Write your code shan DLES, OB Paporancuentn ete odelising tocaeateour game ‘Txfor vo Becareflto folow along with the code tomake sue you know what youre doing. Thisway.youcan make your own changes to the game rus iyou wish, the code:Tuxs and the paddles intial postions are se, along with the intial speed and direction of Tux. These are also used wher speed is set to random fo h spawn. ints won and the playing fe set. The drection and The SimpleGUI code The important parts in the OB ronnie row line, draw_image and draw_text functions. These are specifically from SimpleGU| and alow you to easly put these objects on the screen with a position, size and colour. You need ta tiethem to an object, though -in this case, canvas, Tis tes the software that we want to put these items on the screen for people to se. SimpleGUI setup code 0 The last parts are purely for the interface. We tellthe code what to do when a key is depressed and then released, and give it a frarne to workin. The frame is then told what functions handle the graphics, key functions etc Finaly, we give it frame, start) soit starts Make a Pong clone with Python Create with Python Full code listing import simpleguitk os simplegui if tux_posf@] <= pad_w + tuxr: import random if (paddlel_post(pad_h/2)) >= 4 ‘tux_pos[1] >= (paddlel_pos-(pad_h/2)): tux_velfa} = ~tux_vel[0}#1.1 tuxvelf1] = 1.1 else: score? += 1 ‘tux_spawn( True) def tux_spawn(right) elif tux_posfé] >="w - pad_w - tucr: global tux_pos, tux.vel if (Paddle2_post(pad_h/2)) >= tux_pos = 10,0) ‘tux_postt] >= (paddle2_pos-(pad_lv2)): tuxvel = [0,0] tuxvel[@] = -tux.vel(2} tux_pos{e] = w/2 tuxvelf1] = 1.1 tux_posfi] = h/2 else: if right: scorel += 1 ‘tux_velf@] = random.randrange@2, 4) ‘tux_spawn(False) else: canvas.draw_image(tux, (265 / 2, 314 / 2), 4 ‘tux_vell@] = -randon.randrange(2, 4) (265, 314), tux_pos, (45, 45)) ‘tux_velfi] = -random.randrange(1, 3) ‘canvas.draw_text(str(scorel), [150, 100], <1 3, “Green") def start0: canvas.draw_text(str(score2), [45, 100], <1 global paddlel_pos, paddle?_pos, =! 32, “Green”) paddlel_vel, paddle2_vel global Scorel, score? def keydoun(key): ‘tux_spann(ranidom.choice(LIrue, False) global paddlel_vel, paddle2_vel scorel, score? = 0,0 ace = 3 paddlel_vel, paddle2vel = 0,0 if key == simplegui.KEY_MAP["W"' paddlel_pos, paddle2_pos = h/2, h/2 paddlel_vel == acc elif key == simplegui, KEY MAP["S"): def draw(canvas): paddlel_vel += ace global scorel, score2, paddlel_pos, <1 elif key==simplegui.KEY_MAPT down"): paddle2_pos, tux_pos, tux_vel paddle2_vel += ace if paddiel_pos >’ (h ~ (pad_h/2): elif key==simplegui.KEY_MAPC“up"]: paddlel_pos = (h ~ (pad_h/2)) paddle2_vel ~= ace elif paddlel_pos < (pad_h/2): paddle1_pos = (pad_h/2) def keyup(key) else: global paddlel_vel, paddle2_vel paddlel_pos += paddlel_vel ace = @ if paddle2_pos > (h - (pad_h/2)) if key == simplegui.KEY_MAPL"WJ paddle2_pos = (h ~ (pad_h/2)) paddlel_vel = acc elif paddle2_pos < (pad_h/2) elif key == simplegui. KEY MAPS"): paddle?_pos = (pad_h/2) paddlel_vel = acc else: elif key=simplegui.KEY_MAPL"“down’” paddle?_pos += paddle2_vel paddle2_vel = ace canvas.draw_line(iw / 2, @.iw / 2, hl, 4, elif key=simplegui.KEY_MAPL'up"]: “Green” paddle2_vel = acc canvas.draw_line([(pad_w/2), paddlel_ pos * (pad_h/2)], [(pad_w/2), paddlel_pos - <1 frame = simplegui.create_frame(‘Tux for Two”, <1 (pad_h/2)1, pad, "Green”) wb) canvas.draw_Line(Iw - (pad_w/2), = frame.set_draw_handler (drav) paddle2_pos + (pad_h/2)], tw ~ (pad_w/2), <1 frame. set _keydown_handler(keydowr) paddle2_pos - (pad_h/2)], pad_w, “Green” frame. set_keyup_handler(keyup) ‘tux pos{e] += tux vell0] ‘simplegui.load_inage(http://upload. <1 tux_postt] += tux_velf1] nslalat iF tux _posCI] <= tuxr or tux_posft] >= h = tucr: startO. ‘tux.velLI] = -tuxvel [141.1 frame.start() Create with Python What you'll need... Raspbian Python wverespython oratdoc Pygame Did you know. Era Tats) ight Pagers aSpaceinvaders ‘done we've made especialy fore Pt Program a Space Invaders clone Program a Space Invaders clone When you'e learning to program in a new language or trying to master anew module experimenting with a familiar and relatively simply projects a very useful exercise to help expand your understanding of the tools youre using. Our Space Invaders clone is one such example that lends itself perfectly to Python and the Pygarne module —it'sa simple game with almost universally understood rules and logic. \Weive tried to use many features of Pygame, which is designed to make the creation of games and interactive applications easier We've extensively used the Sprite class, which saves dozens offines of extra code in making collision detection simple and updating the screen and its many actors a single-ine command Have fun with the project and make sure you tweakand change things to make ityour own! Program a Space Invaders clone Create with Python Full code listing fusr/binfeny python? if not self.has_movedE1] self.rect.y += self.vector{!] * «1 import pygame, random self.vector [0] BLACK = (0, 0, 0) self.has_moved = [, 0] BLUE = (0,'0, 255) self.speed = 20 WHITE = (055, 255, 255) if self.speed <= 100: RED = (255, 0, self.speed = 100 ALIEN_SIZE. self.time = GameState.alien_time ‘ALIEN_SPACER BARRIER_ROW class Anmo(pygame.sprite.Sprite): BARRIER_COLUMN = 4 jef _init_Gelf, color, (width, height)): BULLET_SIZE pygame.sprite.Sprite."\\_(elf) MISSILE_SIZE = (5 self-image = pygame,Surface(iwidth, <1 BLOCK SIZE = (10," 10) height) RES = (800, 600) self.image.fill(color) self-rect ~ self.image.get_rect() class Player (pygame.sprite. Sprite) self.speed = 0 ef _init__Gelf) self.vector = 0 pygame.sprite.Sprite. | (self) self.size = (50, 55) lef update(self): self-rect = self.image.get_rect() self.rect.y + self.vector * self. speed self.rect.x = (RES[0] / 2) ~ Gelf.size 4 if self.recty < @ or self.rect.y > RES[II: t/a self.kill() self.rect.y = 520 selftravel = 7 ass Block(pygame.sprite.Sprite): self.speed = 350 f init Gelf, color, (width, height)): self.time = pygame.time.get_ticks() pygame.sprite.Sprite."'__Gelf) self.image = pygame,Surface(iwidth, <1 Jef update(selF) height) self.rect.x + GameState.vector * self, «1 self-image.fill (color) travel self.rect ~ self.image.get_rect() if selfirect.x < 0: oss GameState: self.rect.x pass elif self.rect.x > RES[0] - self.sizefol: self.rect.x = RES[@] ~ self.size[] class Game(obiec): ooh st (self class Alien(pygame. sprite. Sprite) pygame.initQ) ief _ init__(self): pygame.font. init) pygame.sprite.Sprite. ii _ (self) self.clock = pygame.time.Clock() self.size = (ALIEN SIZE) self.game_font = pygame.font.Font( self.rect = self.image.get_rect() ‘data/Orbitracer.ttf', 28) selfhas_moved = [0, 0] self.intro_font = pygame.font.Font( self.vector = Cl, 1] ‘data/Orbitracer.ttf", 72) self.travel = [(ALIEN_SIZE[e] - 7), self.screen = pygame.display.set_ 1 ALIEN_SPACER] mode(TRESE*], RESLITI) self.speed self.tine = pygame.time.get_ticks() self.time = pygame.time.get_ticks() self.refresh_rate = 20 self. rounds won def _update(self): self. level_ty if GameState.alien_time - self.time > 1 self.score = 0 self.speed: self.lives = 2 if self.has_moved{o] < 12: self player_group ~ pygame.sprite.Group() self.rect.x += self.vector[0] * self. 1 self.alien_group = pygame.sprite.GroupQ) travelfo] self.bullet_group = pygame.sprite.Group() self.has_moved{a] *=1 self,missile_group ~ pygame.sprite.Group() else: self.barrier_group = pygame.sprite.Group() Meee era Create with Python Setting up dependencies (Thence ete tee unsesnctng of rograrning games th Python and Pygame, we strongly recommend you copy the Pivaders code inthis tutorial nto your own program. t's great practice and gives you chance rotweakelements ofthe game suityou, beita different ship mage, changing the dificult othe ways the alien waves behave if you just want to pley the game, that’ easly achieved too, though. Ether way, the game's oniy dependency s Pygame, which (fit isritaready) can be installed fram the terminal by typing: W sudo apt-get install python-pygame Installation 02" Pivaders we've used Git, a brillant form of version control used to safely stare the game flles and retain historical versions of your code. Git should already be installed on your Pt if not, you can acquire it by typing: I sudo apt-get install git ‘Asweell as acting as caretaker for your code Git enables you to clone copies of other people's projects so you can work.on them, or just use them. To clone Pivaders, qo to your home folder in the terminal (ed ~) make a directory for the ject (mkair pivaders), enter the dtectory (cd pivaders) and type: git pull. https://github,con/russb78/pivaders git Testing Pivaders 03 \With Pygame installed and the project cloned to your machine (you can aso ind the zip on this issue’ cover DVD - simply unpackitand copyitto your home directory to use_t, youcan take fora quick test dive to make sure everything’ set up property. All you need to dois type python pivaderspy from within the pivaders directory in the terminal toget started. You can start the game with the space bar, shoot with the same button and simply use the lft and right arrows on your keyboard to move your ship left and right. Creating your own clone 04220" racked up 2 good high score (anything over 2,000 points is respectable) and got to know our simple implementation, youll get more from following along with and exploring the code and our brief explanations of ‘what's going on. For those who want io make their own project, create a new project folder and use either IDLE or Leafpad (or perhaps install Geary) to create and save. py fe of your own. applications easier” Program a Space Invaders clone Global variables & tuples 0 ‘Once we've imported the modules we need for the project, there's quite along list of variables in block capitals. The capitals denote that these variables are constants (or global variables, These are important numbers that never change - they represent things referred to requiarlyin the code like colours, block sizes and resolution, Youll also notice that colours and sizes hold multiple numbers in braces - these are tuples. You could use square brackets (10 make them lst, but we use tuples here since they'e immutable, which means you can't reassign individual items within them, Perfect for constants, which arent designed to change anyway. Classes — part 1 063 serene blueprint for an object you'd like to make. In the case of our player, it contains all the required info, from which you can make multiple copies (wre create a player instance in the make_player() method halfway through the project). The great thing about the classes in Pivadersis that they inherit lots of capabilities and shortcuts from Pygame'’s Sprite class, as denoted by the pygemesprite. Sprite found within the braces of the firs ine of the class. You can ead the docs to learn more about the Sprite class via wwwpygameora/docs/refisprite html, “We've tried to use many features of Pygame, which is designed to make the creation of games and interactive Program a Space Invaders clone Deen self.all_sprite_list = pygame.sprite. <1 GroupQ) self.intro_screen = pygame. image. load( ‘data/start_screen. pg’ ).convert() self.background = pygame. image. 1oad( ‘data/Space-Background. jpe").convert pygame.display.set_caption(‘Pivaders ~ 1 ESC to exit’) I, pygame.mouse.set_visible(/lsc) Player. image - pygame.image.load( ‘data/ship.png).convertQ) Player. image.set_colorkey(BLACK) Alien.image = pygame.image.load( ‘data/Spaceshipl6.png’).convert() Alien. image. set _colorkey(WHITE) GameState.end_game = false GameState.start_screen = Truc GameState.vector = 9 GameState.shoot bullet = Felse f control(self): for event in pygame.event.get(): if event.type -= pygame.QUIT: GameState.start_screen = false GameState.end_game = True if event.type == pygame.KEYDOHN \ andl event.key == pygame.K_ESCAPE: if GameState.start_screen: GameState.start_screen = false GameState.end_game = True self.kill_allQ else: GameState.start_screen = Truc self.keys = pygane.key.get_pressed() if self keysfpygame.K_LEFT]: GameState.vector = -1 elif self. keysCpygame.K_RIGHT GameState.vector = 1 else: GameState.vector = 0 if self.keys[pygame.K_SPACE] if GameState.start_screen: Ganestate.start Screen = False self.live self-score self.make_player() self.make_defenses() self-alien_wave() else: GameState. shoot _bullet = True ef splash_screen(self): while GameState.start_screen: self.kill_allQ self.screen.blit(self.intro_screen, « a) self. screen. blit(self.intro_font .render( “PIVADERS”, 1, WHITE), (255, 120)) en, Create with Python self screen. bLit(self. game_font. render( “PRESS SPACE TO PLAY", 1, WHITE), <1 19) pygame.display.FlipO) self.control() f make_player (self) self.player = Player() self.player_group.add(self.player) self.all_sprite_list.add(self player) f refresh_screen(self): self.all_sprite_list.dran(self.screen) self.refresh_scores() pygame.di splay.Flip() self.screen. blit(self. background, [2, J) self.clock.tick(self.refresh_rate) f_refresh_scores(self): self.screen. blit(selF.game_font..render( “SCORE “+ sir(elf.score), 1, WHITE), + G2, 8) self. screen. blit(self. game_font .render( SLIVES “ + sirGelf.lives + 1), 1, RED), 655, 575)) def alien_wave(self, speed): for column in °'ie=(BARRTER_COLUMN): for row in. -2--(BARRIER_ROM): alien = Alien() alien.rect.y = 55 + (column * ( ALIENSIZEC1] + ALIEN SPACER)) alien.rect.x = ALIEN SPACER + ( row * (ALIEN_SIZE[0] + ALIEN_SPACER)) self.alien_group.add(alien) self.all_sprite_list .add(alien) alien.speed -= speed f make_bullet(self): if GameState.game_time - self.player. <1 time > self.player. speed: bulllet = Anno(BLUE, BULLET_SIZE) bullet.vector bullet.speed s bullet.rect.x = self.player.rect.x + 28 bullet.rect.y = self.player.rect-y self.bullet_group.add(bul let) self.all_sprite_list.add(bullet) self.player.time = GameState.game_time GameState.shoot_bullet = False make_missile(self: if en(self.alien_group): shoot = random.random() if shoot <= 0.05: shooter = random.choice(L alien for alien in self.alien_group]) missile = Anmo(RED, MISSILE_SIZE) Create with Python Classes - part 2 0 In Pivader’s classes, besides creating the required attributes for the object, you'll ako notice all the classes have an update) method apart from the Block class {a method fsa function within a class). The updated) method is called in every loop through the main game and simply ask the iteration ofthe class we've created to move. In the case of a bullet ftom the Ammo dass, we're asking it to move down the screen. Ifit goes off either end, we destroy it ee ah) ea Ammo \Whats most interesting about classes, though jsthat you can use one cass OB ere is orators things. You could, for example, have a pet class. From that cass you could create a cat (that meow) and a dog (that barks). They te diferent in many ways, but theyre both furry and have four legs, so can be created fiom the same parent dass Weve done exactly that with our Ammo class using it to create both the player bullets and the alien missles, They‘ cifferent colours and they shoot in opposite directions, but theyte fundementally one and the sare. The game 0 Ourfinal cassis called Game. This is where all the main functionality of the game itself comes in, but remember, so far this is sil usta lst oF ingredients — nothing can actually happen until a ‘Game’ object is crested (right at the bottom of the code}. The Game ciassis where the central mass of the game resides, so we initialse Pygame, set the imagery for our protagonist and extraterrestrial antagonist and create some GameState attrioutes that we use to Control key aspects of external classe, ke changing the player's vector (direction The main loop 10 mr Cf methods (class functions) in the Game class, and each is designed to contio!a particular aspect of etther setting up the game or the gameplay itself The logic that dictates what happens within any one round of the game is contained in the main_loop) method right at the bottom of the pivaders py script and isthe key to unlocking exactly what variables and functions you need for your garne, Program a Space Invaders clone Main loop key logic- part 1 T1 frigate the end_game attribute is false - F's tue, the entieloop in ‘main_loap0 is skipped and we go straight to pygame.quit(, exiting the game Thisfiag is set to tue oniy if the player closes the game window or presses the Esc key when on the start_screen. Assuring end|_game and start_screen are false, the main loop can start proper, with the controll) method, which checks to see ifthe location of the player needs to change. Next we attempt to make an enemy missile and we use the random module to limit the number of missiles that can be created. Next we call the update) method foreach and every actoron the screen using a simple for Joop. This makes sure everyone's up to date and moved before we check colsions in calc_collsions) Main loop key logic part 2 TD Crcalisorshareosen calculated, we need to see ifthe games still meant to continue. We do so with is_deadi) and defenses_breached) -ifeither of these methods returs true, we know we need to return to the start scien, On the other hand, we also need to check to see if we've killed all the aliens from within win_round. Assuming we're not dead, but the aliens are, we know we can cali the next_round) method, which creates, a fresh batch of aliens and increases theirsceed around the screen. Finally, we refresh the screen so everything that’ been moved, shot or killed can be updated or removed from the screen. Rememibey, the main loop happens 20times a second so the fact we don't callfor the screen to Update right at the end of the loop is of no consequence. Program a Space Invaders clone echo tol missile.vector = 1 missile.rect.x = shooter.rect.x + 15 missile.rect.y = shooter.rect.y + 40 missile.speed = 1 self.missile_group.add(nissile) self.all_sprite_list.add(missile) def make_barrier(Gelf, columns, rows, spacer): for column in vans e(columns), for row in range(rows): barrier = Block(WHITE, (BLOCK_SIZE)) barrier.rect.x = 55 + (200 spacer) «1 + (row * 10) barrier.rect.y = 450 + (colum * 1¢) self.barrier_group.add(barrier) self.all_sprite_list.add(barrier) Jef make_defenses(self): for spacing, spacing in +! enumerate(xrange(4) self.make_barrier(3, °, spacing) def kill_all(elf): for items in [self.bullet_group, self. 410: self.screen.blit(self.game_font.render( “The aliens have breached Earth <1 defenses!”, 1, RED), (230, Create with Python self.refresh_screen() Pygame.time.delay(2200) return True def cale_collisions(self): pygame.sprite.groupcollide( self.missile_group, self.barrier_group, +! True, True) pygame.sprite.groupcol lide( self.bullet_group, self.barrier_group, +! True, True) if. pygame. sprite. groupcol Lide( selfibullet_group, self.alien_group, <1 True, True) self.score += 10 if pygame. sprite. groupcollide( self.player_group, selfimissile_group, +! True): self.lives -= 1 next_round(self. for actor in [self.missile_group, self.barrier_group, self.bullet_group]: for i in actor: iLkiO self.alien_wave (self. level_up) self.make_defenses() self.level_up def main_loop(self): while not GameState.end_game: while not GaneState.start_scree GaneState.game_time = pygame.time. «1 get_ticks() GéneState.alien_time = pygame.time get_ticks() self.control() self.make_missile() for actor in [self.player_group, ~! self.bullet_group, self.alien_group, self.nissile group]: for i in actor: i.updateQ) if GameState.shoot_bullet: self.nake_bulletQ self.calc_collisions() if self.is deadQ or self.defenses_ +! breached(): CameState.start_screen = True if self.win_round(): self.next_round() self.refresh_screen() self. splash_screen() pygane.quit() if _nane_ pv = Game() pv.main_loap() Create with Python What you'll need... Raspbian Python Pygame. ownupnaamewaidocs Artassets ‘sosnoamesrtora Did you know. Setting up dependencies 0 Youll get much more from the exercise ifyou download the code [gittio/8QsKow) and use it for reference as you create your ‘own animations and sound effects. Regardless of whether you just want 10 simply preview and play or walk through the cove to get a better understanding of basic game creation, youte stl going te need to satisty some basic dependencies. The two key requirements here are Pygame and Git, both of which ate installed by default on up-to-date Raspbian installations. That's easy Pivaders part 2: graphics and sound Pivaders Pt 2: graphics & sound This time we'll expand our Space Invaders clone to include immersive animation and sound We had great fun creating our basic Space Invaders clone, Pivaders, in the previous guide, Pygame’s ability to group, manage and detect collisions thanks to the Sprite class realy made a great difference to our project, not just in terms of code length, but in simplicity too. If you missed the first part of the project, you can find the v0.1 code listing on GitHub via gitio/cBVTBg, while you can find version v0.2 of the code, including all the images, music and sound effects we've used at gitio/8QsK-w. To help keep our project code manageable and straightforward {@s your projects grow keeping your code easy to follow becomes increasingly hardes) we integrated a few animation methods into our Game class and opted to use a sprite sheet. Not only does it make it very easy to draw to the screen, but it also keeps the asset count under control and keeps performance levels up, which is especially important for the Raspberry Pi. We hope you have fun using our techniques to add animation and sound to your projects! Downloading pivaders O2 Seanereeren control solution that helps programmers safely store their code and associated files, Not only does it help you retain a ful history of changes, it means you can ‘clone’ entire projects to use and work on from places like github.com, To clone: the version of the project we created for this tutorial, goto your hone folder from the command line (cd ~) and type HE ait putt bttps://sithub.com russb7é/pivaders. git ‘This creates a folder called pivaders. Navigating the project OB rteprades sateen, readme and a second pivaders folder. This contain the main game fle pivaderspy, which lunches the application, Within the data folder youll Find subfolders for both araphics and sound asses, as well asthe font weve used forthe tle screen and scores. To take pivades fora tes-dive, simply enter the pivaders subdirectory (3 pivaders/pvaders) and type: EE python pivaders.py Use the arrow keys to steer lftand rightand the space barto shoot. You can quit with the Escape key. Pivaders part 2: graphics and sound Code listing (starting from line 87) class Game(obiect): def _init_Gelf): pygame.init() ygame.font. init) self.clock = pygame.tine.Clock() self. game_font = pygame.font.Font( “data/Orbitracer.ttf”, 28) self.intro_font = pygame.font.Font( ‘data/Orbitracer.ttf”, 72) self.screen = pygane.display.set_node(CRES(J, RES[T]) self.time = pygame.time.got_ticks( self-refresh_rate = 20; self.rounds_won self-level_up = 50; self.score = 0 self-lives = 2 self.player_group = pygane.sprite.Group() self.alien_group = pygane.sprite.Group() self.bullet_group = pygame.sprite.Group() self,missile_group = pygame.sprite.Group() self.barrier_group = pygame.sprite.Group() self.all_sprite_List = pygane.sprite.GroupQ) self.intro_screen = pygame.inage.load( ‘data/graphics/start_screen.jpg’).convertQ. self.background = pygame.image. load( “data/graphics/Space-Background. jpg')-conver t() pygame.display.set_caption('Pivaders - ESC to exit’) ygame.mouse.set_visible(*21s:) Alien.image ~ pygame.image.load( ‘data/graphics/Spaceship16.png").convert() Alien. image.set_colorkey(WHITE) self.ani_pos = self.ship_sheet = pygame. image. load ‘cata/graphics/ship_sheet_final_pne’).convert_alphaQ Player. image = self.ship_sheet. subsurface self.ani_pos*4, 0, 4, 61) self.animate_right = False self.animate_left = False self.explosion_sheet = pygame.image.load( “data/graphics/explosion_new1.png’).convert_alpha() self explosion_image = self.explosion_sheet. subsurface % @ 79, 96) ‘self.alien_explosion_sheet = pygame.image.1oad( ‘data/graphics/al ien_explosion.png”) self.alien_explode_graphics = self.alien_explosion_sheet.! subsurface(0, , 94, 96) self.explode = False self.explode_pos = 0; self.alien_explode = False self.alien_explode_pos = pygame. mixer.music. load( data/sound/1¢_Arpanauts.ogg: pygame.mixer.music.play(-1) ygame.mixer.music. set _volume(?.7) self.bullet_fx = pygame.mixer: Sound( ‘data/sound/nedet ix__pe-bitcrushed-lazer-beam.ogg") self.explosion_fx = pygame.mixer.Sound( “data/sound/t imgormly__8-bit-explosion.oge") self,explosion_fx.set_volume(0.°) self.explodey_alien| ects Toy Create with Python Animation & sound Compared with the game from last month’ tutorial youtl see it’s nowa much more dynamic project. The ship now leans into the turns as you change direction and corrects itself when stationary. When you shoot analen ship. it explodes with several frames of animation and should you take fie, a smaller explosion occurs on your ship. Musi, lasers and explosion sound effects also accompany the animations as they happen. Finding images to animate 0 Before we can program ID snytingits ue whine assets set up correctly. We've opted to se sprite sheets these can be found online or created with GIMP with a little practice. They're a mosaic made up of individual frames of equally sized and spaced images representing each frame, We found ours at ‘opengameart.org, Tweaking assets 06 While many of the assets yout find online can be used ass, you may want to import them into an image-esiting aplication Ike GIMP to configure them to suityour needs. We started wth the central sip sprite and Centred it into a new window. We set the size and width of the frame and then copy-pasted the other frames either side oft. We ended up with 11 frames of exactly the same size and width in a single document. Phel- perfect precision on size and width is key 0 we can just multiply itto find the next frame. Create with Python Loading the sprite sheet 0 ‘ince wete inheriting from the Sprite class to create our Player class, we can easily ater how the player looks on screen by changing Playerimage. First. we nied to load our ship sprite sheet with pygameimage. load Since we made our sheet with a transparent background, we can append. convert_alpha( to the end of the line so the ship ames render conrectly (without any background We then use subsurface to set the initial Playerimage to the middle ship spite on the sheet. This s set by selfani_pos, ‘which has an intial value of. Changing this value wil ater the ship image drawn to the screen: 0’ would draw it leaning fully lef, 1 fully to the dit. Animation flags 0 Slightly further down the list in the intialsing code forthe Garme class, we aso set two flags for our player animation: selfanimate_left and selfanimate_right. As youl see in the Control method of our Game clas, we use these to lag’ when we want animations to happen with True and False. It also allows us to automatically’ animate the player sprite back to its natural resting state (otherwise the ship will continue to look aif’ flying left when it has stopped) The animation method oo flags again in the code forthe player-animate_playerd. Here we use nested ifstatements to control the animation and physically set the player image. It states thatf the animate_right flag is True and ifthe current animation postion i different 10 what we want, we incrementally increase the ani_pos variable and set the player's image. The Else statement then animates the ship sprite backto it esting state and the same logics then appliad in the opposite direction. Pivaders part 2: graphics and sound GameState.end_game = False GameState.start_screen = Truc GameState.vector = 0 GameState.shoot_bullet = False def control(self): for event in pygame.event.get( if event.type == pygame.QUr GameState.start_screen = False GameState.end_game = True {if event. type == pygame.KEYDONN \ and event: key == pygame.K_ESCAPE: if GameState.start_screen: GameState.start_screen GameState.end_game = True self.kill_allO else: GameState.start_screen = True self.keys = pygame.key.get_pressed() if self. keys[pygame._ LEFT] GameState.vector = ~1 self.animate_left = True self.animate_right = Folse elif self-keystpygame.K_RIGHT]: GameState.vector = 1 self.animate_right = Truc self.animate_left = Felse else: GaneState.vector self.animate_right self.animate_left False ‘if’ self keys[pygame.K_SPACE): if GameState. start_screen: GameState.start_screen = False self.lives = 2 self-score self,nake_player() self.make_defenses() self.alien_wave(?) else: GameState. shoot_bullet = True self bullet_fx.playQ def animate_player (self): if self-animate_right: if self.ani_pos < 10: Player. image - self.ship_sheet subsurface( self.ani_pos*64, 0, 64, 61) self.ani_pos += 1 else: if self.ani_pos > 5: self.ani_pos = 1 Player.inage = self.ship_sheet subsurface( self.ani_pos*6i, 0, 64, 61) if self.animate_left: if self-ani_pos > @: self.ani_pos -= 1 Pivaders part 2: graphics and sound » Player.image = self.ship_sheet. subsurface self.ani_posi4, 0, 04, 61) Player.image = self,ship_sheet.subsurface( self.ani_posri, 0, 04, 61) self.ani_pos = 1 def player_explosion(self): if self.explode: if self.explode_pos < 8: self.explosion_image = self.explosion_sheet. subsurface(®, self-explode_pos*%, 79, 96) self.explode_pos “+= self.screen, blit(self.explosion_image, [self.player. srect.x “10, selfiplayer.recty ~ 301) else: self.explode = False self.explode_pos = 0 def alien_explosion(self): af self.alien_explode: if self.alien_explode_pos < 9: self.alien_explode_graphics = self.alien_ ‘explosion_ ~sheet.subsurface(2, self.alien_explode_post5, 4, 96) self.alien_explode_pos #= 1 self.screen.blit(elf.alien_explode_graphics, <1 LintGelf. explodey_alien(@]) - 50, ‘»((self.explodey_alienti]) ~ 6oy) else: self.alien_explode = Folse self.alien_explode_pos = 0 self.explodey_alien = (] ef splash_screen(self): while GameState.start_screen: self.kill_allQ self.screen.blit(self.intro_screen, [0, I) self.screen.blit (self. intro_font.render( “PLVADERS”, 1, WHITE), (265, 120)) self.screen.blit(self-game_font .render( “PRESS SPACE TO PLAY”, 1, WHITE), (274, pygame.display.flipQ self.controlQ) self.clock.tick(self.refresh_rate / 2) is) def make_player(self): self.player = Player) Find the rest of the code at github.com/russb78/pivaders: "Sprite sheets make it es to draw to the screen, but it also keeps the asset count down and performance levels up" Create with Python Animating explosions TO meremrccsonens alien explosion) methods that come after the player animation block in the Game class are similar but simpler executions of the same thing, ‘As we only need to run through the same predefined set offames (this time vertically, we only need to see if the selfexplode and seltalien_expiode flags are True before we increment the variables that change the image. Adding music Terme msstenstoadds musical score toa project. Just obtain a suitable piece of music in your preferred format (we found ours Via figemusicarchive ora) anc! load it using the Miser Pygame class. s its already been initialised via pygame. init, we can go ahead and load the music. The music play¢') reouests that the music should start with the appand continue te loop unt it quits. IFwe replaced 1 with 5, the music would loop five times before ending Lean more about the Mixer clas via wwwpygameorg/docs/ref/ mixer html Using sound effects 1 Loading and using sounds is similar to how we do so for images in Pygame. Fist we load the sound effect using 2 simple assignment. For the laser beam, the initiasation looks lke this: I seifibutlet_tx = pygane. mixer. Sound(‘Location/of/file’) Then we simply trigger the sound effect at the appropriate time. In the case ofthe laser, we want it 0 play ‘whenever we press the space bar to shoot, so we place itn the Game ass's Control method, straight after we rase the shoot _bullet flag, You can get different sounds from www reesound.org, Use Python with Pi Create amazing projects Oar Vitale aR Ute Pi Amazing creations with Python code and Raspberry Pi. From the tutorials up to this point, you'll have a firm grounding in Pythons NAN ROR hat ss Meo era to get started with Python on the Pi, and then you'll discover exciting . projects such as learning to multi-task with your Raspberry Pi (p.110), creating a Pi-powered virtual reality setup (p.114) and using it to get more Cen aera aC) Create amazing projects Use Python with Pi Use Python with Pi What you'll need... nace perherae 1D car latest image for rrr] Using Python on Raspberry Pi Using Python on Raspberry Pi Program in Python with the Raspberry Pi, and lay the foundations for all your future projects Before getting started with this tutorial, ensure that youve set up the latest version of the Raspbian operating system on an SD card for your Raspberry Pi. The beauty of using an SD card image is that the operating system is ready to goand a development environments already configured for us \Wellluse a lightweight integrated development environment (DE) called Geany for our Python development. Geany provides a fiiendlier interface compared to text-based editors such as nano to make it easier toget into the swing of things. This tutoral will cover topics such as + Basic arithmetic + Compatison operators, for example ‘equal to’ and ‘not equal to + Control structures, for example loops and ifstatements By the end, well have an advanced version of our hello world’ application. Lets dive straight in Fle Edt Go Bookmarks view Tools Help 6 OO - OF homers % Br wm desep w Ww i nsien nny Sem 1B Applications 16 G8 Flesystem Staying organised OTesmne have messy folders on our new Pi solet's goto the fle manager and organise ourselves. Open the fie manager by clicking the icon next tothe menulicon on the bottom lef ofthe screen. Create a new folder by right-clicking and selecting New>Foldey, then type aname and dick OK We created a folder called Python, and inside that created a folder called Hello World v2 t's good practice to describe ‘what the prograrn’s purpose isatthe top ofthe fie This wil help you out when ‘working on larger projects vwith multiple files tt’simportant to think about data types. We convert the number to decimal to make sure that we don't lose any decimal numbers during arithmetic The stopping condition fora while loop has tobe satisfied at some point in the *“ code; otherwise the loop will neverendl The print function can only accept string datatypes, soweneed to convert any variables with a number deta type toa string before we can printthem to the screen Using Python on Raspberry Pi Use Python with Pi #1/asr/bin/env python 4 An advanced Hello World program that will demonstrate the basics of Eee Tr Dea te asrotracia | Tented by Lise Fraser G.lnvert the sys Libary for the Sys.exst function ng trom the Decimal Libary re 4 Get the users first name and output a welcome message Firstname = raw input ("Please enter your first name? ") print(Welcome = + firstName + "\n°) # Ask the user for a nunber and square it, double it and halve it unber = raw input("Please enter a number: “) Decimal (nusber) feumber 2 umber 2 = umber * number umbersquare 4 Print out the values we Just worked out, converting each float value Print("The result of halving that nunber: "+ str(numberiialved) ) rint(The result of doubting that number: *'s str(nunberboubted) } » Print ("The result of squaring that number: * + str(nunberSquar } int # The stopping cond: yesdrto = False fon for a white Loop # A while Loop that will run untill a user enters either "yes" or “no while yesortio == False: Feguit = raw input("D0 you want te continue? (yes/ne) * Af result 2» "yes" or result == “no” ‘yesdro ~ True ats print("Error, please type yes or no" + “\n"] # beat with the result it result 2 "yes" print("\nContinuing") ols ine (*\nExiting") Sysvexitc) # Create the count which will be a stopping condition for a white loop count = 1 # Use a while loop to add 5 to the number and output the value each tine Print ("incrementing the number by 5\n") White count <5: umber += 1 Print(-nunber + * + str(count) +" = * + str(number)) count s= 1 # Finish off by printing thet we are exiting Print("\néxiting’) Starting Geany 0 Start Geary by going to the LxDE menu and going to Programs. From here select Geany. Once youte in the Geany interface, create anew Python file ftom a template by selecting 'New (with template}>main py’ Delete ‘everything in this template apart from the fits line: #/ust/birveny python. This line fs important because it means you can un the code from the command tine and the Bash shell will know to open it with the Python interpreter Use Python with Saving your work 03" always a good idea to keep saving your work with Ctrl4S 2 you program, because it would be a shame to lose anything you've been working on. To save your file for the first time, either press Ctrl4S or goto the File menu and select Save Give the file a sensible name and save it in the tidy folder staucture you created before, t's a good habit to be well organised when progremming, because it makes things much easier when your projects become biager and more complicated, Setting it up o4ie: detailed comments in your code is important because it allows you to note down things you find confusing and document complex procedures. If another programmer has to work with your code in the future, they'll be extremely grateful Start by adding a comment with a description of ‘what the program will do and your name All comment lines start with a hash (#) and are not interpreted a5 code by the Python interpreter. We import the sys library so we can. use the sysexit function to close the program later on. We also import everything from the decimal library because we want t0 make use of the decimal type #!/usr/bin/env python # An advanced Hello world # programming in Python v # for Linux User and Deve # Import the sys Libary f import sys # Import everything from from decimal import + Programming in Python on the Raspberry Pi ame Hellowordvaoy save infolder: [/) Hele word v2 ls] ~ Browse for other folders 4p) Python [Helle world v2 create Flde Modified || S Search (© recently Used Bp m Desktop Fla Seatem add 1 Qpen fle in z new tab = pemove “It’s a good habit to be well organised when programming” Variables A variable is data that is stored in memory and can be accessed via a OB ere ou: program is going to start by askina for your fst name, store that ina variable and then print out a welcome message. We're going to adda comment that explains this and create a variable called fistName. Notice how we've capitalised the fist letter ofthe second word to make it easier to read ‘We want the fistName variable to hold the value returned by a function called raw_input, that will ask the user for input. The question is passed into the pint function within brackets, and because this is a string itis enclosed within uotation marks. A string type is basicaly 2 collection of characters Note the extra space we've added after the colon because the user types their input straight after this question. Printing a message OG rzresnncaave firstName, we need to output a welcome message to the screen. We print to the screen in Python using the print function. The print function is followed oy a pair of brackets which enclose the values to print. When using the addition operator with strings, they are joined together. Note how firstName doesn't need to be enclosed by quotation marks because itis thename of a variable. IFt was enclosed in quotation marks, the text firstName would be output. We finish off by adding a W character (new line character) to our output to leave one blank line before we start our next example. Programming in Python on the Raspberry Pi Use Python with Pi aa} General Tool paths Interface Enter tool paths below. Tools you do not need can be left blank. Toolbar eo Terminal: |xterminal 4d Files Bi ; ble-b: Tools jrowser; sensible-browser d pt Templates Grep: Keybindings Printing Terminal Fixing a small issue 7 Tecan image harvere currently using has a small imisconfiguration issue in Geary. Youll know if you have this problem by trying to run your p either the F5 key or going to the Bui electing Execute. IF the issue is present then nothing will happen and youll see a message saying Could net find termina xterm’ Not to worry it's easy to fx. Go to the Edit menu and then select Preferences. Go to the Tools tab and change the value for Tetrinal from xterm to Ixterminal gram with grep ¢d dj Commands Context action: did Testing our program done that part, why not testi It's worth noting that you have os": save before running the program, or anything youve done since you last saved won't be interpreted by Python. Run the program by pressing the F5 key. Input your name by typing it and then pressing the Enter key. Once you have one this, youll seea welcome message. iFthe program exits with the code 0 then everything was run successfully. Press Enter to close the terminal Working with numbers Osten 9 aches for a number by basically repeating the fist 09: ple of ines we did, Once the user gives us a number, well halve square end double it. The raw_input function retums the value thet the user input a string. A string fsa text-based value so we cant perform arithmetic on it.The ef type in Python can only store whole numbers whereas the decimal type g called a type cast, which basically converts a value with one type to another type. Were going toconvert ournumber string to a decimal vaiue because it's likely that decimals willbe involved if we are halving numbers. the number was ofan integer type, any decimal values would simply be cut off the end, without any rounding, This is called truncation. im cansstore numbers with decimals. We're going to do somethin Use Python with Programming in Python on the Raspberry Pi Performing arithmetic 1 Taman atic operon in Python ae 7° the ater ve beng divide and multiply respectively. We've crested three new variables called numberHalved, numberDoubled and numberSquared, Notice that we don't need to specify that they should be decimal because Python gives a type to its variables from the type of their initial value. The number variable is a decimal type, so all values returned from performing arithmetic on that number will also be of a decimal type. nt aut the values we just verted out, converting each flest val int(-The result of halving that runbes + str(nunberalved)) ‘str (nunbarDeubted) } + strinunborsquared) Printing our numbers 11 teotnwrnee performed our arithmetic, we need to print the results using the print function. The print function oniy accepts string values passed to it This means that we need to convert each decimal value to a string Using the str) function before they can be printed. Were using a print statement \with nothing between the quotation marks to print one blankline. This works because the print function always adds a new line at the end ofits output unless solo hepa stent Ppa told otherwise, so printing an empty string just prints @ new line. efits name omits compatby wh te Python pogtonming language Input validation with While loops and If statements. 1 To demonstrate a while loop and if statenents, we will output @ question to the user that requires a yes or no answer. We're going to ask them if they want to continue — and for this we require either a lower-case ‘yes, ora lower-case ino: Awhile loop is a loop that runs until conition is met. In this case, we wil create a variable called yesOrNo and the while loop will ) run while yesO1No is false The yesOrNo variable will be 2 Boolean type that can be either True or False, The variable willbe initiased witha Value of False, or the while loop will not run. ‘Awhile loop has the format ‘while condition} — where any code that is partof the while loop needs to be indented in the lines below the colon, Any code that not indented will not be part of the while loop. This s the same for an if statement. The condition is checked with the comparison operator ==" A single "isan assignment operator ‘whereas a double equals is a comparison operator, Another common comparison operator is''=— which means ‘not equal to We create a variable called ‘tesuit; which hokds the resut of the ‘question, do you want to continue? We then check this result is valid with an ifstaterient. Notice the ‘or operator which allows ‘yo conditions to be tested. Ifthe user inputs a correct value then we set yesOrNo to True, which stops the while loop on the next run, Otherwise, we output an error message and the while loop wil run again, The user can use the Ctil¥C command at the terminal to exit the program at any time. Programming in Python on the Raspberry Pi Use Python with Pi fe Frinecncontinanss) “The print function always adds a new fe ["peinewentinn: line at the end of its output” Continue or exit? TB beeen SS int (incrementing the nner y Sr) =a result that was stored during ss — thewhieloopvithfstemeris SB Pima ftheuserbpec'yes then wewit i 1 print Exiting’ and then call the sys. exit function. You don't have todo anything else for the program to continue because it will simply carry The final step is to print that on wasnt calle 16 recon toetodoarsthina Fe no more lines to interpret Finishing off rogram is exiting. Thisis the last line and Python simply fishes when acter \n can be used any arate quotation marks tke Loops with numbers Lee essey TF ye i Q vistbessinga wii Pobre ra rer ee Pear aut cee ce (less than or equal to) operator as its i a be u stopping condition, The while lo vil be used to increment the number Gist by 1, printing the change on each loo Until the stopping condition is met lows us to know yt ave he count varia igh the wiile loop, Incrementing numbers with a loop 1 The while loop will tun until the Jcountis 6, meaning that it wil being added to the original number, fol wed by the result Finally, the 19, save any changes you have made and run ted, unis incre ry Use Python with Pi What you'll need... Minecraftinip:/mmmojang com/games Python hetpsu/wwwythonorg McPiFoMo http:irogerthat.couk/ McPFoMoror Use Python to code new creations in Minecraft Use Python to code new creations in Minecraft with Python and Forge mod into Minecraft antastic creatio! ‘Sometimes, Minecraft can seer far more than justa game. It's en incredibly creative tool and with the use of Redstone and Command Blocks you can produce some amazing worlds. Wee taking things a step further by enabling you to plug Python code directly nto Minecraft. What you do with itis completely up to your imagination! MCPPy was developed by ‘leap’ and ‘bluepilRabbit’of hetps//mepipywordpress, com, to connect MineCreft Pi Edition with Python on the Raspberry Pi, using open APIs. However with the use of Forge we have put together a package that enables the use of Python in retal Minecraft. Were using Raspbery Jem developed by Alexander Pruss,a Forge mod for Minecraft which implements most of the Raspberry Juice/Pi APL Use Python to code new creations in Minecraft Fe tot Vow Go kms he : Launch Minecraft in Forge mode rt tintin atime ond 0 Launch Minecraft as you a rrommally would, but ater tices es loaging in select the Forge profile. Thisshouid load Minecraft 1.8 with Forge 11.4. You can play around with the latest version of Minecraft and download and install an updated Forge if you wash, but these are the versions weVe found most compatible with Raspberry Jam, Youll now youre running the correct profile when you see the version numbers in the bottom left comer of the window. Creete a new super flat world in singleplayer creative mode and youre ready tO begin coding, ls pr et Fp) dl 0. Use Python with Pi Replace your sminecraft directory Backup minecraftin your homme OV ircctoatyaevingachr you may need to press CTRL#H to view the hidden directories. in terminal mv ~/minecraft ~/minecraft-backup should sulfice Right Backup youreignalminecrat ir and ‘copy over the modded instal rom M 9: ring = x / xy.dist * R # nearest point on major ring ringy = y / xy.dist * R ring_dist_sq = Gcringx)»2 + (y-ringy)«*2 for 2 in rangeCR-r,Rtr): if (ing dist_sq + 22 <= r#z): mic.setBlock(mextx, mey+z, mezty, mcblock) nc = Minecraft() playerPos = me.player.getPos() dram_donut(playerPos.x, playerPos.y + 9, playerPos.z, 18, 9, Lass) I inc.postTochat(“Glass donut done”) dran_donut(playerPos.x, playerPos.y + 9, playerPos.z, 18, 6, WATER_STATIONARY) I nc.postTochat¢“nater donut dene”) By changing the block ID from WATER_STATIONARY you can fll the doughnut with any object type. Try filing the ols with lava, Then try changing outer shell from glessto TNT. Use Python with Pi Common errors Ifyou get a Script not found’ enor, this probably means that you don't have the mod scripts installed in your Minecraft directory, Check that youve replaced _minecraft with the one rom McPFoMo. Ifyou receive a Cannot run program “python” enor your game cannot locate Python. Ensure you've got the latest version of Python instaled, and thatit’s installed in Path. In the Bash shell type export ATH="SPATH/ust/ local/bin/python" wo check Should you come into any problems with memory leskage or infinite loops, you can stop a scrit thar’s running by just typing /python, Cannot find script ret reer Biles stating'Cannot Tee aren cof your Python scripts should Pee ea Peaeaehgeecit set Centers) append'py’to the endof your tun omar er ete) nal Mate ae Reet Pee Seater are erieacer ae elo ae eee) Sec inten aha eras) etree te rater) rr) Use Python with Pi Handle multiple tasks Handle multiple tasks Pi may t thing at a time. Learn how to han« In this tutorial, we will look at how to use the multitasking capabilities within Python to manage multiple tasks. In the standard library, there are three main modules that are available. They are threading, multiprocessing and concurrent. Each has its own strengths and weaknesses, Since these are all part of the standard library, there should not be anything extra that you will need to install First, we will Ook at the threading module. There are two ways that you can use this module. The first is to use it to create new thread objects that can be told to run some target function within your program. The following isa simple example: [import threading TD det my_funco: print(‘Hello World”) [ ny_thread = threading. Thread(target=my_func) my_thread.start() Assuring that your tasks can be partitioned into separate functions, you can create a thread for each of these functions, One thing to be aware fis that these new threads will not start executing the function code nti you cal the start method. At that point, the target function wil start running asynchronous in the background. You can checkto see whether or not a given thread is done by using code lke that below: I iF my thread.is_alive: 1 print(‘This thread is still running’) ‘Atsome point in the main body of your program, you are going to want touse the results from the functions running in these threads. When this happens you can use the join) method ofthe thread object. This halts Handle multiple tasks Use Python with Pi the main core of your program and forces it to wait until the thread ext The thread exits by defauit when the running function exits But how do you waite code that uses threads well’ The firstitem to consider is whether you will be using data that is globally available or whether you are using data that should only be visiole within the current thread. Ifyou do need local only data, you can create a local object that can store these values, The following code stores a string with your author’ name init [ mydata = threading.localQ) [ mydata.myname = ‘Joey Bernard’ This would be code used within the function being run by a thread. if you need to use global data, you need to consider how different threads may ty to use this global data. lf everyone is reading froma ven variable, you won't un into any issues. The problem arises when you have multiple threads that may try to write a given variable. In this case youl end up with a situation known asa race conaltion, where: cone thread may overwrite the data ftom another. In these cases, you wal need to use lock objects to manage access to these global varables. A basic example would look ike: B mytock = threading.Lock() E counter = 0 def funcl(): I mylock.acquire() counter = counter + 1 I mylock.release() As youcan see, you create the lock objectin the main bady of your program Then within the function code, you try to acquire the lock Fit isfiee, you get access tot and itis lacked, f the lock object has already been locked by another thread, then this call to acquire blocks and waits unt the lock has been released. Thisis why you need to be really careful to always have a release statement for every acquire statement. Otherwise, youtl have a bug that will be almost impossible to find after the fact. This also introduces a bottleneck to your program, so you want to make sure that whatever code exists between the acquire and lock isthe bare minimum required to do the necessary work. Thisis the simplest for of lacking mechanism available in Python. your needs Use Python with Pi Handle multiple tasks are greater you can lookat some of the other options to see ifthey might offer better control access, Along with controling access to global data, you may need to communicate directly between threads. This can bbe handled through an event object, which can be used to set aflag to true or false and make that visible to other threads, As an example, the code below shows how to set and use such a flag: Hl eventi = threading.€vent() Tder funcic: 1 event.setQ) | Romincen if eventi.set(): print(‘I got a flag from funct’) ‘Sometimes, the only communication you need is to know when all of the threads have completed some stage of their work Say, you multiple threads loading data files and you need to wait until everyone is done before moving on to the next stage. In this case, you can do so with barrier objects. Below, you can see how you could add a baer to the two threads fabove}. [ barriert = threading Barrier(2) Dicer funcio: I barrierl.wait(Q) der func2c): | barrier1.wait() Inthe above code, you need to set how many threads will take part in the barrier object when you create it. Then, when threads use it and call the wait method, they will block until all of the threads call the wait method, The threading module isa light, fast and easy method to add the ability divide up the processing within your code, but it does suffer from one major issue. Within the Python core engine, there is a structure Handle multiple tasks called the GIL (global interpreter lock) The GIL is Used to control access to certain core functions and data within the Python interpreter. This means that at certain points, your threads will run only one ata time. This can introduce a serious bottleneck in some situations. Ifyou are in this boat, then you may need to use the multiprocessing module. This module uses subprocesses to bypass the GIL completely in order toget true parallel operation. In its most basic use ase, you could use something like the code below toget behaviour similar to what you get with threads: H import multiprocessing H cer finamey: I I I print(‘hello’, name) p = multiprocessing.Process(target=f, args=(‘bob’,)) Pp.starto Tp.0ing) This appears to be the same on the surface, but what ishappening in the backend is radically different. The CORN RRM rl accel) 7 nen emery eae om) herun rea eee Use Python with Pi process object starts up a new Python engine in one of a number of ways. The default on UNIX systems, like the Pi, is to fork a new process. The fork method essentially makes @ complete copy of the current Python engine and executes the given function Another method isto spawn a new Python engine. Inthe spawn method, only the parts of the current Python engine that is needed for the new Python engine. fyoudo need to change it, you can use the following code: I muttiprocessing.set_start_ mnethod(‘spawn") ffyou need to start many subprocesses, this may help speed your code up. The set_start_method should only ever be called once in a given program. Hopefully ths tutorial has given you some ideas on how to include the ability to manage multiple tasks in parallel. This can be a powerful tool to make the software design of your project more flexible and capable. Be aware that we have only been able to cover the most basic topics in such a short tutorial ees sisprare B procz_output = proc2.stdout ert) Use Python with Pi Create a Pi-powered virtual reality setup ver Create a 8GBSD card simceme Powered (optional) virtual reality setup e Raspberry Pi, Python-VRZero ule Pi3D to edit or make ments virtual reality Virtual Realty s huge now and has come a long way since the concepts and CGl visuals of Stephen King's Lawnmower Man. ttis one of the fastest >> =: RESTART >>> Blue-who Finder Found 1 devices 68:48:98:3A:BB:7C - MI6 Mobile Surveillance Check to see who is in the building Checking sun, 10 Jul 2016 19:40:06 TeCoEd is in The Boss is still out, Facebook time! sherlock is still out on a case Another response, the next device is found 16%: before, check and respond, in |, using an fF statement to see ifthe device is not found, Remember to use the new variable name, in this ‘example, device_one.fitfinds the named device then print outa message, line 2. If it does notfind the device, ine 3, then print outa message to notify the user, ne 4, ‘Add these lines of code undemeath the previous line. Save and run the program to find the two particular devices within your location. if Gevice_one != None): print “Linux Laptop is in” else print “Linux Laptop is out” Add an alternative action 7 ‘To customise the projectfurther you could add your own action tothe devices on being discovered. For example, use a strip OFLEDS to flash ‘each time a device enters the location and is detected. Or use individual LEDS for each individual device to incicate ifthe device is present or not, How about combining the program with an LCD screen as a message board for who is present and who is out? For move inspiration, check out httpsi/www.youtube.com/ watch?v=qUZQv87GVdQ_ Every issue of your subscription, delivered direct to your door. Print & digital editions available. (WHAPPE ~ BALE ~ SOUTHGATE » BRONZE » CARRICK - LNA From photography to music and technology to gaming, there’s something for everyone. h har Zs 7 ieee A NMC Lr Nps Photogra| iy. TH FENDER ‘V Nohidden costs by Shippingincluded in all prices 9 We deliver to over 200 countries) Secure online payment my ritemagazines Official Magazine Subscription Store FUTURE HOW TO USE EVERYTHING YOU NEED TO KNOW ABOUT ACCESSING YOUR NEW DIGITAL REPOSITORY Toaccess FileSilo, please visit www.filesilo.co.uk/1710-2 Followtheon-screen Onceyouhave O instructionstocreate ° O loggedin, youare anaccountwithoursecure freetoexplorethewealthof * FileSilosystem, login and contentavailableon FileSilo, = unlock the bookazineby from great video tutorials answeringasimplequestion : andexclusiveoniineguides about it. You can tosuperbdownloadable : thenaccessthe : resources, Andthe more contentforfreeat ° bookazinesyoupurchase, © ( any time,and themoreyourinstantly downloaditto accessiblecollectionof —- yourdesktop, _: digitalcontentwillgrow. = Making a PyGame - An introduction to Game Development 0. Youcanaccess FileSiloonany desktop, tablet or smartphone deviceusing any popular browser (such © asSafari, Firefox or Google Chrome). However, we © recommendthat you usea desktop todownload content, as youmnay notbe * abletodawnloadfilesto yourphone ortablet, : 0. Hyouhaveany : problems with accessing contenton FileSilo, or withthe registration process, take alookattheFAQsonline oremailfilesilohel futurenet.com, a ee ee ee ee ee ee ee ee Ae ee «ee ee ee eee eee eee \A4AAAAAAAAAAaAaaaad I4A44AAAAAAAAAALAAA SA \4A44AAAAAAAALALAAA A I4444AAAAAALALALALAS VVVVVPP Orr VPrVrVrrr 444A 444A de ADA RAR Python The Complete Manual Vv Learn to use ye Teamt to create playable games, J apps with ncanbe Vv Program games v Master bulding apps v Put Python to work C yi y for functional projects such as writing clean cox at id ¥ Amazing projects Vv Free online resources 9 load. ay ra N c x“ fe] fe] cy Get creative and complete projet

    También podría gustarte

    Description