Posted by

Tkinter Tutorial Python Pdf Books

All Coding Club Books currently teach Python 3. This is freely available and easy to install on Windows, Mac and Linux computers. Python 3 installers. Who are Digital Skills? Digital Skills is a small company specialising in creating hands-on, easy-to-follow, training material. Over our 15 years in existence we.

Sebsauvage.net- Snyppets - Python snippets Snyppets - Python snippets This page contains a bunch of miscellaneous Python code snippets, recipes, mini-guides, links, examples, tutorials and ideas, ranging from very ( very) basic things to advanced. I hope they will be usefull to you. All snippets are kept in a single HTML page so that you can easily ❶save it for offline reading (and keep on a USB key) ❷search in it. Note that scripts that do some web-scraping may not work anymore due to website changes. The web is an evolving beast:-) (Don't forget to read my main Python page ( ): there is handful of other programs and a guides.).

Import ftplib # We import the FTP module session = ftplib.FTP('myserver.com','login','passord') # Connect to the FTP server myfile = open('toto.txt','rb') # Open the file to send session.storbinary('STOR toto.txt', myfile) # Send the file myfile.close() # Close the file session.quit() # Close FTP session Queues (FIFO) and stacks (LIFO) Python makes using queues and stacks a piece of cake (Did I already say 'piece of cake'?). No use creating a specific class: simply use list objects. For a stack (LIFO), stack with append() and destack with pop(). >>>a = [5,8,9] >>>a.append(11) >>>a [5, 8, 9, 11] >>>a.pop(0) 5 >>>a.pop(0) 8 >>>a [9, 11] As lists can contain any type of object, you an create queues and stacks of any type of objects!

(Note that there is also a Queue module, but it is mainly usefull with threads.) A function which returns several values When you're not accustomed with Python, it's easy to forget that a function can return just any type of object, including tuples. This a great to create functions which return several values.

This is typically the kind of thing that cannot be done in other languages without some code overhead. Import HTMLParser, urllib class linkParser(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.links = [] def handle_starttag(self, tag, attrs): if tag=='a': self.links.append(dict(attrs)['href']) htmlSource = urllib.urlopen('p = linkParser() p.feed(htmlSource) for link in p.links: print link For each HTML start tag encountered, the handle_starttag() method will be called. For example will trigger the method handle_starttag(self,'A',[('href','See also all others handle_*() methods in Pyhon manual. (Note that HTMLParser is not bullet-proof: it will choke on ill-formed HTML. In this case, use the sgmllib module, go back to regular expressions or use BeautifulSoup.) Get all links in a web page (3) Still hungry? Beautiful Soup is a Python module which is quite good at extracting data from HTML.

Beautiful Soup's main advantages are its ability to handle very bad HTML code and its simplicity. Its drawback is its speed (it's slow). You can get it from.

Tkinter Tutorial Python Pdf Books

Import os.path def processDirectory ( args, dirname, filenames ): print 'Directory',dirname for filename in filenames: print ' File',filename os.path.walk(r'c: windows', processDirectory, None ) os.path.walk() works with a callback: processDirectory() will be called for each directory encountered. Dirname will contain the path of the directory. Filenames will contain a list of filenames in this directory.

You can also use os.walk(), which works in a non-recursive way and is somewhat easier to understand. Import BaseHTTPServer, SimpleHTTPServer server = BaseHTTPServer.HTTPServer((',80),SimpleHTTPServer.SimpleHTTPRequestHandler) server.serve_forever() This webserver will serve files in the current directory. You can use os.chdir() to change the directory. This trick is handy to serve or transfer files between computers on a local network.

Note that this webserver is pretty fast, but can only serve one HTTP request at time. It's not recommended for high-traffic servers. If you want better performance, have a look at asynchronous sockets (asyncore, Medusa.) or multi-thread webservers. Creating and raising your own exceptions Do not consider exception as nasty things which want to break you programs. Exceptions are you friend. Exceptions are a Good Thing.

Exceptions are messengers which tell you that something's wrong, and what is wrong. And try/except blocks will give you the chance to handle the problem.

In your programs, you should also try/catch all calls that may fall into error (file access, network connections.). It's often usefull to define your own exceptions to signal errors specific to your class/module. Here's an example of defining an exception and a class (say in myclass.py). Import myclass myobject = myclass.myclass() try: myobject.dosomething(-2) except myclass.myexception: print 'oops!

Myclass tells me I did something wrong.' This is better! You have a chance to do something if there's a problem. Scripting Microsoft SQL Server with Python If you have Microsoft SQL Server, you must have encountered this situation where you tell yourself «If only I was able to script all those clicks in Enterprise Manager (aka the MMC)!». It's possible to script in Python whatever you can do in the MMC. You just need the win32all python module to access COM objects from within Python (see ) (The win32all module is also provided with ActiveState's Python distribution: ) Once installed, just use the SQL-DMO objects.

For example, get the list of databases in a server. Import dbi, odbc conn = odbc.odbc('mydsn/login/password') c = conn.cursor() c.execute('select clientid, name, city from client') print c.fetchall() Nice and easy!

You can also use fetchone() or fetchmany(n) to fetch - respectively - one or n rows at once. Note: On big datasets, I have quite bizarre and unregular data truncations on tables with a high number of columns. Is that a bug in ODBC, or in the SQL Server ODBC driver? I will have to investigate. Accessing a database with ADO Under Windows, you can also use ADO ( Microsoft ActiveX Data Objects) instead of ODBC to access databases. The following code uses ADO COM objects to connect to a Microsoft SQL Server database, retreive and display a table. Import win32com.client connexion = win32com.client.gencache.EnsureDispatch('ADODB.Connection') connexion.Open('Provider='SQLOLEDB';Data Source='myserver';Initial Catalog='mydatabase';User ID='mylogin';Password='mypassword';') recordset = connexion.Execute('SELECT clientid, clientName FROM clients')[0] while not recordset.EOF: print 'clientid=',recordset.Fields(0).Value,' client name=',recordset.Fields(1).Value recordset.MoveNext() connexion.Close() For ADO documentation, see MSDN: CGI under Windows with TinyWeb TinyWeb is a one-file webserver for Windows (the exe is only 53 kb).

It's fantastic for making instant webservers and share files. TinyWeb is also capable of serving CGI. Let's have some fun and create some CGI with Python!

First, let's get and install TinyWeb: • Get TinyWeb from (it's free, even for commercial use! Fridge Makes Cracking Sound. ) and unzip it to c: somedirectory (or any directory you'd like). • Create the ' www' subdirectory in this directory • Create index.html in the www directory.

Print 'Content-type: text/html' print print 'Hello, this is Python talking!' • Make sure Windows always uses python.exe when you double-clic.py files. (SHIFT+rightclick on a.py file, ' Open with.' , choose python.exe, check the box ' Always use this program.' , click Ok) • Point your browser at You should see ' Hello, this is Python talking!' (and not the source code).

If it's ok, you're done! Now you can make some nice CGI.

(If this does not work, make sure the path to python.exe is ok and that you used an absolute path in tinyweb's command line.) Note that this will never be as fast as mod_python under Apache (because TinyWeb will spawn a new instance of the Python interpreter for each request on a Python CGI). Thus it's not appropriate for high-traffic production servers, but for a small LAN, it can be quite handy to serve CGI like this. Refer to Python documentation for CGI tutorials and reference. • Hint 1: Don't forget that you can also use TinySSL, which is the SSL/HTTPS enabled version of TinyWeb. That's fantastic for making secure webservers (especially to prevent LAN sniffing, when authentication is required). • Hint 2: If you wrap your Python CGI with, you'll be able to run your CGI on computers where Python is not installed.

Sub-hint: Compress all exe/dll/pyd with, and you can take the whole webserver and its CGI on a floppy disk and run it everywhere! (A typical ' Hello, world!' CGI example and TinyWeb weight together only 375 kb with Python 2.2!) • Hint 3: When serving files (not CGI), TinyWeb uses Windows file extension Content-type mapping (like.zip = application/x-zip-compressed). If you find that Content-type is wrong, you can correct using the following file:. • Hint 4: Under Windows there is a trick to send binary files correctly in CGI: You need to change stdout mode from text mode to binary mode.

This is required on Windows only. Import sys if sys.platform == 'win32': import os, msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) (code taken from ) Creating.exe files from Python programs Like Sun's Java or Microsoft's.Net, if you want to distribute your Python programs, you need to bundle the virtual machine too. You have several options: py2exe, cx_Freeze or pyInstaller. Py2exe py2exe provides an easy way to gather all necessary files to distribute your Python program on computers where Python is not installed. For example, under Windows, if you want to transform myprogram.py into myprogram.exe, create the file setup.py as follows. Python setup.py py2exe py2exe will get all dependant files and write them in the dist subdirectory.

You will typically find your program as.exe, pythonXX.dll and complementary.pyd files. Your program will run on any computer even if Python is not installed. This also works for CGI. (Note that if your program uses tkinter, there is a.) Hint: Use to compress all dll/ exe/ pyd files. This will greatly reduce file size. Use: upx --best *.dll *.exe *.pyd (Typically, python22.dll shrinks from 848 kb to 324 kb.) Note that since version 0.6.1, py2exe is capable of creating a single EXE (pythonXX.dll and other files are integrated into the EXE). Try: sys.stdout.write(' n') sys.stdout.flush() except IOError: class dummyStream: '' dummyStream behaves like a stream but does nothing.

'' def __init__(self): pass def write(self,data): pass def read(self,data): pass def flush(self): pass def close(self): pass # and now redirect all default streams to this dummyStream: sys.stdout = dummyStream() sys.stderr = dummyStream() sys.stdin = dummyStream() sys.__stdout__ = dummyStream() sys.__stderr__ = dummyStream() sys.__stdin__ = dummyStream() This way, if the program starts in console-less mode, it will work even if the code contains print statements. And if run in command-line mode, it will print out as usual. (This is basically what I did in webGobbler, too.) pyInstaller pyInstaller is the reincarnation of McMillan Installer. It can also create one-file executables.

You can get it from Unzip pyInstaller in the pyinstaller_1.1 subdirectory, then do. Try: import psyco psyco.full() except: pass This way, if psyco is installed, your program will run faster. If psyco is not available, your program will run as usual. (And if psyco is still not enough, you can rewrite the code which is too slow in C or C++ and wrap it with SWIG ().) Note: Do not use Psyco when debugging, profiling or tracing your code. You may get innacurate results and strange behaviours. Regular expressions are sometimes overkill I helped someone on a forum who wanted process a text file: He wanted to extract the text following 'Two words' in all lines starting whith these 2 word.

He had started writing a regular expression for this: r = re.compile('Two sword s(.*?)'). His problem was better solved with. [.] for line in file: if line.startswith('Two words '): print line[10:] Regular expression are sometime overkill.

They are not always the best choice, because: • They involve some overhead: • You have to compile the regular expression ( re.compile()). This means parsing the regular expression and transforming it into a state machine. This consumes CPU time. • When using the regular expression, you run the state machine against the text, which make the state machine change state according to many rules. This is also eats CPU time. • Regular expression are not failsafe: they can fail sometimes on specific input. You may get a ' maximum recusion limit exceeded' exception.

This means that you should also enclose all match(), search() and findall() methods in try/except blocks. • The Zen of Python ( import this:-) says « Readability counts». That's a good thing. And regular expression quickly become difficult to read, debug and change. Besides, string methods like find(), rfind() or startwith() are very fast, much faster than regular expressions. Do not try to use regular expressions everywhere. Often a bunch of string operations will do the job faster.

Executing another Python program. Traceback (most recent call last): File 'cx_Freeze initscripts console.py', line 26, in? Exec code in m.__dict__ File 'test.py', line 20, in? File 'test.py', line 14, in main File 'C: Python24 Lib lib-tk Tkinter.py', line 1569, in __init__ _tkinter.TclError: Can't find a usable init.tcl in the following directories: [.] Nasty, isn't it? The reason it fails is that Tkinter needs the runtime tcl scripts which are located in C: Python24 tcl tcl8.4 and C: Python24 tcl tk8.4. So let's copy these scripts in the same directory as you application. You building batch becomes.

#!/usr/bin/python # -*- coding: iso-8859-1 -*- import os, os.path # Take the tcl/tk library from local subdirectory if available. If os.path.isdir('libtcltk84'): os.environ['TCL_LIBRARY'] = 'libtcltk84 tcl8.4' os.environ['TK_LIBRARY'] = 'libtcltk84 tk8.4' import Tkinter class myApplication: def __init__(self,root): self.root = root self.initializeGui() def initializeGui(self): Tkinter.Label(self.root,text='Hello, world').grid(column=0,row=0) def main(): root = Tkinter.Tk() root.title('My application') app = myApplication(root) root.mainloop() if __name__ == '__main__': main() Now you can properly package and distribute Tkinter-enabled applications. (I used this trick in.) Possible improvement: You surely could get rid of some tcl/tk script you don't need. Example: bin libtcltk84 tk8.4 demos (around 500 kb) are only tk demonstrations. They are not necessary. This depends on which features of Tkinter your program will use.

(cx_Freeze and - AFAIK - all other packagers are not capable of resolving tcl/tk dependencies.) A few Tkinter tips Tkinter is the basic GUI toolkit provided with Python. Here's a simple example. Import Tkinter class myApplication: #1 def __init__(self,root): self.root = root #2 self.initialisation() #3 def initialisation(self): #3 Tkinter.Label(self.root,text='Hello, world!' ).grid(column=0,row=0) #4 def main(): #5 root = Tkinter.Tk() root.title('My application') app = myApplication(root) root.mainloop() if __name__ == '__main__': main() #1: It's always better to code a GUI in the form of a class. It will be easier to reuse your GUI components. #2: Always keep a reference to your ancestor.

You will need it when adding widgets. #3: Keep the code which creates all the widgets clearly separated from the rest of the code. It will be easier to maintain. #4: Do not use the.pack(). It's usually messy, and painfull when you want to extend your GUI. Grid() lets you place and move your widgets elements easily. Never ever mix.pack() and.grid(), or your application will hang without warning, with 100% CPU usage.

#5: It's always a good idea to have a main() defined. This way, you can test the GUI elements by directly by running the module. I lack time, so this list of recommendations could be much larger after my experience with. Tkinter file dialogs Tkinter is provided with several basic dialogs for file or directory handling. There's pretty easy to use, but it's good to have some examples: Select a directory. Import Tkinter import tkFileDialog myFormats = [ ('Windows Bitmap','*.bmp'), ('Portable Network Graphics','*.png'), ('JPEG / JFIF','*.jpg'), ('CompuServer GIF','*.gif'), ] root = Tkinter.Tk() filename = tkFileDialog.asksaveasfilename(parent=root,filetypes=myFormats,title='Save image as.'

) if len(filename) >0: print 'Now saving as%s'% (filename) Including binaries in your sources Sometime it's handy to include small files in your sources (icons, test files, etc.) Let's take a file (myimage.gif) and convert it in base64 (optionnaly compressing it with zlib). # Read from a file: file = open('a_file.dat','rb') data = file.read() file.close() # Read from an URL: import urllib url = urllib.urlopen('html = url.read() url.close() But what happens if the file is 40 Gb, or the website sends data non-stop? You program will eat all the system's memory, slow down to a crawl and probably crash the system too. You should always bound your read().

For example, I do not expect to process files larger than 10 Mb, nor read HTML pages larger than 200 kb, so I would write. If str(a) == str(b): print 'a and b are equal.' Else: print 'a and b are different!' Why is 0.9+0.8 different than 1.7? Because the computer can only handle bits, and you cannot precisely represent all numbers in binary.

The computer is good a storing values such as 0.5 (which is 0.1 in binary), or 0.125 (which is 0.001 in binary). But it's not capable of storing the exact value 0.3 (because there is no exact representation of 0.3 in binary). Thus, as soon as you do a=1.7, a does not contain 1.7, but only a binary approximation of the decimal number 1.7. Get user's home directory path It's handy to store or retreive configuration files for your programs.

Import os.path print os.path.expanduser('~') Note that this also works under Windows. (It points to the 'Document and settings' user's folder, or even the network folder if the user has one.) Python's virtual machine Python - like Java or Microsoft.Net - has a virtual machine. Python has a specific bytecode. It's an machine language like Intel 80386 or Pentium machine language, but there is no physical microprocessor capable of executing it. The bytecode runs in a program which simulates a microprocessor: a virtual machine.

This is the same for Java and.Net. Java's virtual machine is named JVM (Java Virtual Machine), and.Net's virtual machine is the CLR (Common Language Runtime) Let's have an example: mymodule.py. C: >python Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type 'help', 'copyright', 'credits' or 'license' for more information. >>>import mymodule >>>print mymodule.myfunction(5) I have 5 92 >>>Ok, easy. See the mymodule.pyc file which appeared?

This is the 'compiled' version of our module, the Python bytecode. This file contains instructions for the Python virtual machine. The.pyc files are automatically generated by Python whenever a module is imported. Python can directly run the.pyc files if you want. You could even run the.pyc without the.py. If you delete the.pyc file, it will be recreated from the.py. If you update the.py source, Python will detect this change and automatically update the corresponding.pyc.

Want to have a peek in the.pyc bytecode to see what it looks like? 3 9 LOAD_FAST 0 (a) # Load variable a on the stack. 12 LOAD_CONST 2 (3) # Load the value 3 on the stack 15 BINARY_MULTIPLY # Multiply them 16 STORE_FAST 1 (b) # Store result in variable b Python also tries to optimise the code. For example, the string 'I have' will not be reused after line 2. So Python decides to reuse the adresse of the string (1) for variable b. The list of instructions supported by the Python virtual machine is at SQLite - databases made simple is a tremendous database engine. It has some drawbacks: • Not designed for concurrent access (database-wide lock on writing).

• Only works locally (no network service, although you can use things like ). • Does not handle foreign keys. • No rights management (grant/revoke). Advantages: • very fast (faster than mySQL on most operations).

• Respects almost the whole SQL-92 standard. • Does not require installation of a service. • No database administration to perform. • Does not eat computer memory and CPU when not in use.

• SQLite databases are compact • 1 database = 1 file (easy to move/deploy/backup/transfer/email). • SQLite databases are portable across platforms (Windows, MacOS, Linux, PDA.) • SQLite is (data consistency is assured even on computer failure or crash) • Supports transactions • Fields can store Nulls, integers, reals (floats), text or blob (binary data). • Can handle up to 2 Tera-bytes of data (although going over 12 Gb is not recommended). • Can work as a in-memory database (blazing performances!) SQLite is very fast, very compact, easy to use.

It's god gift for local data processing (websites, data crunching, etc.). And it's not only free, it's also public domain (no GPL license headaches). SQLite engine can be accessed from a wide variety of languages. (Thus SQLite databases are also a great way to exchange complex data sets between programs written in different languages, even with mixed numerical/text/binary data.

No use to invent a special file format or a complex XML schema with base64-encoded data.) SQLite is embeded in Python 2.5. For Python 2.4 and ealier, it must be installed separately: Here's the basics. #!/usr/bin/python # -*- coding: iso-8859-1 -*- from sqlite3 import dbapi2 as sqlite # Connect to an existing database con = sqlite.connect('mydatabase.db3') cur = con.cursor() # Get row by row print 'Row by row:' cur.execute('select id, name from clients order by name;') row = cur.fetchone() while row: print row row = cur.fetchone() # Get all rows at once: print 'All rows at once:' cur.execute('select id, name from clients order by name;') print cur.fetchall() cur.close() con.close() This outputs. Row by row: (7, u'Ella Fitzgerald') (5, u'John Smith') (8, u'Louis Armstrong') (9, u'Miles Davis') All rows at once: [(7, u'Ella Fitzgerald'), (5, u'John Smith'), (8, u'Louis Armstrong'), (9, u'Miles Davis')] Note that creating a database and connecting to an existing one is the same instruction ( sqlite.connect()). To manage your SQLite database, there is a nice freeware under Windows: SQLiteSpy () Hint 1: If you use sqlite.connect(':memory:'), this creates an in-memory database. As there is no disk access, this is a very very fast database. (But make sure you have enough memory to handle your data.) Hint 2: To make your program compatible with Python 2.5 and Python 2.4+pySqlLite, do the following.

Try: from sqlite3 import dbapi2 as sqlite # For Python 2.5 except ImportError: pass if not sqlite: try: from pysqlite2 import dbapi2 as sqlite # For Python 2.4 and pySqlLite except ImportError: pass if not sqlite: # If module not imported successfully, raise an error. Raise ImportError, 'This module requires either: Python 2.5 or Python 2.4 with the pySqlLite module (# Then use it con = sqlite.connect('mydatabase.db3'). This way, sqlite wil be properly imported whenever it's running under Python 2.5 or Python 2.4. Links: • pySQLite homepage: • SQLite homepage (usefull information on the database engine itself): Dive into Python You're programming in Python? Then you should be reading. The book is free.

I can't imagine decent Python programing without reading this book. At least download it.now! This is a must-read. This book is available for free in different formats (HTML, PDF, Word 97.). Plenty of information, good practices, ideas, gotchas and snippets about classes, datatypes, introspection, exceptions, HTML/XML processing, unit testing, webservices, refactoring, whatever.

You'll thank yourself one day for having read this book. Creating a mutex under Windows I use a mutex in so that the InnoSetup uninstaller knows webGobbler is still running (and that it shouldn't be uninstalled while the program is still running). That's a handy feature of InnoSetup.

CTYPES_AVAILABLE = True try: import ctypes except ImportError: CTYPES_AVAILABLE = False WEBGOBBLER_MUTEX = None if CTYPES_AVAILABLE and sys.platform=='win32': try: WEBGOBBLER_MUTEX=ctypes.windll.kernel32.CreateMutexA(None,False,'sebsauvage_net_webGobbler_running') except: pass I perform an except:pass, because if the mutex can't be created, it's not a big deal for my program (It's only an uninstaller issue). Your mileage may vary. This mutex will be automatically destroyed when the Python program exits. Urllib2 and proxies With urllib2, you can use proxies.

Try: urlfile = urllib2.urlopen('except urllib2.HTTPError, exc: if exc.code == 404: print 'Not found!' Else: print 'HTTP request failed with error%d (%s)'% (exc.code, exc.msg) except urllib2.URLError, exc: print 'Failed because:', exc.reason This way, you can check for 404 and other HTTP error codes. Note that urllib2 will not raise an exception on 2xx and 3xx codes. The exception urllib2.HTTPError will be raised with 4xx and 5xx codes (which is the expected behaviour). (Note also that HTTP 30x redirections will be automatically and transparently handled by urllib2.) urllib2: What am I getting? When you send a HTTP request, this may return html, images, videos, whatever.

In some cases you should check that the type of data you're receiving is what you expected. To check the type of document you're receiving, look at the MIME type ( Content-type) header. Document type is Date: Thu, 23 Mar 2006 15:13:29 GMT Content-Type: text/html; charset=iso-8859-1 Server: Apache X-Powered-By: PHP/5.1.2-1.dotdeb.2 Connection: close Reading (and writing) large XLS (Excel) files In one of my projects, I had to read large XLS files. Of course you can access all cells content through COM calls, but it's painfully slow. There's a simple trick: Simply ask Excel to open the XLS file and save it in CSV, then use Python's CSV module to read the file! This is the fastest way to read large XLS data files.

Import os import win32com.client filename = 'myfile.xls' filepath = os.path.abspath(filename) # Always make sure you use an absolute path! # Start Excel and open the XLS file: excel = win32com.client.Dispatch('Excel.Application') excel.Visible = True workbook = excel.Workbooks.Open(filepath) # Save as CSV: xlCSVWindows =0x17 # from enum XlFileFormat workbook.SaveAs(Filename=filepath+'.csv',FileFormat=xlCSVWindows) # Close workbook and Excel workbook.Close(SaveChanges=False) excel.Quit() Hint: You can use this trick the other way round (generate a CSV in Python, open with Excel) to import a large quantity of data into Excel. This is much faster than filling data cell by cell through COM calls. Hint: When using excel.Workbooks.Open(), always make sure you use an asbolute path with os.path.abspath().

Hint: You can also ask excel to save as HTML, then parse the HTML with htmllib, sgmllib or BeautifulSoup. You will be able to get more information, including formatting, colors, cells span, document author or even formulas! Hint: For Excel VBA documentation, search *.chm in C: Program Files Microsoft Office Example: For Excel 2000, it's C: Program Files Microsoft Office Office 1036 VBAXL9.CHM Hint: If you want to find the corresponding VBA code for an action without hunting through the VBA Help file, just record a macro of the action and open it! This will automatically generate the VBA code (which can be easily translated into Python). I created an example video of this trick (in French, sorry): Hint: Sometimes, you'll need Excel constants.

To get the list of constants: • Run makepy.py (eg. C: Python24 Lib site-packages win32com client makepy.py) • In the list, choose ' Microsoft Excel 9.0 Object Library (1.3)' (or similar) and click ok.

• Have a look in C: Python24 Lib site-packages win32com gen_py directory. You will find the wrapper (such as 000-0000-C000046x0x1x3.py) • Open this file: it contains Excel constants and their values (You can copy/paste them in your code.) For example. Traceback (most recent call last): File 'a.py', line 10, in?

Print myfunction(0) File 'a.py', line 7, in myfunction b = fifths(value) * 100 File 'a.py', line 4, in fifths return 5/a ZeroDivisionError: integer division or modulo by zero Hint: You can also simply use traceback.print_exc(file=sys.stdout) to print the stacktrace on screen. Hint: Mixing this trick with can save your day. Detailed error messages = bugs more easily spotted.

Filtering out warnings Sometimes, Python displays warning. While they are usefull and should be taken care of, you sometimes want to disable them.

Here's how to filter them. Import warnings warnings.filterwarnings(action = 'ignore',message='.*?no locals ( ) in functions bound by Psyco') (I use to filter this specific Psyco warning.) message is a regular expression.

Make sure you do not filter too much, so that important information is not thrown away. Saving an image as progressive JPEG with PIL (Python Imaging Library) is very good graphics library for image manipulation (This is the library I used in ). Motorola Hacking there. Here's how to save an Image object in progressive JPEG. This may seem obvious, but hey. Symbol → number The usual suspect is ASCII. In ASCII, the letter 'a' is the number 97.

The question mark '?' Is the number 67. But ASCII is far from a universal standard. There are plenty of other character sets, such as EBCDIC, KOI8-R for Russian characters, ISO-8852-1 for latin characters (accent characters, for example), Big5 for traditional chinese, Shift_JIS for Japanese, etc. Every country, culture, language has developed its own character set. This is a big mess, really. An international effort tries to standardise all this: UNICODE.

Unicode is a huge table which tells which number to use for each symbol. Some examples. Number → Bits ASCII uses the simple mapping: 1 ASCII code (0.127) = 1 byte (8 or 7 bits). It's ok for ASCII, because ASCII uses only numbers from 0 to 127. It fits in a byte. But for Unicode and other charsets, that's a problem: 8 bits are not enough. These charsets require other encodings.

Most of them use a multi-byte encoding (a character is represented by several bytes). For Unicode, there are several encodings. The first one is the raw 16 bits Unicode.

16 bits (2 bytes) per character. But as most texts only use the lower part of the Unicode table (codes 0 to 127), that's huge waste of space. That's why UTF-8 was invented.

That's brilliant: For codes 0 to 127, simply use 1 byte per character. Just like ASCII. If you need special, less common characters (128 to 2047), use two bytes. If you need more specific characters (2048 to 65535), use three bytes. This is the same for emails: Any good email client will indicate which charset/encoding the text is encoded in. Hint: Some encodings are specific to some charsets.

For example, UTF-8 is only used for Unicode. So if I receive UTF-8 encoded data, I know its charset is Unicode.

Python and Unicode Python supports directly Unicode and UTF-8. Use them as much as possible.

Your programs will smoothly support international characters. First, you should always indicate which charset/encoding your Python source uses, such as. >>>import sys >>>a = u' u0153uvre' >>>print a.encode(sys.stdout.encoding,'replace')?uvre >>>Unicode characters which cannot be displayed by the console will be converted to '?' Special note: When dealing with external sources (files, databases, stdint/stdout/stderr, API such as Windows COM or registry, etc.) be carefull: Some of these will not communicate in Unicode, but in some special charset. You should properly convert to and from Unicode accordingly.

For example, to write Unicode strings to an UTF-8 encoded file, you can do. Class clientFileReader: def __init__(self,filename): self.file=open(filename,'r') self.file.readline() # We discard the first line. Def close(self): self.file.close() def __iter__(self): return self def next(self): line = self.file.readline() if not line: raise StopIteration() return ( line[:13], int(line[13:]) ) To create an iterator: • Create a __iter__() method which returns the iterator (which happen to be ourselves!) • The iterator must have a next() method which returns the next item. • The next() method must raise the StopIteration() exception when no more data is available.

It's as simple as this! Then we can simply use our file reader as. ClientFile = clientFileReader('file.txt') for (country,nbclients) in clientFile: print 'We have',nbclients,'clients in',country clientFile.close() See? ' for (country,nbclients) in clientFile:' is a higher level construct which makes the code much more readable and hides the complexity of the underlying file format. This is much better than chopping file lines in the main loop.

Parsing the command-line It's not recommended to try to parse the command-line ( sys.argv) yourself. Parsing the command-line is not as trivial as it seems to be. Python has two good modules dedicated to command-line parsing: getopt ant optparse. They do their job very well (They take care of mundane tasks such as parameters quoting, for example). Optparse is the new, more Pythonic and OO module.

Yet I often prefer.

News about the dynamic, interpreted, interactive, object-oriented, extensible programming language Python If you are about to ask a question, please consider. Homework-style questions will be removed, and you'll be encouraged to post there instead. Please don't use URL shorteners. Reddit filters them out, so your post or comment will be lost. I've read a LOT of programming books, so I decided it was time to give one back to the community. Since I love working with the Tkinter library to create GUIs, I decided to write a book which will hopefully help teach newbies how to get started with writing their own GUI applications. I've finally finished and released Learn Tkinter By Example.

It's free, released under Creative Commons with the Python source code released with the MIT licence. The Latex source code is also available alongside the PDF book, should anybody want that for any reason. The book is available from my Github here, along with more details: All feedback is welcome (preferably constructive rather than just insults!) As the book states towards the end, I am completely open to working on developing it further if need be.

Source code comments, questions, and changes can be sent to me through Github, and anything book-related can be messaged to me directly here or through twitter (@Dvlv292). I hope this book will be of use to some of you. Easy and readable syntax (In my opinion) Comes preinstalled with python No licence issues I just started on making a GUI for an existing back end at a job I have this summer.

I am using Tkinter and it is very easy to use, as long as you find a decent tutorial with images as to what certain lines do. As mentioned writing more code in Tkinter, I find that to be a pretty bad argument.

You can make functions that incorporate making a certain type of window, and so really if you are using proper programming techniques (if you write the same several lines of code over and over, you are programming wrong) then you can make a very generalized function that will make a window with a fairly simple syntax yet still customizable. This, and the fact that it comes with Python makes it pretty worth it for GUI development. Another advantage is Qt Designer, a program to (as the name implies) design a user interface in a graphical way. You can save the result as an XML file, load that into your program and you'll have your window set up automatically.

Unless I am very much mistaken you have to create TkInter user interfaces programmatically. Using Designer saves an enormous amount of code, and it makes it much easier to change the user interface later on. The only thing I would like to add is, if you're interested in using Qt as a user interface, look into PySide. It's an alternative Python binding for Qt that is 99% identical to PyQt, but it is a little more 'pythonic', and it has a much more lenient license.