Dataset Viewer
Auto-converted to Parquet
input
stringlengths
16
30.2k
instruction
stringlengths
12
148
output
stringlengths
11
27.3k
I am using the Photoshop's javascript API to find the fonts in a given PSD. Given a font name returned by the API, I want to find the actual physical font file that that font name corresponds to on the disc. This is all happening in a python program running on OSX so I guess I'm looking for one of: Some Photoshop javascript A Python function An OSX API that I can call from python
How can I find the full path to a font from its display name on a Mac?
Unfortunately the only API that isn't deprecated is located in the ApplicationServices framework, which doesn't have a bridge support file, and thus isn't available in the bridge. If you're wanting to use ctypes, you can use ATSFontGetFileReference after looking up the ATSFontRef. Cocoa doesn't have any native support, at least as of 10.5, for getting the location of a font.
I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF. On the Mac I am spawning sips. Is there something similarly simple I can do on Windows?
Get a preview JPEG of a PDF on Windows?
ImageMagick delegates the PDF->bitmap conversion to GhostScript anyway, so here's a command you can use (it's based on the actual command listed by the ps:alpha delegate in ImageMagick, just adjusted to use JPEG as output): gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \ -dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \ -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r72x72 \ -sOutputFile=$OUTPUT -f$INPUT where $OUTPUT and $INPUT are the output and input filenames. Adjust the 72x72 to whatever resolution you need. (Obviously, strip out the backslashes if you're writing out the whole command as one line.) This is good for two reasons: You don't need to have ImageMagick installed anymore. Not that I have anything against ImageMagick (I love it to bits), but I believe in simple solutions. ImageMagick does a two-step conversion. First PDF->PPM, then PPM->JPEG. This way, the conversion is one-step. Other things to consider: with the files I've tested, PNG compresses better than JPEG. If you want to use PNG, change the -sDEVICE=jpeg to -sDEVICE=png16m.
I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity. I realize I could do this with hooks in most VCSes, but that requires that the tests run on the same machine as the version control server, which isn't as elegant as I would like. Does anyone have any suggestions for a small, user-friendly, open-source continuous integration system suitable for a Python codebase?
Continuous Integration System for a Python Codebase
One possibility is Hudson. It's written in Java, but there's integration with Python projects: Hudson embraces Python I've never tried it myself, however. (Update, Sept. 2011: After a trademark dispute Hudson has been renamed to Jenkins.)
There are several ways to iterate over a result set. What are the tradeoff of each?
cx_Oracle: How do I iterate over a result set?
The canonical way is to use the built-in cursor iterator. curs.execute('select * from people') for row in curs: print row You can use fetchall() to get all rows at once. for row in curs.fetchall(): print row It can be convenient to use this to create a Python list containing the values returned: curs.execute('select first_name from people') names = [row[0] for row in curs.fetchall()] This can be useful for smaller result sets, but can have bad side effects if the result set is large. You have to wait for the entire result set to be returned to your client process. You may eat up a lot of memory in your client to hold the built-up list. It may take a while for Python to construct and deconstruct the list which you are going to immediately discard anyways. If you know there's a single row being returned in the result set you can call fetchone() to get the single row. curs.execute('select max(x) from t') maxValue = curs.fetchone()[0] Finally, you can loop over the result set fetching one row at a time. In general, there's no particular advantage in doing this over using the iterator. row = curs.fetchone() while row: print row row = curs.fetchone()
I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like, foo in iter_attr(array of python objects, attribute name) I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers
Using 'in' to match an attribute of Python objects in an array
Using a list comprehension would build a temporary list, which could eat all your memory if the sequence being searched is large. Even if the sequence is not large, building the list means iterating over the whole of the sequence before in could start its search. The temporary list can be avoiding by using a generator expression: foo = 12 foo in (obj.id for obj in bar) Now, as long as obj.id == 12 near the start of bar, the search will be fast, even if bar is infinitely long. As @Matt suggested, it's a good idea to use hasattr if any of the objects in bar can be missing an id attribute: foo = 12 foo in (obj.id for obj in bar if hasattr(obj, 'id'))
Django view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach. For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc... One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea?
Class views in Django
I've created and used my own generic view classes, defining __call__ so an instance of the class is callable. I really like it; while Django's generic views allow some customization through keyword arguments, OO generic views (if their behavior is split into a number of separate methods) can have much more fine-grained customization via subclassing, which lets me repeat myself a lot less. (I get tired of rewriting the same create/update view logic anytime I need to tweak something Django's generic views don't quite allow). I've posted some code at djangosnippets.org. The only real downside I see is the proliferation of internal method calls, which may impact performance somewhat. I don't think this is much of a concern; it's rare that Python code execution would be your performance bottleneck in a web app. UPDATE: Django's own generic views are now class-based. UPDATE: FWIW, I've changed my opinion on class-based views since this answer was written. After having used them extensively on a couple of projects, I feel they tend to lead to code that is satisfyingly DRY to write, but very hard to read and maintain later, because functionality is spread across so many different places, and subclasses are so dependent on every implementation detail of the superclasses and mixins. I now feel that TemplateResponse and view decorators is a better answer for decomposing view code.
I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host. I found bpgsql really good because it does not require an install, it's a single file that I can look at, read and then call the functions of. Does anybody know of something like this for MySQL?
Python and MySQL
MySQLdb is what I have used before. If you host is using Python version 2.5 or higher, support for sqlite3 databases is built in (sqlite allows you to have a relational database that is simply a file in your filesystem). But buyer beware, sqlite is not suited for production, so it may depend what you are trying to do with it. Another option may be to call your host and complain, or change hosts. Honestly these days, any self respecting web host that supports python and mysql ought to have MySQLdb pre installed.
I haven't been able to find an understandable explanation of how to actually use Python's itertools.groupby() function. What I'm trying to do is this: Take a list - in this case, the children of an objectified lxml element Divide it into groups based on some criteria Then later iterate over each of these groups separately. I've reviewed the documentation, and the examples, but I've had trouble trying to apply them beyond a simple list of numbers. So, how do I use of itertools.groupby()? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.
How do I use Python's itertools.groupby()?
As Sebastjan said, you first have to sort your data. This is important. The part I didn't get is that in the example construction groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) k is the current grouping key, and g is an iterator that you can use to iterate over the group defined by that grouping key. In other words, the groupby iterator itself returns iterators. Here's an example of that, using clearer variable names: from itertools import groupby things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")] for key, group in groupby(things, lambda x: x[0]): for thing in group: print "A %s is a %s." % (thing[1], key) print " " This will give you the output: A bear is a animal. A duck is a animal. A cactus is a plant. A speed boat is a vehicle. A school bus is a vehicle. In this example, things is a list of tuples where the first item in each tuple is the group the second item belongs to. The groupby() function takes two arguments: (1) the data to group and (2) the function to group it with. Here, lambda x: x[0] tells groupby() to use the first item in each tuple as the grouping key. In the above for statement, groupby returns three (key, group iterator) pairs - once for each unique key. You can use the returned iterator to iterate over each individual item in that group. Here's a slightly different example with the same data, using a list comprehension: for key, group in groupby(things, lambda x: x[0]): listOfThings = " and ".join([thing[1] for thing in group]) print key + "s: " + listOfThings + "." This will give you the output: animals: bear and duck. plants: cactus. vehicles: speed boat and school bus.
I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in Python, I think this is called Monkey Patching (or in some cases Duck Punching). I understand that it's not always a good decision to do so. But, how might one do this? UPDATE 8/04/2008 00:21:01 EST: That looks like a good answer John Downey, I tried it but it appears that it ends up being not a true method. Your example defines the new patch function with an argument of self, but if you write actual code that way, the now patched class method asks for an argument named self (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call class.patch(obj) instead of just class.patch() if you want the same functionality as a true method. It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function (and as such is callable). Is there any way to attach an actual method to a class? Oh, and Ryan, that isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.
Adding a Method to an Existing Object Instance
In Python, there is a difference between functions and bound methods. >>> def foo(): ... print "foo" ... >>> class A: ... def bar( self ): ... print "bar" ... >>> a = A() >>> foo <function foo at 0x00A98D70> >>> a.bar <bound method A.bar of <__main__.A instance at 0x00A9BC88>> >>> Bound methods have been "bound" (how descriptive) to an instance, and that instance will be passed as the first argument whenever the method is called. Callables that are attributes of a class (as opposed to an instance) are still unbound, though, so you can modify the class definition whenever you want: >>> def fooFighters( self ): ... print "fooFighters" ... >>> A.fooFighters = fooFighters >>> a2 = A() >>> a2.fooFighters <bound method A.fooFighters of <__main__.A instance at 0x00A9BEB8>> >>> a2.fooFighters() fooFighters Previously defined instances are updated as well (as long as they haven't overridden the attribute themselves): >>> a.fooFighters() fooFighters The problem comes when you want to attach a method to a single instance: >>> def barFighters( self ): ... print "barFighters" ... >>> a.barFighters = barFighters >>> a.barFighters() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: barFighters() takes exactly 1 argument (0 given) The function is not automatically bound when it's attached directly to an instance: >>> a.barFighters <function barFighters at 0x00A98EF0> To bind it, we can use the MethodType function in the types module: >>> import types >>> a.barFighters = types.MethodType( barFighters, a ) >>> a.barFighters <bound method ?.barFighters of <__main__.A instance at 0x00A9BC88>> >>> a.barFighters() barFighters This time other instances of the class have not been affected: >>> a2.barFighters() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: A instance has no attribute 'barFighters' More information can be found by reading about descriptors and metaclass programming.
How do you express an integer as a binary number with Python literals? I was easily able to find the answer for hex: >>> 0x12AF 4783 >>> 0x100 256 and octal: >>> 01267 695 >>> 0100 64 How do you use literals to express binary in Python? Summary of Answers Python 2.5 and earlier: can express binary using int('01010101111',2) but not with a literal. Python 2.5 and earlier: there is no way to express binary literals. Python 2.6 beta: You can do like so: 0b1100111 or 0B1100111. Python 2.6 beta: will also allow 0o27 or 0O27 (second character is the letter O) to represent an octal. Python 3.0 beta: Same as 2.6, but will no longer allow the older 027 syntax for octals.
How do you express binary literals in Python?
For reference—future Python possibilities: Starting with Python 2.6 you can express binary literals using the prefix 0b or 0B: >>> 0b101111 47 You can also use the new bin function to get the binary representation of a number: >>> bin(173) '0b10101101' Development version of the documentation: What's New in Python 2.6
I was just looking through some information about Google's protocol buffers data interchange format. Has anyone played around with the code or even created a project around it? I'm currently using XML in a Python project for structured content created by hand in a text editor, and I was wondering what the general opinion was on Protocol Buffers as a user-facing input format. The speed and brevity benefits definitely seem to be there, but there are so many factors when it comes to actually generating and processing the data.
Any experiences with Protocol Buffers?
Protocol buffers are intended to optimize communications between machines. They are really not intended for human interaction. Also, the format is binary, so it could not replace XML in that use case. I would also recommend JSON as being the most compact text-based format.
I've got a menu in Python. That part was easy. I'm using raw_input() to get the selection from the user. The problem is that raw_input (and input) require the user to press Enter after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far: import sys print """Menu 1) Say Foo 2) Say Bar""" answer = raw_input("Make a selection> ") if "1" in answer: print "foo" elif "2" in answer: print "bar" It would be great to have something like print menu while lastKey = "": lastKey = check_for_recent_keystrokes() if "1" in lastKey: #do stuff...
How do I make a menu that does not require the user to press [enter] to make a selection?
On Linux: set raw mode select and read the keystroke restore normal settings import sys import select import termios import tty def getkey(): old_settings = termios.tcgetattr(sys.stdin) tty.setraw(sys.stdin.fileno()) select.select([sys.stdin], [], [], 0) answer = sys.stdin.read(1) termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings) return answer print """Menu 1) Say Foo 2) Say Bar""" answer=getkey() if "1" in answer: print "foo" elif "2" in answer: print "bar"
What do I need to look at to see if I'm on Windows, Unix, etc?
How to check what OS am I running on in Python?
>>> import os >>> print os.name posix >>> import platform >>> platform.system() 'Linux' >>> platform.release() '2.6.22-15-generic' See: platform — Access to underlying platform’s identifying data
In many places, (1,2,3) and [1,2,3] can be used interchangeably. When should I use one or the other, and why?
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
From the Python FAQ: Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers. Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one. Generally by convention you wouldn't choose a list or a tuple just based on its (im)mutability. You would choose a tuple for small collections of completely different pieces of data in which a full-blown class would be too heavyweight, and a list for collections of any reasonable size where you have a homogeneous set of data.
I have created a PHP-script to update a webserver that is live inside a local directory. I'm migrating the script into Python. It works fine for the most part, but after a PUT command the size of the file appears to change. Thus, the size of the file is different from that of the file on the server. Once I download again the file from the FTP server, the only difference is the CR/LF mark. This annoys me because the same script is comparing the size of the files to update. Also, in case it means anything, the script works perfectly in PHP vía ftp_put. from ftplib import FTP ftpserver = "myserver" ftpuser = "myuser" ftppass = "mypwd" locfile = "g:/test/style.css" ftpfile = "/temp/style.css" try: ftp = FTP(ftpserver, ftpuser, ftppass) except: exit ("Cannot connect") f = open (locfile, "r") try: ftp.delete (ftpfile) except: pass # ftp.sendcmd ("TYPE I") # ftp.storlines("STOR %s" % ftpfile, f) ftp.storbinary("STOR %s" % ftpfile, f) f.close() ftp.dir (ftpfile) ftp.quit() Any suggestions?
File size differences after copying a file to a server vía FTP
Do you need to open the locfile in binary using rb? f = open (locfile, "rb")
Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?
How can I create a directly-executable cross-platform GUI app using Python?
First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables. Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac) Of course, there are many, but the most popular that I've seen in wild are: Tkinter - based on Tk GUI toolkit (de-facto standard GUI library for python, free for commercial projects) WxPython - based on WxWidgets (very popular, free for commercial projects) PyQt - based on Qt (also very popular and more stable than WxWidgets but costly license for commercial projects) Complete list is at http://wiki.python.org/moin/GuiProgramming Single executable (Windows) py2exe - Probably the most popular out there (PyInstaller is also gaining in popularity) Single executable (Linux) Freeze - works the same way like py2exe but targets Linux platform Single executable (Mac) py2app - again, works like py2exe but targets Mac OS
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module foo, and I have a string whose contents are "bar". What is the best way to go about calling foo.bar()? I need to get the return value of the function, which is why I don't just use eval. I figured out how to do it by using eval to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
Calling a function of a module from a string with the function's name in Python
Assuming module foo with method bar: import foo methodToCall = getattr(foo, 'bar') result = methodToCall() As far as that goes, lines 2 and 3 can be compressed to: result = getattr(foo, 'bar')() if that makes more sense for your use case. You can use getattr in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.
I have a Prolite LED sign that I like to set up to show scrolling search queries from a apache logs and other fun statistics. The problem is, my G5 does not have a serial port, so I have to use a usb to serial dongle. It shows up as /dev/cu.usbserial and /dev/tty.usbserial . When i do this everything seems to be hunky-dory: stty -f /dev/cu.usbserial speed 9600 baud; lflags: -icanon -isig -iexten -echo iflags: -icrnl -ixon -ixany -imaxbel -brkint oflags: -opost -onlcr -oxtabs cflags: cs8 -parenb Everything also works when I use the serial port tool to talk to it. If I run this piece of code while the above mentioned serial port tool, everthing also works. But as soon as I disconnect the tool the connection gets lost. #!/usr/bin/python import serial ser = serial.Serial('/dev/cu.usbserial', 9600, timeout=10) ser.write("<ID01><PA> \r\n") read_chars = ser.read(20) print read_chars ser.close() So the question is, what magicks do I need to perform to start talking to the serial port without the serial port tool? Is that a permissions problem? Also, what's the difference between /dev/cu.usbserial and /dev/tty.usbserial? Nope, no serial numbers. The thing is, the problem persists even with sudo-running the python script, and the only thing that makes it go through if I open the connection in the gui tool that I mentioned.
Programmatically talking to a Serial Port in OS X or Linux
/dev/cu.xxxxx is the "callout" device, it's what you use when you establish a connection to the serial device and start talking to it. /dev/tty.xxxxx is the "dialin" device, used for monitoring a port for incoming calls for e.g. a fax listener.
I tried to follow a couple of googled up tutorials on setting up mod_python, but failed every time. Do you have a good, step-by step, rock-solid howto? My dev box is OS X, production - Centos.
How do you set up Python scripts to work in Apache 2.0?
There are two main ways of running Python on Apache. The simplest would be to use CGI and write normal Python scripts while the second is using a web framework like Django or Pylons. Using CGI is straightforward. Make sure your Apache config file has a cgi-bin set up. If not, follow their documentation (http://httpd.apache.org/docs/2.0/howto/cgi.html). At that point all you need to do is place your Python scripts in the cgi-bin directory and the standard output will become the HTTP response. Refer to Python's documentation for further info (https://docs.python.org/library/cgi.html). If you want to use a web framework you'll need to setup mod_python or FastCGI. These steps are dependent on which framework you want to use. Django provides clear instructions on how to setup mod_python and Django with Apache (http://www.djangoproject.com/documentation/modpython/)
I learned Swing back in the day but now I've moved to Python and want to make some apps with GUIs. I haven't had the time to learn a new GUI API so I've been using Jython, but I would prefer to use CPython. It would be great if I can have one simple markup that allows me to switch GUI libraries. It would be even better if I can use the same markup language across languages so I can quickly make GUIs for any language I'm using. Does anyone know of such a markup/library? I've seen markups like Glade and wxWidget's markup (I forget the name). They're partly what I'm looking for (making a GUI without coding it in a language) but they're intertwined with a specific library. And neither are really nice looking or friendly to human editting.
Cross Platform, Language Agnostic GUI Markup Language?
erm.. HTML? (trying to be funny here... while we wait for real answers..)
I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?
Convert Bytes to Floating Point Numbers in Python
>>> import struct >>> struct.pack('f', 3.141592654) b'\xdb\x0fI@' >>> struct.unpack('f', b'\xdb\x0fI@') (3.1415927410125732,) >>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0) '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'
When I try to print a Unicode string in a Windows console, I get a UnicodeEncodeError: 'charmap' codec can't encode character .... error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a ? instead of failing in this situation? Edit: I'm using Python 2.5. Note: @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!! @JFSebastian answer is more relevant as of today (6 Jan 2016).
Python, Unicode, and the Windows console
Note: This answer is sort of outdated (from 2008). Please use the solution below with care!! Here is a page that details the problem and a solution (search the page for the text Wrapping sys.stdout into an instance): PrintFails - Python Wiki Here's a code excerpt from that page: $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' UTF-8 <type 'unicode'> 2 Б Б $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' | cat None <type 'unicode'> 2 Б Б There's some more information on that page, well worth a read.
I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server? import urllib import re url = "http://www.someurl.com" # Download the page locally f = urllib.urlopen(url) html = f.read() f.close() f = open ("temp.htm", "w") f.write (html) f.close() # List only the .TXT / .ZIP files fnames = re.findall('^.*<a href="(\w+(?:\.txt|.zip)?)".*$', html, re.MULTILINE) for fname in fnames: print fname, "..." f = urllib.urlopen(url + "/" + fname) #### Here I want to check the filesize to download or not #### file = f.read() f.close() f = open (fname, "w") f.write (file) f.close() @Jon: thank for your quick answer. It works, but the filesize on the web server is slightly less than the filesize of the downloaded file. Examples: Local Size Server Size 2.223.533 2.115.516 664.603 662.121 It has anything to do with the CR/LF conversion?
Get size of a file before downloading in Python
I have reproduced what you are seeing: import urllib, oslink = "http://python.org"print "opening url:", linksite = urllib.urlopen(link)meta = site.info()print "Content-Length:", meta.getheaders("Content-Length")[0]f = open("out.txt", "r")print "File on disk:",len(f.read())f.close()f = open("out.txt", "w")f.write(site.read())site.close()f.close()f = open("out.txt", "r")print "File on disk after download:",len(f.read())f.close()print "os.stat().st_size returns:", os.stat("out.txt").st_size Outputs this: opening url: http://python.orgContent-Length: 16535File on disk: 16535File on disk after download: 16535os.stat().st_size returns: 16861 What am I doing wrong here? Is os.stat().st_size not returning the correct size? Edit: OK, I figured out what the problem was: import urllib, oslink = "http://python.org"print "opening url:", linksite = urllib.urlopen(link)meta = site.info()print "Content-Length:", meta.getheaders("Content-Length")[0]f = open("out.txt", "rb")print "File on disk:",len(f.read())f.close()f = open("out.txt", "wb")f.write(site.read())site.close()f.close()f = open("out.txt", "rb")print "File on disk after download:",len(f.read())f.close()print "os.stat().st_size returns:", os.stat("out.txt").st_size this outputs: $ python test.pyopening url: http://python.orgContent-Length: 16535File on disk: 16535File on disk after download: 16535os.stat().st_size returns: 16535 Make sure you are opening both files for binary read/write. // open for binary writeopen(filename, "wb")// open for binary readopen(filename, "rb")
What is the library? Is there a full implementation? How is the library used? Where is its website?
How to use Xpath in Python?
libxml2 has a number of advantages: Compliance to the spec Active development and a community participation Speed. This is really a python wrapper around a C implementation. Ubiquity. The libxml2 library is pervasive and thus well tested. Downsides include: Compliance to the spec. It's strict. Things like default namespace handling are easier in other libraries. Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain. Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic. If you are doing simple path selection, stick with ElementTree ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2. Sample of libxml2 XPath Use import libxml2 doc = libxml2.parseFile("tst.xml") ctxt = doc.xpathNewContext() res = ctxt.xpathEval("//*") if len(res) != 2: print "xpath query: wrong node set size" sys.exit(1) if res[0].name != "doc" or res[1].name != "foo": print "xpath query: wrong node set value" sys.exit(1) doc.freeDoc() ctxt.xpathFreeContext() Sample of ElementTree XPath Use from elementtree.ElementTree import ElementTree mydoc = ElementTree(file='tst.xml') for e in mydoc.findall('/foo/bar'): print e.get('title').text
What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?
Accessing mp3 Meta-Data with Python
I used eyeD3 the other day with a lot of success. I found that it could add artwork to the ID3 tag which the other modules I looked at couldn't. You'll have to download the tar and execute python setup.py install from the source folder. Relevant examples from the website are below. Reading the contents of an mp3 file containing either v1 or v2 tag info: import eyeD3 tag = eyeD3.Tag() tag.link("/some/file.mp3") print tag.getArtist() print tag.getAlbum() print tag.getTitle() Read an mp3 file (track length, bitrate, etc.) and access it's tag: if eyeD3.isMp3File(f): audioFile = eyeD3.Mp3AudioFile(f) tag = audioFile.getTag() Specific tag versions can be selected: tag.link("/some/file.mp3", eyeD3.ID3_V2) tag.link("/some/file.mp3", eyeD3.ID3_V1) tag.link("/some/file.mp3", eyeD3.ID3_ANY_VERSION) # The default. Or you can iterate over the raw frames: tag = eyeD3.Tag() tag.link("/some/file.mp3") for frame in tag.frames: print frame Once a tag is linked to a file it can be modified and saved: tag.setArtist(u"Cro-Mags") tag.setAlbum(u"Age of Quarrel") tag.update() If the tag linked in was v2 and you'd like to save it as v1: tag.update(eyeD3.ID3_V1_1) Read in a tag and remove it from the file: tag.link("/some/file.mp3") tag.remove() tag.update() Add a new tag: tag = eyeD3.Tag() tag.link('/some/file.mp3') # no tag in this file, link returned False tag.header.setVersion(eyeD3.ID3_V2_3) tag.setArtist('Fugazi') tag.update()
This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions. I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When I developed this code I did it using TDD, but I've found my tests to be brittle as hell. Because each test essentially wanted to verify that for a given bit of input code (which happens to be a C++ header) I'd get a given bit of outputted code I wrote a small engine that reads test definitions from XML input files and generates test cases from these expectations. The problem is I dread going in to modify the code at all. That and the fact that the unit tests themselves are a: complex, and b: brittle. So I'm trying to think of alternative approaches to this problem, and it strikes me I'm perhaps tackling it the wrong way. Maybe I need to focus more on the outcome, IE: does the code I generate actually run and do what I want it to, rather than, does the code look the way I want it to. Has anyone got any experiences of something similar to this they would care to share?
How should I unit test a code-generator?
I started writing up a summary of my experience with my own code generator, then went back and re-read your question and found you had already touched upon the same issues yourself, focus on the execution results instead of the code layout/look. Problem is, this is hard to test, the generated code might not be suited to actually run in the environment of the unit test system, and how do you encode the expected results? I've found that you need to break down the code generator into smaller pieces and unit test those. Unit testing a full code generator is more like integration testing than unit testing if you ask me.
Is it possible to write a doctest unit test that will check that an exception is raised? For example, if I have a function foo(x) that is supposed to raise an exception if x<0, how would I write the doctest for that?
Can you check that an exception is thrown with doctest in Python?
Yes. You can do it. The doctest module documentation and Wikipedia has an example of it. >>> x Traceback (most recent call last): ... NameError: name 'x' is not defined
I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.
Can you explain closures (as they relate to Python)?
Closure on closures Objects are data with methods attached, closures are functions with data attached. def make_counter(): i = 0 def counter(): # counter() is a closure nonlocal i i += 1 return i return counter c1 = make_counter() c2 = make_counter() print (c1(), c1(), c2(), c2()) # -> 1 2 1 2
I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use import os and then use a command line speech program to say "Process complete." I much rather it be a simple "bell." I know that there's a function that can be used in Cocoa apps, NSBeep, but I don't think that has much anything to do with this. I've also tried print(\a) but that didn't work. I'm using a Mac, if you couldn't tell by my Cocoa comment, so that may help. Thanks!
Python Sound ("Bell")
Have you tried : import sys sys.stdout.write('\a') sys.stdout.flush() That works for me here on Mac OS 10.5 Actually, I think your original attempt works also with a little modification: print('\a') (You just need the single quotes around the character sequence).
I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi) The script works fine, that is until you try and use it on files that have Unicode show-names (something I never really thought about, since all the files I have are English, so mostly pretty-much all fall within [a-zA-Z0-9'\-]) How can I allow the regular expressions to match accented characters and the likes? Currently the regex's config section looks like.. config['valid_filename_chars'] = """0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@£$%^&*()_+=-[]{}"'.,<>`~? """ config['valid_filename_chars_regex'] = re.escape(config['valid_filename_chars']) config['name_parse'] = [ # foo_[s01]_[e01] re.compile('''^([%s]+?)[ \._\-]\[[Ss]([0-9]+?)\]_\[[Ee]([0-9]+?)\]?[^\\/]*$'''% (config['valid_filename_chars_regex'])), # foo.1x09* re.compile('''^([%s]+?)[ \._\-]\[?([0-9]+)x([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])), # foo.s01.e01, foo.s01_e01 re.compile('''^([%s]+?)[ \._\-][Ss]([0-9]+)[\.\- ]?[Ee]([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])), # foo.103* re.compile('''^([%s]+)[ \._\-]([0-9]{1})([0-9]{2})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])), # foo.0103* re.compile('''^([%s]+)[ \._\-]([0-9]{2})([0-9]{2,3})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])), ]
Regex and unicode
Use a subrange of [\u0000-\uFFFF] for what you want. You can also use the re.UNICODE compile flag. The docs say that if UNICODE is set, \w will match the characters [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties database. See also http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-05/2560.html.
I need to validate an XML string (and not a file) against a DTD description file. How can that be done in python?
How do I validate xml against a DTD file in Python
Another good option is lxml's validation which I find quite pleasant to use. A simple example taken from the lxml site: from StringIO import StringIO from lxml import etree dtd = etree.DTD(StringIO("""<!ELEMENT foo EMPTY>""")) root = etree.XML("<foo/>") print(dtd.validate(root)) # True root = etree.XML("<foo>bar</foo>") print(dtd.validate(root)) # False print(dtd.error_log.filter_from_errors()) # <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content
I have been mulling over writing a peak fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually. IIRC, one of Python's original remits was as a prototyping language, however Python is pretty liberal in allowing functions, functors, objects to be passed to functions and methods, whereas I suspect the same is not true of say C or Fortran. What should I know about designing functions/classes which I envisage will have to interface into the compiled language? And how much of these potential problems are dealt with by libraries such as cTypes, bgen, SWIG, Boost.Python, Cython or Python SIP? For this particular use case, (a fitting library) I imagine allowing users to define mathematical functions (Guassian, Lorentzian etc.) as Python functions which can then to be passed an interpreted by the compiled code fitting library. Passing and returning arrays is also essential.
Prototyping with Python code before compiling
Finally a question that I can really put a value answer to :). I have investigated f2py, boost.python, swig, cython and pyrex for my work (PhD in optical measurement techniques). I used swig extensively, boost.python some and pyrex and cython a lot. I also used ctypes. This is my breakdown: Disclaimer: This is my personal experience. I am not involved with any of these projects. swig: does not play well with c++. It should, but name mangling problems in the linking step was a major headache for me on linux & Mac OS X. If you have C code and want it interfaced to python, it is a good solution. I wrapped the GTS for my needs and needed to write basically a C shared library which I could connect to. I would not recommend it. Ctypes: I wrote a libdc1394 (IEEE Camera library) wrapper using ctypes and it was a very straigtforward experience. You can find the code on https://launchpad.net/pydc1394. It is a lot of work to convert headers to python code, but then everything works reliably. This is a good way if you want to interface an external library. Ctypes is also in the stdlib of python, so everyone can use your code right away. This is also a good way to play around with a new lib in python quickly. I can recommend it to interface to external libs. Boost.Python: Very enjoyable. If you already have C++ code of your own that you want to use in python, go for this. It is very easy to translate c++ class structures into python class structures this way. I recommend it if you have c++ code that you need in python. Pyrex/Cython: Use Cython, not Pyrex. Period. Cython is more advanced and more enjoyable to use. Nowadays, I do everything with cython that i used to do with SWIG or Ctypes. It is also the best way if you have python code that runs too slow. The process is absolutely fantastic: you convert your python modules into cython modules, build them and keep profiling and optimizing like it still was python (no change of tools needed). You can then apply as much (or as little) C code mixed with your python code. This is by far faster then having to rewrite whole parts of your application in C; you only rewrite the inner loop. Timings: ctypes has the highest call overhead (~700ns), followed by boost.python (322ns), then directly by swig (290ns). Cython has the lowest call overhead (124ns) and the best feedback where it spends time on (cProfile support!). The numbers are from my box calling a trivial function that returns an integer from an interactive shell; module import overhead is therefore not timed, only function call overhead is. It is therefore easiest and most productive to get python code fast by profiling and using cython. Summary: For your problem, use Cython ;). I hope this rundown will be useful for some people. I'll gladly answer any remaining question. Edit: I forget to mention: for numerical purposes (that is, connection to NumPy) use Cython; they have support for it (because they basically develop cython for this purpose). So this should be another +1 for your decision.
What's the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an XSS or SQL injection attack?
Sanitising user input using Python
Here is a snippet that will remove all tags not on the white list, and all tag attributes not on the attribues whitelist (so you can't use onclick). It is a modified version of http://www.djangosnippets.org/snippets/205/, with the regex on the attribute values to prevent people from using href="javascript:...", and other cases described at http://ha.ckers.org/xss.html. (e.g. <a href="ja&#x09;vascript:alert('hi')"> or <a href="ja vascript:alert('hi')">, etc.) As you can see, it uses the (awesome) BeautifulSoup library. import re from urlparse import urljoin from BeautifulSoup import BeautifulSoup, Comment def sanitizeHtml(value, base_url=None): rjs = r'[\s]*(&#x.{1,7})?'.join(list('javascript:')) rvb = r'[\s]*(&#x.{1,7})?'.join(list('vbscript:')) re_scripts = re.compile('(%s)|(%s)' % (rjs, rvb), re.IGNORECASE) validTags = 'p i strong b u a h1 h2 h3 pre br img'.split() validAttrs = 'href src width height'.split() urlAttrs = 'href src'.split() # Attributes which should have a URL soup = BeautifulSoup(value) for comment in soup.findAll(text=lambda text: isinstance(text, Comment)): # Get rid of comments comment.extract() for tag in soup.findAll(True): if tag.name not in validTags: tag.hidden = True attrs = tag.attrs tag.attrs = [] for attr, val in attrs: if attr in validAttrs: val = re_scripts.sub('', val) # Remove scripts (vbs & js) if attr in urlAttrs: val = urljoin(base_url, val) # Calculate the absolute url tag.attrs.append((attr, val)) return soup.renderContents().decode('utf8') As the other posters have said, pretty much all Python db libraries take care of SQL injection, so this should pretty much cover you.
I'm creating an ZIP file with ZipFile in Python 2.5, it works ok so far: import zipfile, os locfile = "test.txt" loczip = os.path.splitext (locfile)[0] + ".zip" zip = zipfile.ZipFile (loczip, "w") zip.write (locfile) zip.close() but I couldn't find how to encrypt the files in the ZIP file. I could use system and call PKZIP -s, but I suppose there must be a more "Pythonic" way. I'm looking for an open source solution.
Create an encrypted ZIP file in Python
I created a simple library to create a password encrypted zip file in python. - here import pyminizip compression_level = 5 # 1-9 pyminizip.compress("src.txt", "dst.zip", "password", compression_level) The library requires zlib. I have checked that the file can be extracted in WINDOWS/MAC.
My current setup.py script works okay, but it installs tvnamer.py (the tool) as "tvnamer.py" into site-packages or somewhere similar.. Can I make setup.py install tvnamer.py as tvnamer, and/or is there a better way of installing command-line applications?
What's the best way to distribute python command-line tools?
Try the entry_points.console_scripts parameter in the setup() call. As described in the setuptools docs, this should do what I think you want. To reproduce here: from setuptools import setup setup( # other arguments here... entry_points = { 'console_scripts': [ 'foo = package.module:func', 'bar = othermodule:somefunc', ], } )
How would one create an iterative function (or iterator object) in python?
Build a Basic Python Iterator
Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: __iter__() and next(). The __iter__ returns the iterator object and is implicitly called at the start of loops. The next() method returns the next value and is implicitly called at each loop increment. next() raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating. Here's a simple example of a counter: class Counter: def __init__(self, low, high): self.current = low self.high = high def __iter__(self): return self def next(self): # Python 3: def __next__(self) if self.current > self.high: raise StopIteration else: self.current += 1 return self.current - 1 for c in Counter(3, 8): print c This will print: 3 4 5 6 7 8 This is easier to write using a generator, as covered in a previous answer: def counter(low, high): current = low while current <= high: yield current current += 1 for c in counter(3, 8): print c The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter. David Mertz's article, Iterators and Simple Generators, is a pretty good introduction.
I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item. For example: original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4]) Is there a builtin function that does that?
A Transpose/Unzip Function in Python (inverse of zip)
zip is its own inverse! Provided you use the special * operator. >>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)]) [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] The way this works is by calling zip with the arguments: zip(('a', 1), ('b', 2), ('c', 3), ('d', 4)) … except the arguments are passed to zip directly (after being converted to a tuple), so there's no need to worry about the number of arguments getting too big.
What's the easiest, tersest, and most flexible method or library for parsing Python command line arguments?
What's the best way to grab/parse command line arguments passed to a Python script?
This answer suggests optparse which is appropriate for older Python versions. For Python 2.7 and above, argparse replaces optparse. See this answer for more information. As other people pointed out, you are better off going with optparse over getopt. getopt is pretty much a one-to-one mapping of the standard getopt(3) C library functions, and not very easy to use. optparse, while being a bit more verbose, is much better structured and simpler to extend later on. Here's a typical line to add an option to your parser: parser.add_option('-q', '--query', action="store", dest="query", help="query string", default="spam") It pretty much speaks for itself; at processing time, it will accept -q or --query as options, store the argument in an attribute called query and has a default value if you don't specify it. It is also self-documenting in that you declare the help argument (which will be used when run with -h/--help) right there with the option. Usually you parse your arguments with: options, args = parser.parse_args() This will, by default, parse the standard arguments passed to the script (sys.argv[1:]) options.query will then be set to the value you passed to the script. You create a parser simply by doing parser = optparse.OptionParser() These are all the basics you need. Here's a complete Python script that shows this: import optparse parser = optparse.OptionParser() parser.add_option('-q', '--query', action="store", dest="query", help="query string", default="spam") options, args = parser.parse_args() print 'Query string:', options.query 5 lines of python that show you the basics. Save it in sample.py, and run it once with python sample.py and once with python sample.py --query myquery Beyond that, you will find that optparse is very easy to extend. In one of my projects, I created a Command class which allows you to nest subcommands in a command tree easily. It uses optparse heavily to chain commands together. It's not something I can easily explain in a few lines, but feel free to browse around in my repository for the main class, as well as a class that uses it and the option parser
If I call os.stat() on a broken symlink, python throws an OSError exception. This makes it useful for finding them. However, there are a few other reasons that os.stat() might throw a similar exception. Is there a more precise way of detecting broken symlinks with Python under Linux?
Find broken symlinks with Python
A common Python saying is that it's easier to ask forgiveness than permission. While I'm not a fan of this statement in real life, it does apply in a lot of cases. Usually you want to avoid code that chains two system calls on the same file, because you never know what will happen to the file in between your two calls in your code. A typical mistake is to write something like: if os.path.exists(path): os.unlink(path) The second call (os.unlink) may fail if something else deleted it after your if test, raise an Exception, and stop the rest of your function from executing. (You might think this doesn't happen in real life, but we just fished another bug like that out of our codebase last week - and it was the kind of bug that left a few programmers scratching their head and claiming 'Heisenbug' for the last few months) So, in your particular case, I would probably do: try: os.stat(path) except OSError, e: if e.errno == errno.ENOENT: print 'path %s does not exist or is a broken symlink' % path else: raise e The annoyance here is that stat returns the same error code for a symlink that just isn't there and a broken symlink. So, I guess you have no choice than to break the atomicity, and do something like if not os.path.exists(os.readlink(path)): print 'path %s is a broken symlink' % path
How do I go about specifying and using an ENUM in a Django model?
Specifying a mySQL ENUM in a Django model
From the Django documentation: MAYBECHOICE = ( ('y', 'Yes'), ('n', 'No'), ('u', 'Unknown'), ) And you define a charfield in your model : married = models.CharField(max_length=1, choices=MAYBECHOICE) You can do the same with integer fields if you don't like to have letters in your db. In that case, rewrite your choices: MAYBECHOICE = ( (0, 'Yes'), (1, 'No'), (2, 'Unknown'), )
Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed. But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time. Why does Java choose this strategy and what is the benefit from this? Is this better than the Python approach?
Why Java and Python garbage collection methods are different?
There are drawbacks of using reference counting. One of the most mentioned is circular references: Suppose A references B, B references C and C references B. If A were to drop its reference to B, both B and C will still have a reference count of 1 and won't be deleted with traditional reference counting. CPython (reference counting is not part of python itself, but part of the C implementation thereof) catches circular references with a separate garbage collection routine that it runs periodically... Another drawback: Reference counting can make execution slower. Each time an object is referenced and dereferenced, the interpreter/VM must check to see if the count has gone down to 0 (and then deallocate if it did). Garbage Collection does not need to do this. Also, Garbage Collection can be done in a separate thread (though it can be a bit tricky). On machines with lots of RAM and for processes that use memory only slowly, you might not want to be doing GC at all! Reference counting would be a bit of a drawback there in terms of performance...
I stumbled over this passage in the Django tutorial: Django models have a default str() method that calls unicode() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8. Now, I'm confused because afaik Unicode is not any particular representation, so what is a "Unicode string" in Python? Does that mean UCS-2? Googling turned up this "Python Unicode Tutorial" which boldly states Unicode is a two-byte encoding which covers all of the world's common writing systems. which is plain wrong, or is it? I have been confused many times by character set and encoding issues, but here I'm quite sure that the documentation I'm reading is confused. Does anybody know what's going on in Python when it gives me a "Unicode string"?
Unicode vs UTF-8 confusion in Python / Django?
what is a "Unicode string" in Python? Does that mean UCS-2? Unicode strings in Python are stored internally either as UCS-2 (fixed-length 16-bit representation, almost the same as UTF-16) or UCS-4/UTF-32 (fixed-length 32-bit representation). It's a compile-time option; on Windows it's always UTF-16 whilst many Linux distributions set UTF-32 (‘wide mode’) for their versions of Python. You are generally not supposed to care: you will see Unicode code-points as single elements in your strings and you won't know whether they're stored as two or four bytes. If you're in a UTF-16 build and you need to handle characters outside the Basic Multilingual Plane you'll be Doing It Wrong, but that's still very rare, and users who really need the extra characters should be compiling wide builds. plain wrong, or is it? Yes, it's quite wrong. To be fair I think that tutorial is rather old; it probably pre-dates wide Unicode strings, if not Unicode 3.1 (the version that introduced characters outside the Basic Multilingual Plane). There is an additional source of confusion stemming from Windows's habit of using the term “Unicode” to mean, specifically, the UTF-16LE encoding that NT uses internally. People from Microsoftland may often copy this somewhat misleading habit.
I need to find out how to format numbers as strings. My code is here: return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm". Bottom line, what library / function do I need to do this for me?
Format numbers to strings in Python
Formatting in Python is done via the string formatting (%) operator: "%02d:%02d:%02d" % (hours, minutes, seconds) /Edit: There's also strftime.
I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes. The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows .bat file to download the actual MP3 however. I would prefer to have the entire utility written in Python though. I struggled though to find a way to actually down load the file in Python, thus why I resorted to wget. So, how do I download the file using Python?
How do I download a file over HTTP using Python?
One more, using urlretrieve: import urllib urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3") (for Python 3+ use 'import urllib.request' and urllib.request.urlretrieve) Yet another one, with a "progressbar" import urllib2 url = "http://download.thinkbroadband.com/10MB.zip" file_name = url.split('/')[-1] u = urllib2.urlopen(url) f = open(file_name, 'wb') meta = u.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading: %s Bytes: %s" % (file_name, file_size) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8)*(len(status)+1) print status, f.close()
How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the fork() system call, using Python? I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting.
What's the best way to duplicate fork() in windows?
Use the python multiprocessing module which will work everywhere. Here is a IBM developerWords article that shows how to convert from os.fork() to the multiprocessing module.
Basically I want to get the number of lines-of-code in the repository after each commit. The only (really crappy) ways I have found is to use git filter-branch to run "wc -l *", and a script that run git reset --hard on each commit, then ran wc -l To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on.. This is what I want the tool to output (as an example): me@something:~/$ gitsloc --branch master 10 48 153 450 1734 1542 I've played around with the ruby 'git' library, but the closest I found was using the .lines() method on a diff, which seems like it should give the added lines (but does not.. it returns 0 when you delete lines for example) require 'rubygems' require 'git' total = 0 g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api') last = nil g.log.each do |cur| diff = g.diff(last, cur) total = total + diff.lines puts total last = cur end
How can I graph the Lines of Code history for git repo?
You may get both added and removed lines with git log, like: git log --shortstat --reverse --pretty=oneline From this, you can write a similar script to the one you did using this info. In python: #!/usr/bin/python """ Display the per-commit size of the current git branch. """ import subprocess import re import sys def main(argv): git = subprocess.Popen(["git", "log", "--shortstat", "--reverse", "--pretty=oneline"], stdout=subprocess.PIPE) out, err = git.communicate() total_files, total_insertions, total_deletions = 0, 0, 0 for line in out.split('\n'): if not line: continue if line[0] != ' ': # This is a description line hash, desc = line.split(" ", 1) else: # This is a stat line data = re.findall( ' (\d+) files changed, (\d+) insertions\(\+\), (\d+) deletions\(-\)', line) files, insertions, deletions = ( int(x) for x in data[0] ) total_files += files total_insertions += insertions total_deletions += deletions print "%s: %d files, %d lines" % (hash, total_files, total_insertions - total_deletions) if __name__ == '__main__': sys.exit(main(sys.argv))
In Python you can use StringIO for a file-like buffer for character data. Memory-mapped file basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's ByteArrayOutputStream? The use-case I have is I want to create a ZIP file in memory, and ZipFile requires a file-like object.
Binary buffer in Python
You are probably looking for io.BytesIO class. It works exactly like StringIO except that it supports binary data: from io import BytesIO bio = BytesIO(b"some initial binary data: \x00\x01") StringIO will throw TypeError: from io import StringIO sio = StringIO(b"some initial binary data: \x00\x01")
If I have Python code class A(): pass class B(): pass class C(A, B): pass and I have class C, is there a way to iterate through it's super classed (A and B)? Something like pseudocode: >>> magicGetSuperClasses(C) (<type 'A'>, <type 'B'>) One solution seems to be inspect module and getclasstree function. def magicGetSuperClasses(cls): return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type] but is this a "Pythonian" way to achieve the goal?
Python super class reflection
C.__bases__ is an array of the super classes, so you could implement your hypothetical function like so: def magicGetSuperClasses(cls): return cls.__bases__ But I imagine it would be easier to just reference cls.__bases__ directly in most cases.
Is there any difference between: if foo is None: pass and if foo == None: pass The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?
Is there any difference between "foo is None" and "foo == None"?
is always returns True if it compares the same object instance Whereas == is ultimately determined by the __eq__() method i.e. >>> class foo(object): def __eq__(self, other): return True >>> f = foo() >>> f == None True >>> f is None False
I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names. Simple search and replace only gets me so far. In my case, I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug, so the first one's search-and-replace would also hit the second, wrongly. Does anyone have experience with Python refactoring tools ? Bonus points if they can fix class names in the XML documents too.
What refactoring tools do you use for Python?
In the meantime, I've tried it two tools that have some sort of integration with vim. The first is Rope, a python refactoring library that comes with a Vim (and emacs) plug-in. I tried it for a few renames, and that definitely worked as expected. It allowed me to preview the refactoring as a diff, which is nice. It is a bit text-driven, but that's alright for me, just takes longer to learn. The second is Bicycle Repair Man which I guess wins points on name. Also plugs into vim and emacs. Haven't played much with it yet, but I remember trying it a long time ago. Haven't played with both enough yet, or tried more types of refactoring, but I will do some more hacking with them.
Here is my sample code: from xml.dom.minidom import * def make_xml(): doc = Document() node = doc.createElement('foo') node.innerText = 'bar' doc.appendChild(node) return doc if __name__ == '__main__': make_xml().writexml(sys.stdout) when I run the above code I get this: <?xml version="1.0" ?> <foo/> I would like to get: <?xml version="1.0" ?> <foo>bar</foo> I just guessed that there was an innerText property, it gives no compiler error, but does not seem to work... how do I go about creating a text node?
How do I create an xml document in python
Setting an attribute on an object won't give a compile-time or a run-time error, it will just do nothing useful if the object doesn't access it (i.e. "node.noSuchAttr = 'bar'" would also not give an error). Unless you need a specific feature of minidom, I would look at ElementTree: import sys from xml.etree.cElementTree import Element, ElementTree def make_xml(): node = Element('foo') node.text = 'bar' doc = ElementTree(node) return doc if __name__ == '__main__': make_xml().write(sys.stdout)
I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in *nix anyway so I'm not worried about it being cross platform. my main goal is to create a .deb package for debian/ubuntu users, but I don't understand make/configure files. I've primarily been a web developer up until now. Thanks for your help! edit: Does anyone know of a project that uses distutils so I could see it in action and, you know, actually try building it? Here are a few useful links Ubuntu Python Packaging Guide This Guide is very helpful. I don't know how I missed it during my initial wave of gooling. It even walks you through packaging up an existing python application The Ubuntu MOTU Project This is the official package maintaining project at ubuntu. Anyone can join, and there are lots of tutorials and info about creating packages, of all types, which include the above 'python packaging guide'. "Python distutils to deb?" - Ars Technica Forum discussion According to this conversation, you can't just use distutils. It doesn't follow the debian packaging format (or something like that). I guess that's why you need dh_make as seen in the Ubuntu Packaging guide "A bdist_deb command for distutils This one has some interesting discussion (it's also how I found the ubuntu guide) about concatenating a zip-file and a shell script to create some kind of universal executable (anything with python and bash that is). weird. Let me know if anyone finds more info on this practice because I've never heard of it. Description of the deb format and how distutils fit in - python mailing list
Python distutils - does anyone know how to use it?
See the distutils simple example. That's basically what it is like, except real install scripts usually contain a bit more information. I have not seen any that are fundamentally more complicated, though. In essence, you just give it a list of what needs to be installed. Sometimes you need to give it some mapping dicts since the source and installed trees might not be the same. Here is a real-life (anonymized) example: #!/usr/bin/python from distutils.core import setup setup (name = 'Initech Package 3', description = "Services and libraries ABC, DEF", author = "That Guy, Initech Ltd", author_email = "that.guy@initech.com", version = '1.0.5', package_dir = {'Package3' : 'site-packages/Package3'}, packages = ['Package3', 'Package3.Queries'], data_files = [ ('/etc/Package3', ['etc/Package3/ExternalResources.conf']) ])
I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up. From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so? Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.
How do threads work in Python, and what are common Python-threading specific pitfalls?
Yes, because of the Global Interpreter Lock (GIL) there can only run one thread at a time. Here are some links with some insights about this: http://www.artima.com/weblogs/viewpost.jsp?thread=214235 http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/ From the last link an interesting quote: Let me explain what all that means. Threads run inside the same virtual machine, and hence run on the same physical machine. Processes can run on the same physical machine or in another physical machine. If you architect your application around threads, you’ve done nothing to access multiple machines. So, you can scale to as many cores are on the single machine (which will be quite a few over time), but to really reach web scales, you’ll need to solve the multiple machine problem anyway. If you want to use multi core, pyprocessing defines an process based API to do real parallelization. The PEP also includes some interesting benchmarks.
I have a tree structure in memory that I would like to render in HTML using a Django template. class Node(): name = "node name" children = [] There will be some object root that is a Node, and children is a list of Nodes. root will be passed in the content of the template. I have found this one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment. Does anybody know of a better way?
How can I render a tree structure (recursive) using a django template?
Using with template tag, I could do tree/recursive list. Sample code: main template: assuming 'all_root_elems' is list of one or more root of tree <ul> {%for node in all_root_elems %} {%include "tree_view_template.html" %} {%endfor%} </ul> tree_view_template.html renders the nested ul, li and uses node template variable as below: <li> {{node.name}} {%if node.has_childs %} <ul> {%for ch in node.all_childs %} {%with node=ch template_name="tree_view_template.html" %} {%include template_name%} {%endwith%} {%endfor%} </ul> {%endif%} </li>
I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service. I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to demonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services. Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)? I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines. Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: How is Windows aware of my service? Can I manage it with the native Windows utilities? Basically, what is the equivalent of putting a start/stop script in /etc/init.d?
Is it possible to run a Python script as a service in Windows? If possible, how?
Yes you can. I do it using the pythoncom libraries that come included with ActivePython or can be installed with pywin32 (Python for Windows extensions). This is a basic skeleton for a simple service: import win32serviceutil import win32service import win32event import servicemanager import socket class AppServerSvc (win32serviceutil.ServiceFramework): _svc_name_ = "TestService" _svc_display_name_ = "Test Service" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.main() def main(self): pass if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) Your code would go in the main() method, usually with some kind of infinite loop that might be interrumped by checking a flag, that you set in the SvcStop method
I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this: import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?
How to generate dynamic (parametrized) unit tests in python?
i use something like this: import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequense(unittest.TestCase): pass def test_generator(a, b): def test(self): self.assertEqual(a,b) return test if __name__ == '__main__': for t in l: test_name = 'test_%s' % t[0] test = test_generator(t[1], t[2]) setattr(TestSequense, test_name, test) unittest.main() The nose-parameterized package can be used to automate this process: from nose_parameterized import parameterized class TestSequence(unittest.TestCase): @parameterized.expand([ ["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"], ]) def test_sequence(self, name, a, b): self.assertEqual(a,b) Which will generate the tests: test_sequence_0_foo (__main__.TestSequence) ... ok test_sequence_1_bar (__main__.TestSequence) ... FAIL test_sequence_2_lee (__main__.TestSequence) ... ok ====================================================================== FAIL: test_sequence_1_bar (__main__.TestSequence) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/nose_parameterized/parameterized.py", line 233, in <lambda> standalone_func = lambda *a: func(*(a + p.args), **p.kwargs) File "x.py", line 12, in test_sequence self.assertEqual(a,b) AssertionError: 'a' != 'b'
How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want.
Find out how much memory is being used by an object in Python
There's no easy way to find out the memory size of a python object. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries). There is a big chunk of code (and an updated big chunk of code) out there to try to best approximate the size of a python object in memory. There's also some simpler approximations. But they will always be approximations. You may also want to check some old description about PyObject (the internal C struct that represents virtually all python objects).
A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor?
Are Python threads buggy?
Python threads are good for concurrent I/O programming. Threads are swapped out of the CPU as soon as they block waiting for input from file, network, etc. This allows other Python threads to use the CPU while others wait. This would allow you to write a multi-threaded web server or web crawler, for example. However, Python threads are serialized by the GIL when they enter interpreter core. This means that if two threads are crunching numbers, only one can run at any given moment. It also means that you can't take advantage of multi-core or multi-processor architectures. There are solutions like running multiple Python interpreters concurrently, using a C based threading library. This is not for the faint of heart and the benefits might not be worth the trouble. Let's hope for an all Python solution in a future release.
What's the best way to specify a proxy with username and password for an http connection in python?
How to specify an authenticated proxy for a python http connection?
This works for me: import urllib2 proxy = urllib2.ProxyHandler({'http': 'http:// username:password@proxyurl:proxyport'}) auth = urllib2.HTTPBasicAuthHandler() opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) urllib2.install_opener(opener) conn = urllib2.urlopen('http://python.org') return_str = conn.read()
Given a Python object of any kind, is there an easy way to get a list of all methods that this object has? Or, if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?
Finding what methods an object has
It appears you can use this code, replacing 'object' with the object you're interested in:- [method for method in dir(object) if callable(getattr(object, method))] I discovered it at this site, hopefully that should provide some further detail!
What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.
Validate (X)HTML in Python
http://countergram.com/software/pytidylib is a nice python binding for HTML Tidy. Their example: from tidylib import tidy_document document, errors = tidy_document('''<p>f&otilde;o <img src="bar.jpg">''', options={'numeric-entities':1}) print document print errors
Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)? What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.
Is Python good for big software projects (not web based)?
We've used IronPython to build our flagship spreadsheet application (40kloc production code - and it's Python, which IMO means loc per feature is low) at Resolver Systems, so I'd definitely say it's ready for production use of complex apps. There are two ways in which this might not be a useful answer to you :-) We're using IronPython, not the more usual CPython. This gives us the huge advantage of being able to use .NET class libraries. I may be setting myself up for flaming here, but I would say that I've never really seen a CPython application that looked "professional" - so having access to the WinForms widget set was a huge win for us. IronPython also gives us the advantage of being able to easily drop into C# if we need a performance boost. (Though to be honest we have never needed to do that. All of our performance problems to date have been because we chose dumb algorithms rather than because the language was slow.) Using C# from IP is much easier than writing a C Extension for CPython. We're an Extreme Programming shop, so we write tests before we write code. I would not write production code in a dynamic language without writing the tests first; the lack of a compile step needs to be covered by something, and as other people have pointed out, refactoring without it can be tough. (Greg Hewgill's answer suggests he's had the same problem. On the other hand, I don't think I would write - or especially refactor - production code in any language these days without writing the tests first - but YMMV.) Re: the IDE - we've been pretty much fine with each person using their favourite text editor; if you prefer something a bit more heavyweight then WingIDE is pretty well-regarded.
If I create a class A as follows: class A: def __init__(self): self.name = 'A' Inspecting the __dict__ member looks like {'name': 'A'} If however I create a class B: class B: name = 'B' __dict__ is empty. What is the difference between the two, and why doesn't name show up in B's __dict__?
Why is my instance variable not in __dict__?
B.name is a class attribute, not an instance attribute. It shows up in B.__dict__, but not in b = B(); b.__dict__. The distinction is obscured somewhat because when you access an attribute on an instance, the class dict is a fallback. So in the above example, b.name will give you the value of B.name.
When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash. I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option: def sh_escape(s): return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ") os.system("cat %s | grep something | sort > %s" % (sh_escape(in_filename), sh_escape(out_filename))) Edit: I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently. Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).
How to escape os.system() calls in Python?
shlex.quote() does what you want since python 3. (Use pipes.quote to support both python 2 and python 3)
I'm using Google App Engine and Django templates. I have a table that I want to display the objects look something like: Object Result: Items = [item1,item2] Users = [{name='username',item1=3,item2=4},..] The Django template is: <table> <tr align="center"> <th>user</th> {% for item in result.items %} <th>{{item}}</th> {% endfor %} </tr> {% for user in result.users %} <tr align="center"> <td>{{user.name}}</td> {% for item in result.items %} <td>{{ user.item }}</td> {% endfor %} </tr> {% endfor %} </table> Now the Django documention states that when it sees a . in variables It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen...
Django templates and variable attributes
I found a "nicer"/"better" solution for getting variables inside Its not the nicest way, but it works. You install a custom filter into django which gets the key of your dict as a parameter To make it work in google app-engine you need to add a file to your main directory, I called mine *django_hack.py* which contains this little piece of code from google.appengine.ext import webapp register = webapp.template.create_template_register() def hash(h,key): if key in h: return h[key] else: return None register.filter(hash) Now that we have this file, all we need to do is tell the app-engine to use it... we do that by adding this little line to your main file webapp.template.register_template_library('django_hack') and in your template view add this template instead of the usual code {{ user|hash:item }} And its should work perfectly =)
Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like: class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3
C-like structures in Python
Use a named tuple, which was added to the collections module in the standard library in Python 2.6. It's also possible to use Raymond Hettinger's named tuple recipe if you need to support Python 2.4. It's nice for your basic example, but also covers a bunch of edge cases you might run into later as well. Your fragment above would be written as: from collections import namedtuple MyStruct = namedtuple("MyStruct", "field1 field2 field3") The newly created type can be used like this: m = MyStruct("foo", "bar", "baz") Or you can use named arguments: m = MyStruct(field1 = "foo", field2 = "bar", field3 = "baz")
What is the best way of creating an alphabetically sorted list in Python?
How do I sort a list of strings in Python?
Basic answer: mylist = ["b", "C", "A"] mylist.sort() This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the sorted() function: for x in sorted(mylist): print x However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter key to specify custom sorting order (the alternative, using cmp, is a deprecated solution, as it has to be evaluated multiple times - key is only computed once per element). So, to sort according to the current locale, taking language-specific rules into account (cmp_to_key is a helper function from functools): sorted(mylist, key=cmp_to_key(locale.strcoll)) And finally, if you need, you can specify a custom locale for sorting: import locale locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale assert sorted((u'Ab', u'ad', u'aa'), key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad'] Last note: you will see examples of case-insensitive sorting which use the lower() method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data: # this is incorrect! mylist.sort(key=lambda x: x.lower()) # alternative notation, a bit faster, but still wrong mylist.sort(key=str.lower)
In the following method definitions, what does the * and ** do for param2? def foo(param1, *param2): def bar(param1, **param2):
What does ** (double star) and * (star) do for Python parameters?
The *args and **kwargs is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation. The *args will give you all function parameters as a tuple: In [1]: def foo(*args): ...: for a in args: ...: print a ...: ...: In [2]: foo(1) 1 In [4]: foo(1,2,3) 1 2 3 The **kwargs will give you all keyword arguments except for those corresponding to a formal parameter as a dictionary. In [5]: def bar(**kwargs): ...: for a in kwargs: ...: print a, kwargs[a] ...: ...: In [6]: bar(name='one', age=27) age 27 name one Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments: def foo(kind, *args, **kwargs): pass Another usage of the *l idiom is to unpack argument lists when calling a function. In [9]: def foo(bar, lee): ...: print bar, lee ...: ...: In [10]: l = [1,2] In [11]: foo(*l) 1 2 In Python 3 it is possible to use *l on the left side of an assignment (Extended Iterable Unpacking): first, *rest = [1,2,3,4] first, *l, last = [1,2,3,4] Also Python 3 adds new semantic (refer PEP 3102): def func(arg1, arg2, arg3='default', *, kwarg1='abc', kwarg2='xyz'): pass Such function accepts only 2 positional arguments, and everything after * can only be passed as keyword argument, not positional one. In Python 2 similar was true for all parameters after *args.
I'm mainly a C# developer, but I'm currently working on a project in Python. How can I represent the equivalent of an Enum in Python?
How can I represent an 'Enum' in Python?
Enums have been added to Python 3.4 as described in PEP 435. It has also been backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4 on pypi. For more advanced Enum techniques try the aenum library (2.7, 3.3+, same author as enum34. Code is not perfectly compatible between py2 and py3, e.g. you'll need __order__ in python 2). To use enum34, do $ pip install enum34 To use aenum, do $ pip install aenum Installing enum (no numbers) will install a completely different and incompatible version. from enum import Enum # for enum34, or the stdlib version # from aenum import Enum # for the aenum version Animal = Enum('Animal', 'ant bee cat dog') Animal.ant # returns <Animal.ant: 1> Animal['ant'] # returns <Animal.ant: 1> (string lookup) Animal.ant.name # returns 'ant' (inverse lookup) or equivalently: class Animal(Enum): ant = 1 bee = 2 cat = 3 dog = 4 In earlier versions, one way of accomplishing enums is: def enum(**enums): return type('Enum', (), enums) which is used like so: >>> Numbers = enum(ONE=1, TWO=2, THREE='three') >>> Numbers.ONE 1 >>> Numbers.TWO 2 >>> Numbers.THREE 'three' You can also easily support automatic enumeration with something like this: def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) and used like so: >>> Numbers = enum('ZERO', 'ONE', 'TWO') >>> Numbers.ZERO 0 >>> Numbers.ONE 1 Support for converting the values back to names can be added this way: def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) reverse = dict((value, key) for key, value in enums.iteritems()) enums['reverse_mapping'] = reverse return type('Enum', (), enums) This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw KeyError if the reverse mapping doesn't exist. With the first example: >>> Numbers.reverse_mapping['three'] 'THREE'
Can people point me to resources on lexing, parsing and tokenising with Python? I'm doing a little hacking on an open source project (hotwire) and wanted to do a few changes to the code that lexes, parses and tokenises the commands entered into it. As it is real working code it is fairly complex and a bit hard to work out. I haven't worked on code to lex/parse/tokenise before, so I was thinking one approach would be to work through a tutorial or two on this aspect. I would hope to learn enough to navigate around the code I actually want to alter. Is there anything suitable out there? (Ideally it could be done in an afternoon without having to buy and read the dragon book first ...) Edit: (7 Oct 2008) None of the below answers quite give what I want. With them I could generate parsers from scratch, but I want to learn how to write my own basic parser from scratch, not using lex and yacc or similar tools. Having done that I can then understand the existing code better. So could someone point me to a tutorial where I can build a basic parser from scratch, using just python?
Resources for lexing, tokenising and parsing in python
I'm a happy user of PLY. It is a pure-Python implementation of Lex & Yacc, with lots of small niceties that make it quite Pythonic and easy to use. Since Lex & Yacc are the most popular lexing & parsing tools and are used for the most projects, PLY has the advantage of standing on giants' shoulders. A lot of knowledge exists online on Lex & Yacc, and you can freely apply it to PLY. PLY also has a good documentation page with some simple examples to get you started. For a listing of lots of Python parsing tools, see this.
Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python.
Filter out HTML tags and resolve entities in python
Use lxml which is the best xml/html library for python. import lxml.html t = lxml.html.fromstring("...") t.text_content() And if you just want to sanitize the html look at the lxml.html.clean module
I've got a bunch of FoxPro (VFP9) DBF files on my Ubuntu system, is there a library to open these in Python? I only need to read them, and would preferably have access to the memo fields too. Update: Thanks @cnu, I used Yusdi Santoso's dbf.py and it works nicely. One gotcha: The memo file name extension must be lower case, i.e. .fpt, not .FPT which was how the filename came over from Windows.
What's the easiest way to read a FoxPro DBF file from Python?
I prefer dbfpy. It supports both reading and writing of .DBF files and can cope with most variations of the format. It's the only implementation I have found that could both read and write the legacy DBF files of some older systems I have worked with.
I'm teaching myself Python and my most recent lesson was that Python is not Java, and so I've just spent a while turning all my Class methods into functions. I now realise that I don't need to use Class methods for what I would done with static methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them. Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?
What are Class methods in Python for?
Class methods are for when you need to have methods that aren't specific to any particular instance, but still involve the class in some way. The most interesting thing about them is that they can be overridden by subclasses, something that's simply not possible in Java's static methods or Python's module-level functions. If you have a class MyClass, and a module-level function that operates on MyClass (factory, dependency injection stub, etc), make it a classmethod. Then it'll be available to subclasses.
I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string. Related question: Is it pythonic for a function to return multiple values?
What's the best way to return multiple values from a function in Python?
def f(in_str): out_str = in_str.upper() return True, out_str # Creates tuple automatically succeeded, b = f("a") # Automatic tuple unpacking
How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view? I have looked through the Django forms documentation, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it? Here is my template that I want it applied on. <form action="." method="POST"> <table> {% for f in form %} <tr> <td> {{ f.name }}</td> <td>{{ f }}</td> </tr> {% endfor %} </table> <input type="submit" name="submit" value="Add Product"> </form> Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py: (r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...
Using Django time/date widgets in custom form
The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doing this at all. It's relying on undocumented internal implementation details of the admin, is likely to break again in future versions of Django, and is no easier to implement than just finding another JS calendar widget and using that. That said, here's what you have to do if you're determined to make this work: Define your own ModelForm subclass for your model (best to put it in forms.py in your app), and tell it to use the AdminDateWidget / AdminTimeWidget / AdminSplitDateTime (replace 'mydate' etc with the proper field names from your model): from django import forms from my_app.models import Product from django.contrib.admin import widgets class ProductForm(forms.ModelForm): class Meta: model = Product def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.fields['mydate'].widget = widgets.AdminDateWidget() self.fields['mytime'].widget = widgets.AdminTimeWidget() self.fields['mydatetime'].widget = widgets.AdminSplitDateTime() Change your URLconf to pass 'form_class': ProductForm instead of 'model': Product to the generic create_object view (that'll mean "from my_app.forms import ProductForm" instead of "from my_app.models import Product", of course). In the head of your template, include {{ form.media }} to output the links to the Javascript files. And the hacky part: the admin date/time widgets presume that the i18n JS stuff has been loaded, and also require core.js, but don't provide either one automatically. So in your template above {{ form.media }} you'll need: <script type="text/javascript" src="/my_admin/jsi18n/"></script> <script type="text/javascript" src="/media/admin/js/core.js"></script> You may also wish to use the following admin CSS (thanks Alex for mentioning this): <link rel="stylesheet" type="text/css" href="/media/admin/css/forms.css"/> <link rel="stylesheet" type="text/css" href="/media/admin/css/base.css"/> <link rel="stylesheet" type="text/css" href="/media/admin/css/global.css"/> <link rel="stylesheet" type="text/css" href="/media/admin/css/widgets.css"/> This implies that Django's admin media (ADMIN_MEDIA_PREFIX) is at /media/admin/ - you can change that for your setup. Ideally you'd use a context processor to pass this values to your template instead of hardcoding it, but that's beyond the scope of this question. This also requires that the URL /my_admin/jsi18n/ be manually wired up to the django.views.i18n.javascript_catalog view (or null_javascript_catalog if you aren't using I18N). You have to do this yourself instead of going through the admin application so it's accessible regardless of whether you're logged into the admin (thanks Jeremy for pointing this out). Sample code for your URLconf: (r'^my_admin/jsi18n', 'django.views.i18n.javascript_catalog'), Lastly, if you are using Django 1.2 or later, you need some additional code in your template to help the widgets find their media: {% load adminmedia %} /* At the top of the template. */ /* In the head section of the template. */ <script type="text/javascript"> window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}"; </script> Thanks lupefiasco for this addition.
I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The update() method would be what I need, if it returned its result instead of modifying a dict in-place. >>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> z = x.update(y) >>> print z None >>> x {'a': 1, 'b': 10, 'c': 11} How can I get that final merged dict in z, not x? (To be extra-clear, the last-one-wins conflict-handling of dict.update() is what I'm looking for as well.)
How to merge two Python dictionaries in a single expression?
In your case, what you can do is: z = dict(x.items() + y.items()) This will, as you want it, put the final dict in z, and make the value for key b be properly overridden by the second (y) dict's value: >>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> z = dict(x.items() + y.items()) >>> z {'a': 1, 'c': 11, 'b': 10} If you use Python 3, it is only a little more complicated. To create z: >>> z = dict(list(x.items()) + list(y.items())) >>> z {'a': 1, 'c': 11, 'b': 10}
I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it. What is the best way to do this, within the following code? f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file
Search and replace a line in a file in Python
The shortest way would probably be to use the fileinput module. For example, the following adds line numbers to a file, in-place: import fileinput for line in fileinput.input("test.txt", inplace=True): print "%d: %s" % (fileinput.filelineno(), line), What happens here is: The original file is moved to a backup file The standard output is redirected to the original file within the loop Thus any print statements write back into the original file fileinput has more bells and whistles. For example, it can be used to automatically operate on all files in sys.args[1:], without your having to iterate over them explicitly. Starting with Python 3.2 it also provides a convenient context manager for use in a with statement. While fileinput is great for throwaway scripts, I would be wary of using it in real code because admittedly it's not very readable or familiar. In real (production) code it's worthwhile to spend just a few more lines of code to make the process explicit and thus make the code readable. There are two options: The file is not overly large, and you can just read it wholly to memory. Then close the file, reopen it in writing mode and write the modified contents back. The file is too large to be stored in memory; you can move it over to a temporary file and open that, reading it line by line, writing back into the original file. Note that this requires twice the storage.
I've written a Python package that includes a bsddb database of pre-computed values for one of the more time-consuming computations. For simplicity, my setup script installs the database file in the same directory as the code which accesses the database (on Unix, something like /usr/lib/python2.5/site-packages/mypackage/). How do I store the final location of the database file so my code can access it? Right now, I'm using a hack based on the __file__ variable in the module which accesses the database: dbname = os.path.join(os.path.dirname(__file__), "database.dat") It works, but it seems... hackish. Is there a better way to do this? I'd like to have the setup script just grab the final installation location from the distutils module and stuff it into a "dbconfig.py" file that gets installed alongside the code that accesses the database.
Finding a file in a Python module distribution
Try using pkg_resources, which is part of setuptools (and available on all of the pythons I have access to right now): >>> import pkg_resources >>> pkg_resources.resource_ filename(__name__, "foo.config") 'foo.config' >>> pkg_resources.resource_filename('tempfile', "foo.config") '/usr/lib/python2.4/foo.config' There's more discussion about using pkg_resources to get resources on the eggs page and the pkg_resources page. Also note, where possible it's probably advisable to use pkg_resources.resource_stream or pkg_resources.resource_string because if the package is part of an egg, resource_filename will copy the file to a temporary directory.
I'm reading some MPEG Transport Stream protocol over UDP and it has some funky bitfields in it (length 13 for example). I'm using the "struct" library to do the broad unpacking, but is there a simple way to say "Grab the next 13 bits" rather than have to hand-tweak the bit manipulation? I'd like something like the way C does bit fields (without having to revert to C). Suggestions?
What is the best way to do Bit Field manipulation in Python?
The bitstring module is designed to address just this problem. It will let you read, modify and construct data using bits as the basic building blocks. The latest versions are for Python 2.6 or later (including Python 3) but version 1.0 supported Python 2.4 and 2.5 as well. A relevant example for you might be this, which strips out all the null packets from a transport stream (and quite possibly uses your 13 bit field?): from bitstring import Bits, BitStream # Opening from a file means that it won't be all read into memory s = Bits(filename='test.ts') outfile = open('test_nonull.ts', 'wb') # Cut the stream into 188 byte packets for packet in s.cut(188*8): # Take a 13 bit slice and interpret as an unsigned integer PID = packet[11:24].uint # Write out the packet if the PID doesn't indicate a 'null' packet if PID != 8191: # The 'bytes' property converts back to a string. outfile.write(packet.bytes) Here's another example including reading from bitstreams: # You can create from hex, binary, integers, strings, floats, files... # This has a hex code followed by two 12 bit integers s = BitStream('0x000001b3, uint:12=352, uint:12=288') # Append some other bits s += '0b11001, 0xff, int:5=-3' # read back as 32 bits of hex, then two 12 bit unsigned integers start_code, width, height = s.readlist('hex:32, 2*uint:12') # Skip some bits then peek at next bit value s.pos += 4 if s.peek(1): flags = s.read(9) You can use standard slice notation to slice, delete, reverse, overwrite, etc. at the bit level, and there are bit level find, replace, split etc. functions. Different endiannesses are also supported. # Replace every '1' bit by 3 bits s.replace('0b1', '0b001') # Find all occurrences of a bit sequence bitposlist = list(s.findall('0b01000')) # Reverse bits in place s.reverse() The full documentation is here.
In python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals(). Is there some equivalent way of doing this in javascript? For instance, I would like to do something like the following: var foo = function(){ alert('foo'); }; var bar = function(){ alert('bar'); }; var s = 'foo'; locals()[s](); // alerts 'foo' Is this at all possible, or should I just be using a local object for the lookup?
javascript locals()?
locals() - No. globals() - Yes. window is a reference to the global scope, like globals() in python. globals()["foo"] is the same as: window["foo"]
At the beginning of all my executable Python scripts I put the shebang line: #!/usr/bin/env python I'm running these scripts on a system where env python yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version: if sys.version_info < (2, 4): raise ImportError("Cannot run with Python version < 2.4") I don't want to have to change the shebang line on every executable file, if it's possible; however, I don't have administrative access to the machine to change the result of env python and I don't want to force a particular version, as in: #!/usr/bin/env python2.4 I'd like to avoid this because system may have a newer version than Python 2.4, or may have Python 2.5 but no Python 2.4. What's the elegant solution? [Edit:] I wasn't specific enough in posing the question -- I'd like to let users execute the scripts without manual configuration (e.g. path alteration or symlinking in ~/bin and ensuring your PATH has ~/bin before the Python 2.2 path). Maybe some distribution utility is required to prevent the manual tweaks?
Python deployment and /usr/bin/env portability
"env" simply executes the first thing it finds in the PATH env var. To switch to different python, prepend the directory for that python's executable to the path before invoking your script.
I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests. In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation? Or will I have to make my own custom shortcuts to setup the context properly?
Always including the user in the django template context
There is no need to write a context processor for the user object if you already have the "django.core.context_processors.auth" in TEMPLATE_CONTEXT_PROCESSORS and if you're using RequestContext in your views. if you are using django 1.4 or latest the module has been moved to django.contrib.auth.context_processors.auth
I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username) For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this? Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)
Splitting tuples in Python - best practice?
I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values. For example: job={} job['jobid'], job['label'], job['username']=<querycode>
I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?
What is a tuple useful for?
Tuples are used whenever you want to return multiple results from a function. Since they're immutable, they can be used as keys for a dictionary (lists can't).
Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.) Antiword seems like it might be a reasonable option, but it seems like it might be abandoned. A Python solution would be ideal, but doesn't appear to be available.
Best way to extract text from a Word doc without using COM/automation?
(Same answer as extracting text from MS word files in python) Use the native Python docx module which I made this week. Here's how to extract all the text from a doc: document = opendocx('Hello world.docx') # This location is where most document content lives docbody = document.xpath('/w:document/w:body', namespaces=wordnamespaces)[0] # Extract all text print getdocumenttext(document) See Python DocX site 100% Python, no COM, no .net, no Java, no parsing serialized XML with regexs, no crap.
The Python docs say: re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string... So what's going on when I get the following unexpected result? >>> import re >>> s = """// The quick brown fox. ... // Jumped over the lazy dog.""" >>> re.sub('^//', '', s, re.MULTILINE) ' The quick brown fox.\n// Jumped over the lazy dog.'
Python re.sub MULTILINE caret match
Look at the definition of re.sub: sub(pattern, repl, string[, count]) The 4th argument is the count, you are using re.MULTILINE (which is 8) as the count, not as a flag. You have to compile your regex if you wish to use flags. re.sub(re.compile('^//', re.MULTILINE), '', s) A flags argument was added in Python 2.7, so the full definition is now: re.sub(pattern, repl, string[, count, flags]) Which means that: re.sub('^//', '', s, flags=re.MULTILINE) works.
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month? If the standard library doesn't support that, does the dateutil package support this?
Get Last Day of the Month in Python
I didn't notice this earlier when I was looking at the documentation for the calendar module, but a method called monthrange provides this information: monthrange(year, month)     Returns weekday of first day of the month and number of days in month, for the specified year and month. >>> import calendar >>> calendar.monthrange(2002,1) (1, 31) >>> calendar.monthrange(2008,2) (4, 29) >>> calendar.monthrange(2100,2) (0, 28) so: calendar.monthrange(year, month)[1] seems like the simplest way to go. Just to be clear, monthrange supports leap years as well: >>> from calendar import monthrange >>> monthrange(2012, 2) (2, 29) My previous answer still works, but is clearly suboptimal.
In Django's template language, you can use {% url [viewname] [args] %} to generate a URL to a specific view with parameters. How can you programatically do the same in Python code? What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language.
How to generate urls in django
If you need to use something similar to the {% url %} template tag in your code, Django provides the django.core.urlresolvers.reverse(). The reverse function has the following signature: reverse(viewname, urlconf=None, args=None, kwargs=None) https://docs.djangoproject.com/en/dev/ref/urlresolvers/
Using PyObjC, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?
Can I write native iPhone apps using Python
You can use PyObjC on the iPhone as well, due to the excellent work by Jay Freeman (saurik). See iPhone Applications in Python. Note that this requires a jailbroken iPhone at the moment.
I'm a firm believer of the heretic thought of tight coupling between the backend and frontend: I want existing, implied knowledge about a backend to be automatically made use of when generating user interfaces. E.g., if a VARCHAR column has a maximum with of 20 characters, there GUIs should automatically constrain the user from typing more than 20 characters in a related form field. And I have strong antipathy to ORMs which want to define my database tables, or are based on some hack where every table needs to have extra numeric ID columns because of the ORM. I've looked a bit into Python database frameworks and I think I can conclude the SQLAlchemy fits best to my mentality. Now, I need to find a web application framework which fits naturally with SQLAlchemy (or an equivalent) and perhaps even with my appetite for coupling. With "web application framework", I mean products/project such as Pyhons, Django, TurboGears, web2py, etc. E.g., it should ideally be able to: automatically select a suitable form widget for data entering a given column if told to do so; e.g., if the column has a foreign key to a column with 10 different values, widget should display the 10 possible values as a dropdown auto-generate javascript form validation code which gives the end-user quick error feedback if a string is entered into a field which is about to end up in an INTEGER column, etc auto-generate a calendar widget for data which will end up in a DATE column hint NOT NULL constraints as javascript which complains about empty or whitespace-only data in a related input field generate javascript validation code which matches relevant (simple) CHECK-constraints make it easy to avoid SQL injection, by using prepared statements and/or validation of externally derived data make it easy to avoid cross site scripting by automatically escape outgoing strings when appropriate make use of constraint names to generate somewhat user friendly error messages in case a constrataint is violated All this should happen dynamically, so table adjustments are automatically reflected on the frontend - probably with a caching mechanism, so that all the model introspection wouldn't kill performance. In other words, I don't want to repeat my model definition in an XML file (or alike) when it has already been carefully been defined in my database. Does such a framework exist for Python (or for any language, for that matter)? If not: Which of the several Python web application frameworks will be least in the way if I were to add parts of the above features myself?
A python web application framework for tight DB/GUI coupling?
web2py does most of what you ask: Based on a field type and its validators it will render the field with the appropriate widget. You can override with db.table.field.widget=... and use a third party widget. web2py has js to blocks the user from entering a non-integer in a integer field or a non-double in a double field. time, date and datetime fields have their own pickers. These js validation work with (not instead) of server side validation. There is IS_EMPTY_OR(...) validator. The DAL prevents SQL injections since everthing is escaped when goes in the DB. web2py prevents XSS because in {{=variable}}, 'variable' is escaped unless specified otherwise {{=XML(variable)}} or {{=XML(variable,sanitize=True)}} Error messages are arguments of validators for example db.table.field.requires=IS_NOT_EMPTY(error_message=T('hey! write something in here')) T is for internationalization.
Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer. Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response. Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type. How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. Does the browser add this information when posting the file to the web page? Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?
How to find the mime type of a file in python?
The python-magic method suggested by toivotuo is outdated. Python-magic's current trunk is at Github and based on the readme there, finding the MIME-type, is done like this. # For MIME types >>> import magic >>> mime = magic.Magic(mime=True) >>> mime.from_file("testdata/test.pdf") 'application/pdf' >>>
I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that. It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like web.py, Pyroxide and Django. What are the pros and cons of the frameworks or approaches that you've worked on? What trade-offs are there? For what kind of projects they do well and for what they don't? Edit: I haven't got much experience with web programing yet. I would like to avoid the basic and tedious things like parsing the URL for parameters, etc. On the other hand, while the video of blog created in 15 minutes with Ruby on Rails left me impressed, I realized that there were hundreds of things hidden from me - which is cool if you need to write a working webapp in no time, but not that great for really understanding the magic - and that's what I seek now.
Pros and Cons of different approaches to web programming in Python
CGI is great for low-traffic websites, but it has some performance problems for anything else. This is because every time a request comes in, the server starts the CGI application in its own process. This is bad for two reasons: 1) Starting and stopping a process can take time and 2) you can't cache anything in memory. You can go with FastCGI, but I would argue that you'd be better off just writing a straight WSGI app if you're going to go that route (the way WSGI works really isn't a whole heck of a lot different from CGI). Other than that, your choices are for the most part how much you want the framework to do. You can go with an all singing, all dancing framework like Django or Pylons. Or you can go with a mix-and-match approach (use something like CherryPy for the HTTP stuff, SQLAlchemy for the database stuff, paste for deployment, etc). I should also point out that most frameworks will also let you switch different components out for others, so these two approaches aren't necessarily mutually exclusive. Personally, I dislike frameworks that do too much magic for me and prefer the mix-and-match technique, but I've been told that I'm also completely insane. :) How much web programming experience do you have? If you're a beginner, I say go with Django. If you're more experienced, I say to play around with the different approaches and techniques until you find the right one.
Can you please tell me how much is (-2) % 5? According to my Python interpreter is 3, but do you have a wise explanation for this? I've read that in some languages the result can be machine-dependent, but I'm not sure though.
Modulus operation with negatives values - weird thing?
By the way: most programming languages would disagree with Python and give the result -2. Depending on the interpretation of modulus this is correct. However, the most agreed-upon mathematical definition states that the modulus of a and b is the (strictly positive) rest r of the division of a / b. More precisely, 0 <= r < b by definition.
That's it. If you want to document a function or a class, you put a string just after the definition. For instance: def foo(): """This function does nothing.""" pass But what about a module? How can I document what a file.py does?
How do I document a module in Python?
For the packages, you can document it in __init__.py. For the modules, you can add a docstring simply in the module file. All the information is here: http://www.python.org/dev/peps/pep-0257/
In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?
Iterate over subclasses of a given class in a given module
Although Quamrana's suggestion works fine, there are a couple of possible improvements I'd like to suggest to make it more pythonic. They rely on using the inspect module from the standard library. You can avoid the getattr call by using inspect.getmembers() The try/catch can be avoided by using inspect.isclass() With those, you can reduce the whole thing to a single list comprehension if you like: def find_subclasses(module, clazz): return [ cls for name, cls in inspect.getmembers(module) if inspect.isclass(cls) and issubclass(cls, clazz) ]
What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, [ 'a', 'b', 'c' ] to 'a,b,c'? (The cases [ s ] and [] should be mapped to s and '', respectively.) I usually end up using something like ''.join(map(lambda x: x+',',l))[:-1], but also feeling somewhat unsatisfied. Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed "simple" concatenation in the past and somehow memorised s.join([e1,e2,...]) as a shorthand for s+e1+e2+....)
How would you make a comma-separated string from a list?
myList = ['a','b','c','d'] myString = ",".join(myList ) This won't work if the list contains numbers. As Ricardo Reyes suggested, if it contains non-string types (such as integers, floats, bools, None) then do: myList = ','.join(map(str, myList))
I have been using Python more and more, and I keep seeing the variable __all__ set in different __init__.py files. Can someone explain what this does?
Can someone explain __all__ in Python?
Linked to, but not explicitly mentioned here, is exactly when __all__ is used. It is a list of strings defining what symbols in a module will be exported when from <module> import * is used on the module. For example, the following code in a foo.py explicitly exports the symbols bar and baz: __all__ = ['bar', 'baz'] waz = 5 bar = 10 def baz(): return 'baz' These symbols can then be imported like so: from foo import * print bar print baz # The following will trigger an exception, as "waz" is not exported by the module print waz If the __all__ above is commented out, this code will then execute to completion, as the default behaviour of import * is to import all symbols that do not begin with an underscore, from the given namespace. Reference: https://docs.python.org/3.5/tutorial/modules.html#importing-from-a-package NOTE: __all__ affects the from <module> import * behavior only. Members that are not mentioned in __all__ are still accessible from outside the module and can be imported with from <module> import <member>.
Say I have the following file structure: app/ app.py controllers/ __init__.py project.py plugin.py If app/controllers/project.py defines a class Project, app.py would import it like this: from app.controllers.project import Project I'd like to just be able to do: from app.controllers import Project How would this be done?
Python packages - import by class, not file
You need to put from project import Project in controllers/__init__.py. Note that when Absolute imports become the default (Python 2.7?), you will want to add a dot before the module name (to avoid collisions with a top-level model named project), i.e., from .project import Project
I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online?
Where can I find the time and space complexity of the built-in sequence types in Python
Checkout the TimeComplexity page on the py dot org wiki. It covers set/dicts/lists/etc at least as far as time complexity goes.
I'm looking to create favicon.ico files programatically from Python, but PIL only has support for reading ico files.
Is there a Python library for generating .ico files?
Perhaps the following would work: Generate your icon image using PIL Convert the image to .ico format using the python interface to ImageMagick, PythonMagick I have not tried this approach. The ImageMagick convert command line program was able to convert a .png file to .ico format, so at least ImageMagick supports the .ico format.
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
123