instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
How to set the PYTHONPATH in Emacs?
Emacs does not recognize my correct python path. I think it is a general problem with emacs not recognizing my environment variables. I have GNU Emacs 22.1.1 (i386-apple-darwin8.9.1, Carbon Version 1.6.0) of 2007-06-17 installed. I have set the PYTHONPATH in my ~/.bashrc. Maybe I should set it somewhere else?
.bashrc only gets read when a shell starts; it won't affect Carbon Emacs. Instead, use setenv in your .emacs: (setenv "PYTHONPATH" "PATH_STRING_HERE") You can set PYTHONPATH for the entire Mac OS session, by adding it to ~/.MacOSX/environment.plist (more here). You probably don't want to do this unless you have XCode (and its property list editor) installed. (Via Procrastiblog)
How to copy all properties of an object to another object, in Python?
Is there a library method to copy all the properties between two (already present) instances of the same class, in Python? I mean, something like Apache Commons' PropertyUtilsBean.copyProperties() Thanks!
Try destination.__dict__.update(source.__dict__).
What is the OCaml idiom equivalent to Python's range function?
I want to create a list of integers from 1 to n. I can do this in Python using range(1, n+1), and in Haskell using: take n (iterate (1+) 1). What is the right OCaml idiom for this?
There is no idiom that I know of, but here is a fairly natural definition using an infix operator: # let (--) i j = let rec aux n acc = if n < i then acc else aux (n-1) (n :: acc) in aux j [] ;; val ( -- ) : int -> int -> int list = <fun> # 1--2;; - : int list = [1; 2] # 1--5;; - : int list = [1; 2; 3; 4; 5] # 5--10;; - : int list = [5; 6; 7; 8; 9; 10] Alternatively, the comprehensions syntax extension (which gives the syntax [i .. j] for the above) is likely to be included in a future release of the "community version" of OCaml, so that may become idiomatic. I don't recommend you start playing with syntax extensions if you are new to the language, though.
How do I merge two python iterators?
I have two iterators, a list and an itertools.count object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two: >>> import itertools >>> c = itertools.count(1) >>> items = ['foo', 'bar'] >>> merged = imerge(items, c) # the mythical "imerge" >>> merged.next() 'foo' >>> merged.next() 1 >>> merged.next() 'bar' >>> merged.next() 2 >>> merged.next() Traceback (most recent call last): ... StopIteration What is the simplest, most concise way to do this?
A generator will solve your problem nicely. def imerge(a, b): for i, j in itertools.izip(a,b): yield i yield j
Which Eclipse package to download for pydev?
I'm getting started with python, eclipse and pydev. Which Eclipse package should I choose? Nothing on the eclipse homepage tells me what to choose and python documentation assumes I have eclipse installed. Does which package I choose matter?
If you just plan on doing Python dev, I'd just go with Platform Runtime Binary. After that, I'd follow the instructions http://pydev.org/download.html and http://pydev.org/manual_101_root.html to install PyDev. I use the same setup for Python development. I also have the RadRails plugin for Ruby on Rails development.
What are "first class" objects?
When are objects or something else said to be "first class" in a given programming language, and why? In what do they differ from languages where they are not? EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?
In short, it means there are no restrictions on the object's use. It's the same as any other object. A first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have. Depending on the language, this can imply: being expressible as an anonymous literal value being storable in variables being storable in data structures having an intrinsic identity (independent of any given name) being comparable for equality with other entities being passable as a parameter to a procedure/function being returnable as the result of a procedure/function being constructible at runtime being printable being readable being transmissible among distributed processes being storable outside running processes Source. In C++ functions themselves are not first class objects, however: You can override the '()' operator making it possible to have an object function, which is first class. Function pointers are first class. boost bind, lambda and function do offer first class functions In C++, classes are not first class objects but instances of those classes are. In Python both the classes and the objects are first class objects. (See this answer for more details about classes as objects). Here is an example of Javascript first class functions: // f: function that takes a number and returns a number // deltaX: small positive number // returns a function that is an approximate derivative of f function makeDerivative( f, deltaX ) { var deriv = function(x) { return ( f(x + deltaX) - f(x) )/ deltaX; } return deriv; } var cos = makeDerivative( Math.sin, 0.000001); // cos(0) ~> 1 // cos(pi/2) ~> 0 Source. Entities that are not first class objects are referred to as second-class objects. Functions in C++ are second class because they can't be dynamically created. Regarding the edit: EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"? The term object can be used loosely and doesn't imply being first class. And it would probably make more sense to call the whole concept 'first class entities'. But in Python they do aim to make everything first class. I believe the intent of the person who made your statement meant first class.
Running Django with FastCGI or with mod_python
which would you recommend? which is faster, reliable? apache mod_python or nginx/lighttpd FastCGI?
I've done both, and Apache/mod_python tended to be easier to work with and more stable. But these days I've jumped over to Apache/mod_wsgi, which is everything I've ever wanted and more: Easy management of daemon processes. As a result, much better process isolation (running multiple sites in the same Apache config with mod_python almost always ends in trouble -- environment variables and C extensions leak across sites when you do that). Easy code reloads (set it up right and you can just touch the .wsgi file to reload instead of restarting Apache). More predictable resource usage. With mod_python, a given Apache child process' memory use can jump around a lot. With mod_wsgi it's pretty stable: once everything's loaded, you know that's how much memory it'll use.
How do I get the name of a function or method from within a Python function or method?
I feel like I should know this, but I haven't been able to figure it out... I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.
This seems to be the simplest way using module inspect: import inspect def somefunc(a,b,c): print "My name is: %s" % inspect.stack()[0][3] You could generalise this with: def funcname(): return inspect.stack()[1][3] def somefunc(a,b,c): print "My name is: %s" % funcname() Credit to Stefaan Lippens which was found via google.
How do I draw text at an angle using python's PIL?
Using Python I want to be able to draw text at different angles using PIL. For example, imagine you were drawing the number around the face of a clock. The number 3 would appear as expected whereas 12 would we drawn rotated counter-clockwise 90 degrees. Therefore, I need to be able to draw many different strings at many different angles.
Draw text into a temporary blank image, rotate that, then paste that onto the original image. You could wrap up the steps in a function. Good luck figuring out the exact coordinates to use - my cold-fogged brain isn't up to it right now. This demo writes yellow text on a slant over an image: # Demo to add rotated text to an image using PIL import Image import ImageFont, ImageDraw, ImageOps im=Image.open("stormy100.jpg") f = ImageFont.load_default() txt=Image.new('L', (500,50)) d = ImageDraw.Draw(txt) d.text( (0, 0), "Someplace Near Boulder", font=f, fill=255) w=txt.rotate(17.5, expand=1) im.paste( ImageOps.colorize(w, (0,0,0), (255,255,84)), (242,60), w)
When is not a good time to use python generators?
This is rather the inverse of What can you use Python generator functions for?: python generators, generator expressions, and the itertools module are some of my favorite features of python these days. They're especially useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files. So when is it not a good time to use a generator, or a generator expression, or an itertools function? When should I prefer zip() over itertools.izip(), or range() over xrange(), or [x for x in foo] over (x for x in foo)? Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking. We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off? I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of list comprehension performance vs. map() and filter(). (alt link)
In general, don't use a generator when you need list operations, like len(), reversed(), and so on. There may also be times when you don't want lazy evaluation (e.g. to do all the calculation up front so you can release a resource). In that case, a list expression might be better.
How can I draw a bezier curve using Python's PIL?
I'm using Python's Imaging Library and I would like to draw some bezier curves. I guess I could calculate pixel by pixel but I'm hoping there is something simpler.
def make_bezier(xys): # xys should be a sequence of 2-tuples (Bezier control points) n = len(xys) combinations = pascal_row(n-1) def bezier(ts): # This uses the generalized formula for bezier curves # http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization result = [] for t in ts: tpowers = (t**i for i in range(n)) upowers = reversed([(1-t)**i for i in range(n)]) coefs = [c*a*b for c, a, b in zip(combinations, tpowers, upowers)] result.append( tuple(sum([coef*p for coef, p in zip(coefs, ps)]) for ps in zip(*xys))) return result return bezier def pascal_row(n): # This returns the nth row of Pascal's Triangle result = [1] x, numerator = 1, n for denominator in range(1, n//2+1): # print(numerator,denominator,x) x *= numerator x /= denominator result.append(x) numerator -= 1 if n&1 == 0: # n is even result.extend(reversed(result[:-1])) else: result.extend(reversed(result)) return result This, for example, draws a heart: from PILL import Image from PIL import ImageDraw if __name__ == '__main__': im = Image.new('RGBA', (100, 100), (0, 0, 0, 0)) draw = ImageDraw.Draw(im) ts = [t/100.0 for t in range(101)] xys = [(50, 100), (80, 80), (100, 50)] bezier = make_bezier(xys) points = bezier(ts) xys = [(100, 50), (100, 0), (50, 0), (50, 35)] bezier = make_bezier(xys) points.extend(bezier(ts)) xys = [(50, 35), (50, 0), (0, 0), (0, 50)] bezier = make_bezier(xys) points.extend(bezier(ts)) xys = [(0, 50), (20, 80), (50, 100)] bezier = make_bezier(xys) points.extend(bezier(ts)) draw.polygon(points, fill = 'red') im.save('out.png')
How do I add tab completion to the Python shell?
When starting a django application using python manage.py shell, I get an InteractiveConsole shell - I can use tab completion, etc. Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) When just starting a python interpreter using python, it doesn't offer tab completion. Can someone tell me what django is doing to give me an interactive console, or what I need to do to start an interactive console without a django app?
I may have found a way to do it. Create a file .pythonrc # ~/.pythonrc # enable syntax completion try: import readline except ImportError: print("Module readline not available.") else: import rlcompleter readline.parse_and_bind("tab: complete") then in your .bashrc file, add export PYTHONSTARTUP=~/.pythonrc That seems to work.
How can I launch an instance of an application using Python?
I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?
While the Popen answers are reasonable for the general case, I would recommend win32api for this specific case, if you want to do something useful with it: It goes something like this: from win32com.client import Dispatch xl = Dispatch('Excel.Application') wb = xl.Workbooks.Open('C:\\Documents and Settings\\GradeBook.xls') xl.Visible = True # optional: if you want to see the spreadsheet Taken from a mailing list post but there are plenty of examples around.
Retrieving python module path
I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from. How do I retrieve a module's path in python?
import a_module print a_module.__file__ Will actually give you the path to the .pyc file that was loaded, at least on Mac OS X. So I guess you can do import os path = os.path.dirname(amodule.__file__) You can also try path = os.path.abspath(amodule.__file__) To get the directory to look for changes.
Python: using a recursive algorithm as a generator
Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequences. Here is an example. Suppose we want to compute all the permutations of a string with a recursive function. The following naive algorithm takes an extra argument 'storage' and appends a permutation to it whenever it finds one: def getPermutations(string, storage, prefix=""): if len(string) == 1: storage.append(prefix + string) # <----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], storage, prefix+string[i]) storage = [] getPermutations("abcd", storage) for permutation in storage: print permutation (Please don't care about inefficiency, this is only an example.) Now I want to turn my function into a generator, i.e. to yield a permutation instead of appending it to the storage list: def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string # <----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], prefix+string[i]) for permutation in getPermutations("abcd"): print permutation This code does not work (the function behaves like an empty generator). Am I missing something? Is there a way to turn the above recursive algorithm into a generator without replacing it with an iterative one?
def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string else: for i in xrange(len(string)): for perm in getPermutations(string[:i] + string[i+1:], prefix+string[i]): yield perm Or without an accumulator: def getPermutations(string): if len(string) == 1: yield string else: for i in xrange(len(string)): for perm in getPermutations(string[:i] + string[i+1:]): yield string[i] + perm
Django: Arbitrary number of unnamed urls.py parameters
I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this: /browse/<name1>/<value1>/<name2>/<value2>/ .... etc .... where 'name' maps to a model attribute and 'value' is the search criteria for that attribute. Each "name" will be treated like a category to return subsets of the model instances where the categories match. Now, this could be handled with GET parameters, but I prefer more readable URLs for both the user's sake and the search engines. These URLs subsets will be embedded on each page that displays this model, so it seems worth the effort to make pretty URLs. Ideally each name/value pair will be passed to the view function as a parameter named name1, name2, etc. However, I don't believe it's possible to defined named patterns via a regex's matched text. Am I wrong there? So, it seems I need to do something like this: urlpatterns = patterns('', url(r'^browse/(?:([\w]+)/([\w]+)/)+$', 'app.views.view', name="model_browse"), ) It seems this should match any sets of two name/value pairs. While it matches it successfully, it only passes the last name/value pair as parameters to the view function. My guess is that each match is overwriting the previous match. Under the guess that the containing (?:...)+ is causing it, I tried a simple repeating pattern instead: urlpatterns = patterns('', url(r'^browse/([\w]+/)+$', 'app.views.view', name="model_browse"), ) ... and got the same problem, but this time *args only includes the last matched pattern. Is this a limitation of Django's url dispatcher, and/or Python's regex support? It seems either of these methods should work. Is there a way to achieve this without hardcoding each possible model attribute in the URL as an optional (.*) pattern?
A possibility that you might consider is matching the entire string of possible values within the url pattern portion and pull out the specific pieces within your view. As an example: urlpatterns = patterns('', url(r'^browse/(?P<match>.+)/$', 'app.views.view', name='model_browse'), ) def view(request, match): pieces = match.split('/') # even indexed pieces are the names, odd are values ... No promises about the regexp I used, but I think you understand what I mean. (Edited to try and fix the regexp.)
Virtualenv on Ubuntu with no site-packages
I've been using virtualenv lately while developing in python. I like the idea of a segregated development environment using the --no-site-packages option, but doing this while developing a PyGTK app can be a bit tricky. The PyGTK modules are installed on Ubuntu by default, and I would like to make a virtualenv (with --no-site-packages) aware of specific modules that are located elsewhere on the system. What's the best way to do this? Or should I just suck it up and drop the --no-site-packages option?
$ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv $ cd myvirtualenv $ source bin/activate $ cd lib/python2.6/ $ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/ $ ln -s /usr/lib/pymodules/python2.6/pygtk.pth $ ln -s /usr/lib/pymodules/python2.6/pygtk.py $ ln -s /usr/lib/pymodules/python2.6/cairo/ $ python >>> import pygtk >>> import gtk
How can I add post-install scripts to easy_install / setuptools / distutils?
I would like to be able to add a hook to my setup.py that will be run post-install (either when easy_install'ing or when doing python setup.py install). In my project, PySmell, I have some support files for Vim and Emacs. When a user installs PySmell the usual way, these files get copied in the actual egg, and the user has to fish them out and place them in his .vim or .emacs directories. What I want is either asking the user, post-installation, where would he like these files copied, or even just a message printing the location of the files and what should he do with them. What is the best way to do this? Thanks My setup.py looks like so: #!/usr/bin/env python # -*- coding: UTF-8 -*- from setuptools import setup version = __import__('pysmell.pysmell').pysmell.__version__ setup( name='pysmell', version = version, description = 'An autocompletion library for Python', author = 'Orestis Markou', author_email = 'orestis@orestis.gr', packages = ['pysmell'], entry_points = { 'console_scripts': [ 'pysmell = pysmell.pysmell:main' ] }, data_files = [ ('vim', ['pysmell.vim']), ('emacs', ['pysmell.el']), ], include_package_data = True, keywords = 'vim autocomplete', url = 'http://code.google.com/p/pysmell', long_description = """\ PySmell is a python IDE completion helper. It tries to statically analyze Python source code, without executing it, and generates information about a project's structure that IDE tools can use. The first target is Vim, because that's what I'm using and because its completion mechanism is very straightforward, but it's not limited to it. """, classifiers = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Utilities', 'Topic :: Text Editors', ] ) EDIT: Here's a stub which demonstrates the python setup.py install: from setuptools.command.install import install as _install class install(_install): def run(self): _install.run(self) print post_install_message setup( cmdclass={'install': install}, ... No luck with the easy_install route yet.
It depends on how the user installs your package. If the user actually runs "setup.py install", it's fairly easy: Just add another subcommand to the install command (say, install_vim), whose run() method will copy the files you want in the places where you want them. You can add your subcommand to install.sub_commands, and pass the command into setup(). If you want a post-install script in a binary, it depends on the type of binary you are creating. For example, bdist_rpm, bdist_wininst, and bdist_msi have support for post-install scripts, because the underlying packing formats support post-install scripts. bdist_egg doesn't support a post-install mechanism by design: http://bugs.python.org/setuptools/issue41
Lua as a general-purpose scripting language?
When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW". Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl? Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example: Renaming a bunch of files Download some files from the web Webscraping Is it the lack of the standard library?
Lua is a cool language, light-weight and extremely fast! But the point is: Is performance so important for those tasks you mentioned? Renaming a bunch of files Download some files from the web Webscraping You write those programs once, and run them once, too maybe. Why do you care about performance so much for a run-once program? For example: Cost 3 hours to write a C/C++ program, to handle data once, the program will take 1 hour to run. Cost 30 Minute to write a Python program to handle data once, the program will take 10 hours to run. If you choose the first, you save the time to run the program, but you cost your time to develop the program. On the other hand, if you choose the second, you waste time to run the program, but you can do other things when the program is running. How about play World of Warcraft, kill monsters with your warlock? Eat my D.O.T! :P That's it! Although Lua is not so difficult to write, everything about Lua is designed to be efficient.And what's more, there are little modules for Lua, but there are so many modules for Python. You don't want to port a C library for Lua just for a run-once program, do you? Instead, choose Python and use those module to achieve your task easily might be a better idea. FYI: Actually, I have tried to use Lua to do webscraping, but finally, I realized I do not have to care so much about language performance. The bottleneck of webscraping is not on the performance of the language. The bottleneck is on network I/O, HTML parsing and multitasking. All I have to do is make sure the program works and find the bottleneck. Finally, I chose Python rather than Lua. There is so many excellent Python modules; I have no reason to build my own. According to my experience about webscraping, I chose Twisted for network I/O and lxml for html parsing as the backend of my webscraping program. I have wrote an article for an introduction to this technology. The best choice to grab data from websites: Python + Twisted + lxml Hope this is helpful.
Python Regex - How to Get Positions of Matches
How can I get the start and end positions of all matches using the re module? For example given the pattern r'[a-z]' and the string 'a1b2c3d4' I'd want to get the positions where it finds each letter (ideally I'd like to get the text of the match back too).
import re p = re.compile("[a-z]") for m in p.finditer('a1b2c3d4'): print m.start(), m.group()
How to scp in python?
What's the most pythonic way to scp a file in Python? The only route I'm aware of is os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted's conch, but I'd prefer to avoid implementing scp myself via low-level ssh modules. I'm aware of paramiko, a Python module that supports ssh and sftp; but it doesn't support scp. Background: I'm connecting to a router which doesn't support sftp but does support ssh/scp, so sftp isn't an option. EDIT: This is a duplicate of http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh. However, that question doesn't give an scp-specific answer that deals with keys from within python. I'm hoping for a way to run code kind of like import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename')
Try the module paramiko_scp. It's very easy to use. See the following example: def createSSHClient(server, port, user, password): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(server, port, user, password) return client ssh = createSSHClient(server, port, user, password) scp = SCPClient(ssh.get_transport()) Then call scp.get() or scp.put() to do scp operations. (SCPClient code)
Truncate a string without ending in the middle of a word
I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word. For example: Original: "This is really awesome." "Dumb" truncate: "This is real..." "Smart" truncate: "This is really..." I'm looking for a way to accomplish the "smart" truncate from above.
I actually wrote a solution for this on a recent project of mine. I've compressed the majority of it down to be a little smaller. def smart_truncate(content, length=100, suffix='...'): if len(content) <= length: return content else: return ' '.join(content[:length+1].split(' ')[0:-1]) + suffix What happens is the if-statement checks if your content is already less than the cutoff point. If it's not, it truncates to the desired length, splits on the space, removes the last element (so that you don't cut off a word), and then joins it back together (while tacking on the '...').
How to get a function name as a string in Python?
In Python, how do I get a function name as a string without calling the function? def my_function(): pass print get_function_name_as_string(my_function) # my_function is not in quotes should output "my_function". Is this available in python? If not, any idea how to write get_function_name_as_string in Python?
my_function.__name__ Using __name__ is the preferred method as it applies uniformly. Unlike func_name, it works on built-in functions as well: >>> import time >>> time.time.func_name Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: 'builtin_function_or_method' object has no attribute 'func_name' >>> time.time.__name__ 'time' Also the double underscores indicate to the reader this is a special attribute. As a bonus, classes and modules have a __name__ attribute too, so you only have remember one special name.
Possible Google Riddle?
My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying. Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help. I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses. I hope someone knows better. #This code interprets the google t-shirt as a binary code, each box 4 bits. # I try every permutation of counting the bits and then try to interpret these # interpretations as letters, or hex numbers, or ip addresses. # I need more interpretations, maybe one will find a pattern import string #these represent the boxes binary codes from left to right top to bottom boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001'] #changing the ordering permutations = ["1234", "1243", "1324", "1342", "1423", "1432", "2134", "2143", "2314", "2341", "2413", "2431", "3124", "3142", "3214", "3241", "3412", "3421", "4123", "4132", "4213", "4231","4312", "4321"] #alphabet hashing where 0 = a alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d', '0100':'e', '0101':'f', '0110':'g', '0111':'h', '1000':'i', '1001':'j', '1010':'k', '1011':'l', '1100':'m', '1101':'n', '1110':'o', '1111':'p'} #alphabet hasing where 1 = a alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c', '0100':'d', '0101':'e', '0110':'f', '0111':'g', '1000':'h', '1001':'i', '1010':'j', '1011':'k', '1100':'l', '1101':'m', '1110':'n', '1111':'o'} hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3', '0100':'4', '0101':'5', '0110':'6', '0111':'7', '1000':'8', '1001':'9', '1010':'a', '1011':'b', '1100':'c', '1101':'d', '1110':'e', '1111':'f'} #code to convert from a string of ones and zeros(binary) to decimal number def bin_to_dec(bin_string): l = len(bin_string) answer = 0 for index in range(l): answer += int(bin_string[l - index - 1]) * (2**index) return answer #code to try and ping ip addresses def ping(ipaddress): #ping the network addresses import subprocess # execute the code and pipe the result to a string, wait 5 seconds test = "ping -t 5 " + ipaddress process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE) # give it time to respond process.wait() # read the result to a string result_str = process.stdout.read() #For now, need to manually check if the ping worked, fix later print result_str #now iterate over the permuation and then the boxes to produce the codes for permute in permutations: box_codes = [] for box in boxes: temp_code = "" for index in permute: temp_code += box[int(index) - 1] box_codes.append(temp_code) #now manipulate the codes using leter translation, network, whatever #binary print string.join(box_codes, "") #alphabet1 print string.join( map(lambda x: alphabet1[x], box_codes), "") #alphabet2 print string.join( map(lambda x: alphabet2[x], box_codes), "") #hex print string.join( map(lambda x: hex[x], box_codes), "") #ipaddress, call ping and see who is reachable ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2]) ip = "" for code in ipcodes: bin = bin_to_dec(code[0] + code[1]) ip += repr(bin) + "." print ip[:-1] #ping(ip[:-1]) print print t-shirt.
I emailed the Website Optimizer Team, and they said "There's no secret code, unless you find one. :)"
How can I use a DLL file from Python?
What is the easiest way to use a DLL file from within Python? Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.
For ease of use, ctypes is the way to go. The following example of ctypes is from actual code I've written (in Python 2.5). This has been, by far, the easiest way I've found for doing what you ask. import ctypes # Load DLL into memory. hllDll = ctypes.WinDLL ("c:\\PComm\\ehlapi32.dll") # Set up prototype and parameters for the desired function call. # HLLAPI hllApiProto = ctypes.WINFUNCTYPE ( ctypes.c_int, # Return type. ctypes.c_void_p, # Parameters 1 ... ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p) # ... thru 4. hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0), # Actually map the call ("HLLAPI(...)") to a Python name. hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams) # This is how you can actually call the DLL function. # Set up the variables and call the Python name with them. p1 = ctypes.c_int (1) p2 = ctypes.c_char_p (sessionVar) p3 = ctypes.c_int (1) p4 = ctypes.c_int (0) hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4)) The ctypes stuff has all the C-type data types (int, char, short, void*, and so on) and can pass by value or reference. It can also return specific data types although my example doesn't do that (the HLL API returns values by modifying a variable passed by reference). In terms of the specific example shown above, IBM's EHLLAPI is a fairly consistent interface. All calls pass four void pointers (EHLLAPI sends the return code back through the fourth parameter, a pointer to an int so, while I specify int as the return type, I can safely ignore it) as per IBM's documentation here. In other words, the C variant of the function would be: int hllApi (void *p1, void *p2, void *p3, void *p4) This makes for a single, simple ctypes function able to do anything the EHLLAPI library provides, but it's likely that other libraries will need a separate ctypes function set up per library function. The return value from WINFUNCTYPE is a function prototype but you still have to set up more parameter information (over and above the types). Each tuple in hllApiParams has a parameter "direction" (1 = input, 2 = output and so on), a parameter name and a default value - see the ctypes doco for details Once you have the prototype and parameter information, you can create a Python "callable" hllApi with which to call the function. You simply create the needed variable (p1 through p4 in my case) and call the function with them.
append vs. extend
What's the difference between the list methods append() and extend()?
append: Appends object at end. x = [1, 2, 3] x.append([4, 5]) print (x) gives you: [1, 2, 3, [4, 5]] extend: Extends list by appending elements from the iterable. x = [1, 2, 3] x.extend([4, 5]) print (x) gives you: [1, 2, 3, 4, 5]
What Python bindings are there for CVS or SVN?
I once did a cursory search and found no good CVS bindings for Python. I wanted to be able to write helper scripts to do some fine-grained manipulation of the repository and projects in it. I had to resort to using popen and checking stdout and stderr and then parsing those. It was messy and error-prone. Are there any good quality modules for CVS integration for Python? Which module do you prefer and why? While I am at it, is there a good Subversion integration module for Python? My understanding is that Subversion has a great API for such things.
For cvs, pyCVS may be worth a look. For svn, there is pysvn, which is pretty good.
In Python, is there a concise way of comparing whether the contents of two text files are the same?
I don't care what the differences are. I just want to know whether the contents are different.
The low level way: from __future__ import with_statement with open(filename1) as f1: with open(filename2) as f2: if f1.read() == f2.read(): ... The high level way: import filecmp if filecmp.cmp(filename1, filename2, shallow=False): ...
Converting datetime to POSIX time
How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way.
import time, datetime d = datetime.datetime.now() print time.mktime(d.timetuple())
How do I keep Python print from adding newlines or spaces?
In python, if I say print 'h' I get the letter h and a newline. If I say print 'h', I get the letter h and no newline. If I say print 'h', print 'm', I get the letter h, a space, and the letter m. How can I prevent Python from printing the space? The print statements are different iterations of the same loop so I can't just use the + operator.
Just a comment. In Python 3, you will use print('h', end='') to suppress the endline terminator, and print('a', 'b', 'c', sep='') to suppress the whitespace separator between items.
Browser-based application or stand-alone GUI app?
I'm sure this has been asked before, but I can't find it. What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework? I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff. The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using Karrigell for the web framework if I go browser-based. Edit For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.
The obvious advantages to browser-based: you can present the same UI regardless of platform you can upgrade the application easily, and all users have the same version of the app running you know the environment that your application will be running in (the server hardware/OS) which makes for easier testing and support compared to the multitude of operating system/hardware configurations that a GUI app will be installed on. And for GUI based: some applications (e.g.: image editing) arguably work better in a native GUI application doesn't require network access Also see my comments on this question: Cross-platform GUIs are an age-old problem. Qt, GTK, wxWindows, Java AWT, Java Swing, XUL -- they all suffer from the same problem: the resulting GUI doesn't look native on every platform. Worse still, every platform has a slightly different look and feel, so even if you were somehow able to get a toolkit that looked native on every platform, you'd have to somehow code your app to feel native on each platform. It comes down to a decision: do you want to minimise development effort and have a GUI that doesn't look and feel quite right on each platform, or do you want to maximise the user experience? If you choose the second option, you'll need to develop a common backend and a custom UI for each platform. [edit: or use a web application.] Another thought I just had: you also need to consider the kind of data that your application manipulates and where it is stored, and how the users will feel about that. People are obviously okay having their facebook profile data stored on a webserver, but they might feel differently if you're writing a finance application like MYOB and you want to store all their personal financial details on your server. You might be able to get that to work, but it would require a lot of effort to implement the required security and to assure the userbase that their data is safe. In that situation you might decide that the overall effort is lower if you go with a native GUI app.
Which exception should I raise on bad/illegal argument combinations in Python?
I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so: def import_to_orm(name, save=False, recurse=False): """ :param name: Name of some external entity to import. :param save: Save the ORM object before returning. :param recurse: Attempt to import associated objects as well. Because you need the original object to have a key to relate to, save must be `True` for recurse to be `True`. :raise BadValueError: If `recurse and not save`. :return: The ORM object. """ pass The only annoyance with this is that every package has its own, usually slightly differing BadValueError. I know that in Java there exists java.lang.IllegalArgumentException -- is it well understood that everybody will be creating their own BadValueErrors in Python or is there another, preferred method?
I would just raise ValueError, unless you need a more specific exception.. def import_to_orm(name, save=False, recurse=False): if recurse and not save: raise ValueError("save must be True if recurse is True") There's really no point in doing class BadValueError(ValueError):pass - your custom class is identical in use to ValueError, so why not use that?
Python packages and egg-info directories
Can someone explain how egg-info directories are tied to their respective modules? For example, I have the following: /usr/local/lib/python2.5/site-packages/quodlibet/ /usr/local/lib/python2.5/site-packages/quodlibet-2.0.egg-info/ I'm assuming the egg-info directory is to make the corresponding module visible to setuptools (easy_install), right? If so, how does setuptools tie the egg-info directory to the module directory? Assuming that I'm on the right track, and for the sake of example... If I wanted to make an existing package of mine visible to setuptools, could I just symlink the module directory and the egg-info directory to the site-packages directory? I would have just tried this myself, but I'm not sure how to test if the package is visible to setuptools. Bonus points if you can also tell me how to test this :) The main reason I'm trying to understand all this is because I would like to symlink some of my modules into site-packages so that I can make changes to them and have the changes visible to the scripts that use them without having to reinstall the egg from PyPI after each change.
The .egg-info directories get only created if --single-version-externally-managed was used to install the egg. "Normally", installing an egg would create a single directory (or zip file), containing both the code and the metadata. pkg_resources (which is the library that reads the metadata) has a function require which can be used to request a specific version of the package. For "old-style", regular imports, easy_install hacks a .pth file to get the egg directory onto sys.path. For --single-version-externally-managed, this hacking is not necessary, because there will only be a single version installed (by the system's pacakging infrastructure, e.g. rpm or dpkg). The egg-info is still included, for applications that use require (or any of the other pkg_resources binding mechanisms). If you want to install a package by hard-linking, I recommend to use "setup.py develop". This is a command from setuptools which doesn't actually install the egg, but makes it available site-wide. To do so, it creates an egg-link file so that pkg_resources can find it, and it manipulates a .pth file, so that regular import can find it.
Download image file from the HTML page source using python?
I am writing a scraper that downloads all the image files from a HTML page and saves them to a specific folder. all the images are the part of the HTML page.
Here is some code to download all the images from the supplied URL, and save them in the specified output folder. You can modify it to your own needs. """ dumpimages.py Downloads all the images on the supplied URL, and saves them to the specified output file ("/test/" by default) Usage: python dumpimages.py http://example.com/ [output] """ from BeautifulSoup import BeautifulSoup as bs import urlparse from urllib2 import urlopen from urllib import urlretrieve import os import sys def main(url, out_folder="/test/"): """Downloads all the images at 'url' to /test/""" soup = bs(urlopen(url)) parsed = list(urlparse.urlparse(url)) for image in soup.findAll("img"): print "Image: %(src)s" % image filename = image["src"].split("/")[-1] parsed[2] = image["src"] outpath = os.path.join(out_folder, filename) if image["src"].lower().startswith("http"): urlretrieve(image["src"], outpath) else: urlretrieve(urlparse.urlunparse(parsed), outpath) def _usage(): print "usage: python dumpimages.py http://example.com [outpath]" if __name__ == "__main__": url = sys.argv[-1] out_folder = "/test/" if not url.lower().startswith("http"): out_folder = sys.argv[-1] url = sys.argv[-2] if not url.lower().startswith("http"): _usage() sys.exit(-1) main(url, out_folder) Edit: You can specify the output folder now.
Why are Exceptions iterable?
I have been bitten by something unexpected recently. I wanted to make something like that: try : thing.merge(iterable) # this is an iterable so I add it to the list except TypeError : thing.append(iterable) # this is not iterable, so I add it Well, It was working fine until I passed an object inheriting from Exception which was supposed to be added. Unfortunetly, an Exception is iterable. The following code does not raise any TypeError: for x in Exception() : print 1 Does anybody know why?
Note that what is happening is not related to any kind of implicit string conversion etc, but because the Exception class implements __getitem__(), and uses it to return the values in the args tuple (ex.args). You can see this by the fact that you get the whole string as your first and only item in the iteration, rather than the character-by-character result you'd get if you iterate over the string. This surprised me too, but thinking about it, I'm guessing it is for backwards compatability reasons. Python used to (pre-1.5) lack the current class hierarchy of exceptions. Instead, strings were thrown, with (usually) a tuple argument for any details that should be passed to the handling block. ie: try: raise "something failed", (42, "some other details") except "something failed", args: errCode, msg = args print "something failed. error code %d: %s" % (errCode, msg) It looks like this behavior was put in to avoid breaking pre-1.5 code expecting a tuple of arguments, rather than a non-iterable exception object. There are a couple of examples of this with IOError in the Fatal Breakage section of the above link String exceptions have been depecated for a while, and are going away in Python 3. I've now checked how Python 3 handles exception objects, and it looks like they are no longer iterable there: >>> list(Exception("test")) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'Exception' object is not iterable [Edit] Checked python3's behaviour
Django models - how to filter number of ForeignKey objects
I have a models A and B, that are like this: class A(models.Model): title = models.CharField(max_length=20) (...) class B(models.Model): date = models.DateTimeField(auto_now_add=True) (...) a = models.ForeignKey(A) Now I have some A and B objects, and I'd like to get a query that selects all A objects that have less then 2 B pointing at them. A is something like a pool thing, and users (the B) join pool. if there's only 1 or 0 joined, the pool shouldn't be displayed at all. Is it possible with such model design? Or should I modify that a bit?
The question and selected answer are from 2008 and since then this functionality has been integrated into the django framework. Since this is a top google hit for "django filter foreign key count" I'd like to add an easier solution with a recent django version using Aggregation. from django.db.models import Count cats = A.objects.annotate(num_b=Count('b')).filter(num_b__lt=2) In my case I had to take this concept a step further. My "B" object had a boolean field called is_available, and I only wanted to return A objects who had more than 0 B objects with is_available set to True. A.objects.filter(B__is_available=True).annotate(num_b=Count('b')).filter(num_b__gt=0).order_by('-num_items')
Credit card payments and notifications on the Google App Engine
I ported gchecky to the google app engine. you can try it here It implements both level 1 (cart submission) and level 2 (notifications from google checkout). Is there any other payment option that works on the google app engine (paypal for example) and supports level 2 (notifications)?
I think you can have a look into the official toolkit from PayPal's X Platform http://code.google.com/p/paypalx-gae-toolkit/
Splitting a person's name into forename and surname
ok so basically I am asking the question of their name I want this to be one input rather than Forename and Surname. Now is there any way of splitting this name? and taking just the last word from the "Sentence" e.g. name = "Thomas Winter" print name.split() and what would be output is just "Winter"
You'll find that your key problem with this approach isn't a technical one, but a human one - different people write their names in different ways. In fact, the terminology of "forename" and "surname" is itself flawed. While many blended families use a hyphenated family name, such as Smith-Jones, there are some who just use both names separately, "Smith Jones" where both names are the family name. Many european family names have multiple parts, such as "de Vere" and "van den Neiulaar". Sometimes these extras have important family history - for example, a prefix awarded by a king hundreds of years ago. Side issue: I've capitalised these correctly for the people I'm referencing - "de" and "van den" don't get captial letters for some families, but do for others. Conversely, many Asian cultures put the family name first, because the family is considered more important than the individual. Last point - some people place great store in being "Junior" or "Senior" or "III" - and your code shouldn't treat those as the family name. Also noting that there are a fair number of people who use a name that isn't the one bestowed by their parents, I've used the following scheme with some success: Full Name (as normally written for addressing mail); Family Name; Known As (the name commonly used in conversation). e.g: Full Name: William Gates III; Family Name: Gates; Known As: Bill Full Name: Soong Li; Family Name: Soong; Known As: Lisa
Hashtable/dictionary/map lookup with regular expressions
I'm trying to figure out if there's a reasonably efficient way to perform a lookup in a dictionary (or a hash, or a map, or whatever your favorite language calls it) where the keys are regular expressions and strings are looked up against the set of keys. For example (in Python syntax): >>> regex_dict = { re.compile(r'foo.') : 12, re.compile(r'^FileN.*$') : 35 } >>> regex_dict['food'] 12 >>> regex_dict['foot in my mouth'] 12 >>> regex_dict['FileNotFoundException: file.x does not exist'] 35 (Obviously the above example won't work as written in Python, but that's the sort of thing I'd like to be able to do.) I can think of a naive way to implement this, in which I iterate over all of the keys in the dictionary and try to match the passed in string against them, but then I lose the O(1) lookup time of a hash map and instead have O(n), where n is the number of keys in my dictionary. This is potentially a big deal, as I expect this dictionary to grow very large, and I will need to search it over and over again (actually I'll need to iterate over it for every line I read in a text file, and the files can be hundreds of megabytes in size). Is there a way to accomplish this, without resorting to O(n) efficiency? Alternatively, if you know of a way to accomplish this sort of a lookup in a database, that would be great, too. (Any programming language is fine -- I'm using Python, but I'm more interested in the data structures and algorithms here.) Someone pointed out that more than one match is possible, and that's absolutely correct. Ideally in this situation I'd like to return a list or tuple containing all of the matches. I'd settle for the first match, though. I can't see O(1) being possible in that scenario; I'd settle for anything less than O(n), though. Also, the underlying data structure could be anything, but the basic behavior I'd like is what I've written above: lookup a string, and return the value(s) that match the regular expression keys.
This is not possible to do with a regular hash table in any language. You'll either have to iterate through the entire keyset, attempting to match the key to your regex, or use a different data structure. You should choose a data structure that is appropriate to the problem you're trying to solve. If you have to match against any arbitrary regular expression, I don't know of a good solution. If the class of regular expressions you'll be using is more restrictive, you might be able to use a data structure such as a trie or suffix tree.
Most efficient way to search the last x lines of a file in python
I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than: s = "foo" last_bit = fileObj.readlines()[-10:] for line in last_bit: if line == s: print "FOUND"
Here's an answer like MizardX's, but without its apparent problem of taking quadratic time in the worst case from rescanning the working string repeatedly for newlines as chunks are added. Compared to the activestate solution (which also seems to be quadratic), this doesn't blow up given an empty file, and does one seek per block read instead of two. Compared to spawning 'tail', this is self-contained. (But 'tail' is best if you have it.) Compared to grabbing a few kB off the end and hoping it's enough, this works for any line length. import os def reversed_lines(file): "Generate the lines of file in reverse order." part = '' for block in reversed_blocks(file): for c in reversed(block): if c == '\n' and part: yield part[::-1] part = '' part += c if part: yield part[::-1] def reversed_blocks(file, blocksize=4096): "Generate blocks of file's contents in reverse order." file.seek(0, os.SEEK_END) here = file.tell() while 0 < here: delta = min(blocksize, here) here -= delta file.seek(here, os.SEEK_SET) yield file.read(delta) To use it as requested: from itertools import islice def check_last_10_lines(file, key): for line in islice(reversed_lines(file), 10): if line.rstrip('\n') == key: print 'FOUND' break Edit: changed map() to itertools.imap() in head(). Edit 2: simplified reversed_blocks(). Edit 3: avoid rescanning tail for newlines. Edit 4: rewrote reversed_lines() because str.splitlines() ignores a final '\n', as BrianB noticed (thanks). Note that in very old Python versions the string concatenation in a loop here will take quadratic time. CPython from at least the last few years avoids this problem automatically.
Play audio with Python
How can I play audio (it would be like a 1 second sound) from a Python script? It would be best if it was platform independent, but firstly it needs to work on a Mac. I know I could just execute the afplay file.mp3 command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.
Your best bet is probably to use pygame/SDL. It's an external library, but it has great support across platforms. pygame.mixer.init() pygame.mixer.music.load("file.mp3") pygame.mixer.music.play() You can find more specific documentation about the audio mixer support in the pygame.mixer.music documentation
How do I protect Python code?
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
"Is there a good way to handle this problem?" No. Nothing can be protected against reverse engineering. Even the firmware on DVD machines has been reverse engineered and AACS Encryption key exposed. And that's in spite of the DMCA making that a criminal offense. Since no technical method can stop your customers from reading your code, you have to apply ordinary commercial methods. Licenses. Contracts. Terms and Conditions. This still works even when people can read the code. Note that some of your Python-based components may require that you pay fees before you sell software using those components. Also, some open-source licenses prohibit you from concealing the source or origins of that component. Offer significant value. If your stuff is so good -- at a price that is hard to refuse -- there's no incentive to waste time and money reverse engineering anything. Reverse engineering is expensive. Make your product slightly less expensive. Offer upgrades and enhancements that make any reverse engineering a bad idea. When the next release breaks their reverse engineering, there's no point. This can be carried to absurd extremes, but you should offer new features that make the next release more valuable than reverse engineering. Offer customization at rates so attractive that they'd rather pay you do build and support the enhancements. Use a license key which expires. This is cruel, and will give you a bad reputation, but it certainly makes your software stop working. Offer it as a web service. SaaS involves no downloads to customers.
Converting a List of Tuples into a Dict in Python
I have a list of tuples like this: [ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ] I want to iterate through this keying by the first item, so for example I could print something like this: a 1 2 3 b 1 2 c 1 How would I go about doing this without keeping an item to track whether the first item is the same as I loop round the tuples. This feels rather messy (plus I have to sort the list to start with)... Thanks, Dan
l = [ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ] d = {} for x, y in l: d.setdefault(x, []).append(y) print d produces: {'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}
Is it possible to change the Environment of a parent process in python?
In Linux When I invoke python from the shell it replicates its environment, and starts the python process. Therefore if I do something like the following: import os os.environ["FOO"] = "A_Value" When the python process returns, FOO, assuming it was undefined originally, will still be undefined. Is there a way for the python process (or any child process) to modify the environment of its parent process? I know you typically solve this problem using something like source script_name.sh But this conflicts with other requirements I have.
It's not possible, for any child process, to change the environment of the parent process. The best you can do is to output shell statements to stdout that you then source, or write it to a file that you source in the parent.
Creating a python win32 service
I am currently trying to create a win32 service using pywin32. My main point of reference has been this tutorial: http://code.activestate.com/recipes/551780/ What i don't understand is the initialization process, since the Daemon is never initialized directly by Daemon(), instead from my understanding its initialized by the following: mydaemon = Daemon __svc_regClass__(mydaemon, "foo", "foo display", "foo description") __svc_install__(mydaemon) Where svc_install, handles the initalization, by calling Daemon.init() and passing some arguments to it. But how can i initialize the daemon object, without initalizing the service? I want to do a few things, before i init the service. Does anyone have any ideas? class Daemon(win32serviceutil.ServiceFramework): def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcDoRun(self): self.run() def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def start(self): pass def stop(self): self.SvcStop() def run(self): pass def __svc_install__(cls): win32api.SetConsoleCtrlHandler(lambda x: True, True) try: win32serviceutil.InstallService( cls._svc_reg_class_, cls._svc_name_, cls._svc_display_name_, startType = win32service.SERVICE_AUTO_START ) print "Installed" except Exception, err: print str(err) def __svc_regClass__(cls, name, display_name, description): #Bind the values to the service name cls._svc_name_ = name cls._svc_display_name_ = display_name cls._svc_description_ = description try: module_path = sys.modules[cls.__module__].__file__ except AttributeError: from sys import executable module_path = executable module_file = os.path.splitext(os.path.abspath(module_path))[0] cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__)
I just create a simple "how to" where the program is in one module and the service is in another place, it uses py2exe to create the win32 service, which I believe is the best you can do for your users that don't want to mess with the python interpreter or other dependencies. You can check my tutorial here: Create win32 services using Python and py2exe
Merging/adding lists in Python
I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators. Example - I have the following list: array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] I want to have result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9] So far what I've come up with is: def add_list(array): number_items = len(array[0]) result = [0] * number_items for index in range(number_items): for line in array: result[index] += line[index] return result But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?
[sum(a) for a in zip(*array)]
What is a Ruby equivalent for Python's "zip" builtin?
Is there any Ruby equivalent for Python's builtin zip function? If not, what is a concise way of doing the same thing? A bit of context: this came up when I was trying to find a clean way of doing a check involving two arrays. If I had zip, I could have written something like: zip(a, b).all? {|pair| pair[0] === pair[1]} I'd also accept a clean way of doing this without anything resembling zip (where "clean" means "without an explicit loop").
Ruby has a zip function: [1,2].zip([3,4]) => [[1,3],[2,4]] so your code example is actually: a.zip(b).all? {|pair| pair[0] === pair[1]} or perhaps more succinctly: a.zip(b).all? {|a,b| a === b }
How to fetch more than 1000?
How can I fetch more than 1000 record from data store and put all in one single list to pass to django?
Starting with Version 1.3.6 (released Aug-17-2010) you CAN From the changelog: Results of datastore count() queries and offsets for all datastore queries are no longer capped at 1000.
Why the Global Interpreter Lock?
What is exactly the function of Python's Global Interpreter Lock? Do other languages that are compiled to bytecode employ a similar mechanism?
In general, for any thread safety problem you will need to protect your internal data structures with locks. This can be done with various levels of granularity. You can use fine-grained locking, where every separate structure has its own lock. You can use coarse-grained locking where one lock protects everything (the GIL approach). There are various pros and cons of each method. Fine-grained locking allows greater parallelism - two threads can execute in parallel when they don't share any resources. However there is a much larger administrative overhead. For every line of code, you may need to acquire and release several locks. The coarse grained approach is the opposite. Two threads can't run at the same time, but an individual thread will run faster because its not doing so much bookkeeping. Ultimately it comes down to a tradeoff between single-threaded speed and parallelism. There have been a few attempts to remove the GIL in python, but the extra overhead for single threaded machines was generally too large. Some cases can actually be slower even on multi-processor machines due to lock contention. Do other languages that are compiled to bytecode employ a similar mechanism? It varies, and it probably shouldn't be considered a language property so much as an implementation property. For instance, there are Python implementations such as Jython and IronPython which use the threading approach of their underlying VM, rather than a GIL approach. Additionally, the next version of Ruby looks to be moving towards introducing a GIL.
Best way to strip punctuation from a string in Python
It seems like there should be a simpler way than: import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) Is there?
From an efficiency perspective, you're not going to beat translate() - it's performing raw string operations in C with a lookup table - there's not much that will beat that but writing your own C code. If speed isn't a worry, another option though is: exclude = set(string.punctuation) s = ''.join(ch for ch in s if ch not in exclude) This is faster than s.replace with each char, but won't perform as well as non-pure python approaches such as regexes or string.translate, as you can see from the below timings. For this type of problem, doing it at as low a level as possible pays off. Timing code: import re, string, timeit s = "string. With. Punctuation" exclude = set(string.punctuation) table = string.maketrans("","") regex = re.compile('[%s]' % re.escape(string.punctuation)) def test_set(s): return ''.join(ch for ch in s if ch not in exclude) def test_re(s): # From Vinko's solution, with fix. return regex.sub('', s) def test_trans(s): return s.translate(table, string.punctuation) def test_repl(s): # From S.Lott's solution for c in string.punctuation: s=s.replace(c,"") return s print "sets :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000) print "regex :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000) print "translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000) print "replace :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000) This gives the following results: sets : 19.8566138744 regex : 6.86155414581 translate : 2.12455511093 replace : 28.4436721802
Python: Check if uploaded file is jpg
How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)? This is how far I got by now: Script receives image via HTML Form Post and is processed by the following code ... incomming_image = self.request.get("img") image = db.Blob(incomming_image) ... I found mimetypes.guess_type, but it does not work for me.
If you need more than looking at extension, one way would be to read the JPEG header, and check that it matches valid data. The format for this is: Start Marker | JFIF Marker | Header Length | Identifier 0xff, 0xd8 | 0xff, 0xe0 | 2-bytes | "JFIF\0" so a quick recogniser would be: def is_jpg(filename): data = open(filename,'rb').read(11) if data[:4] != '\xff\xd8\xff\xe0': return False if data[6:] != 'JFIF\0': return False return True However this won't catch any bad data in the body. If you want a more robust check, you could try loading it with PIL. eg: from PIL import Image def is_jpg(filename): try: i=Image.open(filename) return i.format =='JPEG' except IOError: return False
How do I treat an ASCII string as unicode and unescape the escaped characters in it in python?
For example, if I have a unicode string, I can encode it as an ASCII string like so: >>> u'\u003cfoo/\u003e'.encode('ascii') '<foo/>' However, I have e.g. this ASCII string: '\u003foo\u003e' ... that I want to turn into the same ASCII string as in my first example above: '<foo/>'
It took me a while to figure this one out, but this page had the best answer: >>> s = '\u003cfoo/\u003e' >>> s.decode( 'unicode-escape' ) u'<foo/>' >>> s.decode( 'unicode-escape' ).encode( 'ascii' ) '<foo/>' There's also a 'raw-unicode-escape' codec to handle the other way to specify Unicode strings -- check the "Unicode Constructors" section of the linked page for more details (since I'm not that Unicode-saavy). EDIT: See also Python Standard Encodings.
Getting key with maximum value in dictionary?
I have a dictionary: keys are strings, values are integers. Example: stats = {'a':1000, 'b':3000, 'c': 100} I'd like to get 'b' as an answer, since it's the key with a higher value. I did the following, using an intermediate list with reversed key-value tuples: inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] Is that one the better (or even more elegant) approach?
max(stats, key=stats.get)
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
I am running my HTTPServer in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down. The Python documentation states that BaseHTTPServer.HTTPServer is a subclass of SocketServer.TCPServer, which supports a shutdown method, but it is missing in HTTPServer. The whole BaseHTTPServer module has very little documentation :(
I should start by saying that "I probably wouldn't do this myself, but I have in the past". The serve_forever (from SocketServer.py) method looks like this: def serve_forever(self): """Handle one request at a time until doomsday.""" while 1: self.handle_request() You could replace (in subclass) while 1 with while self.should_be_running, and modify that value from a different thread. Something like: def stop_serving_forever(self): """Stop handling requests""" self.should_be_running = 0 # Make a fake request to the server, to really force it to stop. # Otherwise it will just stop on the next request. # (Exercise for the reader.) self.make_a_fake_request_to_myself() Edit: I dug up the actual code I used at the time: class StoppableRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer): stopped = False allow_reuse_address = True def __init__(self, *args, **kw): SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, *args, **kw) self.register_function(lambda: 'OK', 'ping') def serve_forever(self): while not self.stopped: self.handle_request() def force_stop(self): self.server_close() self.stopped = True self.create_dummy_request() def create_dummy_request(self): server = xmlrpclib.Server('http://%s:%s' % self.server_address) server.ping()
Is there a Python library function which attempts to guess the character-encoding of some bytes?
I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwing a UnicodeDecodeError . So, I'm looking for a function that takes a str and optionally some hints and does its darndest to give me back a unicode. I could write one of course, but if such a function exists its author has probably thought a bit deeper about the best way to go about this. I also know that Python's design prefers explicit to implicit and that the standard library is designed to avoid implicit magic in decoding text. I just want to explicitly say "go ahead and guess".
You may be interested in Universal Encoding Detector.
How do I find the location of Python module sources?
How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux? I'm trying to look for the source of the datetime module in particular, but I'm interested in a more general answer as well.
For a pure python module you can find the source by looking at themodule.__file__. The datetime module, however, is written in C, and therefore datetime.__file__ points to a .so file (there is no datetime.__file__ on Windows), and therefore, you can't see the source. If you download a python source tarball and extract it, the modules' code can be found in the Modules subdirectory. For example, if you want to find the datetime code for python 2.6, you can look at Python-2.6/Modules/datetimemodule.c You can also find the latest Mercurial version on the web at https://hg.python.org/cpython/file/tip/Modules/_datetimemodule.c
Tkinter: invoke event in main loop
How do you invoke a tkinter event from a separate object? I'm looking for something like wxWidgets wx.CallAfter. For example, If I create an object, and pass to it my Tk root instance, and then try to call a method of that root window from my object, my app locks up. The best I can come up with is to use the the after method and check the status from my separate object, but that seems wasteful.
To answer your specific question of "How do you invoke a TkInter event from a separate object", use the event_generate command. It allows you to inject events into the event queue of the root window. Combined with Tk's powerful virtual event mechanism it becomes a handy message passing mechanism. For example: from tkinter import * def doFoo(*args): print("Hello, world") root = Tk() root.bind("<<Foo>>", doFoo) # some time later, inject the "<<Foo>>" virtual event at the # tail of the event queue root.event_generate("<<Foo>>", when="tail") Note that the event_generate call will return immediately. It's not clear if that's what you want or not. Generally speaking you don't want an event based program to block waiting for a response to a specific event because it will freeze the GUI. I'm not sure if this solves your problem though; without seeing your code I'm not sure what your real problem is. I can, for example, access methods of root in the constructor of an object where the root is passed in without the app locking up. This tells me there's something else going on in your code. Here's an example of successfully accessing methods on a root window from some other object: from tkinter import * class myClass: def __init__(self, root): print("root background is %s" % root.cget("background")) root = Tk() newObj = myClass(root)
How do I determine all of my IP addresses when I have multiple NICs?
I have multiple Network Interface Cards on my computer, each with its own IP address. When I use gethostbyname(gethostname()) from Python's (built-in) socket module, it will only return one of them. How do I get the others?
Use the netifaces module. Because networking is complex, using netifaces can be a little tricky, but here's how to do what you want: >>> import netifaces >>> netifaces.interfaces() ['lo', 'eth0'] >>> netifaces.ifaddresses('eth0') {17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '00:11:2f:32:63:45'}], 2: [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::211:2fff:fe32:6345%eth0'}]} >>> for interface in netifaces.interfaces(): ... print netifaces.ifaddresses(interface)[netifaces.AF_INET] ... [{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}] [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}] >>> for interface in netifaces.interfaces(): ... for link in netifaces.ifaddresses(interface)[netifaces.AF_INET]: ... print link['addr'] ... 127.0.0.1 10.0.0.2 This can be made a little more readable like this: from netifaces import interfaces, ifaddresses, AF_INET def ip4_addresses(): ip_list = [] for interface in interfaces(): for link in ifaddresses(interface)[AF_INET]: ip_list.append(link['addr']) return ip_list If you want IPv6 addresses, use AF_INET6 instead of AF_INET. If you're wondering why netifaces uses lists and dictionaries all over the place, it's because a single computer can have multiple NICs, and each NIC can have multiple addresses, and each address has its own set of options.
Efficiently updating database using SQLAlchemy ORM
I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy. Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy: db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo = foo + 1') I figured out the SQLAlchemy SQL-builder equivalent: engine = sqlalchemy.create_engine('sqlite:///mydata.sqlitedb') md = sqlalchemy.MetaData(engine) table = sqlalchemy.Table('stuff', md, autoload=True) upd = table.update(values={table.c.foo:table.c.foo+1}) engine.execute(upd) This is slightly slower, but there's not much in it. Here's my best guess for a SQLAlchemy ORM approach: # snip definition of Stuff class made using declarative_base # snip creation of session object for c in session.query(Stuff): c.foo = c.foo + 1 session.flush() session.commit() This does the right thing, but it takes just under fifty times as long as the other two approaches. I presume that's because it has to bring all the data into memory before it can work with it. Is there any way to generate the efficient SQL using SQLAlchemy's ORM? Or using any other python ORM? Or should I just go back to writing the SQL by hand?
SQLAlchemy's ORM is meant to be used together with the SQL layer, not hide it. But you do have to keep one or two things in mind when using the ORM and plain SQL in the same transaction. Basically, from one side, ORM data modifications will only hit the database when you flush the changes from your session. From the other side, SQL data manipulation statements don't affect the objects that are in your session. So if you say for c in session.query(Stuff).all(): c.foo = c.foo+1 session.commit() it will do what it says, go fetch all the objects from the database, modify all the objects and then when it's time to flush the changes to the database, update the rows one by one. Instead you should do this: session.execute(update(stuff_table, values={stuff_table.c.foo: stuff_table.c.foo + 1})) session.commit() This will execute as one query as you would expect, and because atleast the default session configuration expires all data in the session on commit you don't have any stale data issues. In the almost-released 0.5 series you could also use this method for updating: session.query(Stuff).update({Stuff.foo: Stuff.foo + 1}) session.commit() That will basically run the same SQL statement as the previous snippet, but also select the changed rows and expire any stale data in the session. If you know you aren't using any session data after the update you could also add synchronize_session=False to the update statement and get rid of that select.
Django - How to do tuple unpacking in a template 'for' loop
In my views.py, I'm building a list of two-tuples, where the second item in the tuple is another list, like this: [ Product_Type_1, [ product_1, product_2 ], Product_Type_2, [ product_3, product_4 ]] In plain old Python, I could iteration the list like this: for product_type, products in list: print product_type for product in products: print product I can't seem to do the same thing in my Django template: {% for product_type, products in product_list %} print product_type {% for product in products %} print product {% endfor %} {% endfor %} I get this error from Django: Caught an exception while rendering: zip argument #2 must support iteration Of course, there is some HTML markup in the template, not print statements. Is tuple unpacking not supported in the Django template language? Or am I going about this the wrong way? All I am trying to do is display a simple hierarchy of objects - there are several product types, each with several products (in models.py, Product has a foreign key to Product_type, a simple one-to-many relationship). Obviously, I am quite new to Django, so any input would be appreciated.
it would be best if you construct your data like {note the '(' and ')' can be exchanged for '[' and ']' repectively, one being for tuples, one for lists} [ (Product_Type_1, ( product_1, product_2 )), (Product_Type_2, ( product_3, product_4 )) ] and have the template do this: {% for product_type, products in product_type_list %} {{ product_type }} {% for product in products %} {{ product }} {% endfor %} {% endfor %} the way tuples/lists are unpacked in for loops is based on the item returned by the list iterator. each iteration only one item was returned. the first time around the loop, Product_Type_1, the second your list of products...
Linking languages
I asked a question earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. So, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better? My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!
Boost.Python provides an easy way to turn C++ code into Python modules. It's rather mature and works well in my experience. For example, the inevitable Hello World... char const* greet() { return "hello, world"; } can be exposed to Python by writing a Boost.Python wrapper: #include <boost/python.hpp> BOOST_PYTHON_MODULE(hello_ext) { using namespace boost::python; def("greet", greet); } That's it. We're done. We can now build this as a shared library. The resulting DLL is now visible to Python. Here's a sample Python session: >>> import hello_ext >>> print hello.greet() hello, world (example taken from boost.org)
Interactive console using Pydev in Eclipse?
I'm debugging my Python code in Eclipse using the Pydev plugin. I'm able to open a Pydev console and it gives me two options: "Console for currently active editor" and "Python console". However none of them is useful to inspect current variable status after a breakpoint. For example, the code stopped at a breakpoint and I want to inspect an "action" variable using the console. However my variables are not available. How can I do things like "dir(action)", etc? (even if it is not using a console).
This feature is documented here: http://pydev.org/manual_adv_debug_console.html
How should I stress test / load test a client server application?
I develop a client-server style, database based system and I need to devise a way to stress / load test the system. Customers inevitably want to know such things as: • How many clients can a server support? • How many concurrent searches can a server support? • How much data can we store in the database? • Etc. Key to all these questions is response time. We need to be able to measure how response time and performance degrades as new load is introduced so that we could for example, produce some kind of pretty graph we could throw at clients to give them an idea what kind of performance to expect with a given hardware configuration. Right now we just put out fingers in the air and make educated guesses based on what we already know about the system from experience. As the product is put under more demanding conditions, this is proving to be inadequate for our needs going forward though. I've been given the task of devising a method to get such answers in a meaningful way. I realise that this is not a question that anyone can answer definitively but I'm looking for suggestions about how people have gone about doing such work on their own systems. One thing to note is that we have full access to our client API via the Python language (courtesy of SWIG) which is a lot easier to work with than C++ for this kind of work. So there we go, I throw this to the floor: really interested to see what ideas you guys can come up with!
Test 1: Connect and Disconnect clients like mad, to see how well you handle the init and end of sessions, and just how much your server will survive under spikes, also while doing this measure how many clients fail to connect. That is very important Test 2: Connect clients and keep them logged on for say a week, doing random actions (FuzzTest). Time the round-trip of each action. Also keep record of the order of actions, because this way your "clients" will find loopholes in your usecases (very important, and VERY hard to test rationally). Test 3 & 4: Determine major use cases for your system, and write up scripts that do these tasks. Then run several clients doing same task(test 3), and also several clients doing different tasks(test 4). Series: Now the other dimension you need here is amount of clients. A nice series would be: 5,10,50,100,500,1000,5000,10000,... This way you can get data for each series of tests with different work loads. Also congrats on SWIGing your clients api to Python! That is a great way to get things ready. Note: IBM has a sample of fuzz testing on Java, which is unrealted to your case, but will help you design a good fuzztest for your system
Code Coverage and Unit Testing of Python Code
I have already visited Preferred Python unit-testing framework. I am not just looking at Python Unit Testing Framework, but also code coverage with respect to unit tests. So far I have only come across coverage.py. Is there any better option? An interesting option for me is to integrate cpython, unit testing of Python code and code coverage of Python code with Visual Studio 2008 through plugins (something similar to IronPython Studio). What can be done to achieve this? I look forward to suggestions.
We use this Django coverage integration, but instead of using the default coverage.py reporting, we generate some simple HTML: Colorize Python source using the built-in tokenizer.
Generating a WSDL using Python and SOAPpy
First of all, I will admit I am a novice to web services, although I'm familiar with HTML and basic web stuff. I created a quick-and-dirty web service using Python that calls a stored procedure in a MySQL database, that simply returns a BIGINT value. I want to return this value in the web service, and I want to generate a WSDL that I can give our web developers. I might add that the stored procedure only returns one value. Here's some example code: #!/usr/bin/python import SOAPpy import MySQLdb def getNEXTVAL(): cursor = db.cursor() cursor.execute( "CALL my_stored_procedure()" ) # Returns a number result=cursor.fetchall() for record in result: return record[0] db=MySQLdb.connect(host="localhost", user="myuser", passwd="********", db="testing") server = SOAPpy.SOAPServer(("10.1.22.29", 8080)) server.registerFunction(getNEXTVAL) server.serve_forever() I want to generate a WSDL that I can give to the web folks, and I'm wondering if it's possible to have SOAPpy just generate one for me. Is this possible?
When I tried to write Python web service last year, I ended up using ZSI-2.0 (which is something like heir of SOAPpy) and a paper available on its web. Basically I wrote my WSDL file by hand and then used ZSI stuff to generate stubs for my client and server code. I wouldn't describe the experience as pleasant, but the application did work.
How to check if a directory exists and create it if necessary?
What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried: filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) Somehow, I missed os.path.exists (thanks kanja, Blair, and Douglas). This is what I have now: def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) Is there a flag for "open", that makes this happen automatically?
I see two answers with good qualities, each with a small flaw, so I will give my take on it: Try os.path.exists, and consider os.makedirs for the creation. if not os.path.exists(directory): os.makedirs(directory) As noted in comments and elsewhere, there's a race condition - if the directory is created between the os.path.exists and the os.makedirs calls, the os.makedirs will fail with an OSError. Unfortunately, blanket-catching OSError and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc. One option would be to trap the OSError and examine the embedded error code, if one knew what's what (on my OS, 13 seems to indicate that permission is denied, and 17 that the file exists - it's not clear that that's even remotely portable, but is explored in Is there a cross-platform way of getting information from Python’s OSError). Alternatively, there could be a second os.path.exists, but suppose another created the directory after the first check, then removed it before the second one - we could still be fooled. Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.
Python 3.0 and language evolution
Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity? Also, do you believe that this is how programming languages should evolve or is the price to pay simply too high?
The only language I can think of to attempt such a mid-stream change would be Perl. Of course, Python is beating Perl to that particular finish line by releasing first. It should be noted, however, that Perl's changes are much more extensive than Python's and likely will be harder to detangle. (There's a price for Perl's "There's More Than One Way To Do It" philosophy.) There are examples like the changes from version to version of .NET-based languages (ironic, considering the whole point of .NET was supposed to be API stability and cross-platform compatibility). However, I would hardly call those languages "mature"; it's always been more of a design-on-the-go, build-the-plane-as-we-fly approach to things. Or, as I tend to think of it, most languages come from either "organic growth" or "engineered construction." Perl is the perfect example of organic growth; it started as a fancy text processing tool ala awk/sed and grew into a full language. Python, on the other hand, is much more engineered. Spend a bit of time wandering around the extensive whitepapers on their website to see the extensive debate that goes into every even minor change to the language's syntax and implementation. The idea of making these sorts of far-reaching changes is somewhat new to programming languages because programming languages themselves have changed in nature. It used to be that programming methodologies changed only when a new processor came out that had a new instruction set. The early languages tended to either be so low-level and married to assembly language (e.g. C) or so utterly dynamic in nature (Forth, Lisp) that such a mid-stream change wouldn't even come up as a consideration. As to whether or not the changes are good ones, I'm not sure. I tend to have faith in the people guiding Python's development, however; the changes in the language thus far have been largely for the better. I think in the days to come the Global Interpreter Lock will prove more central than syntax changes. Though the new multiprocessor library might alleviate most of that.
Is there a cross-platform way of getting information from Python's OSError?
On a simple directory creation operation for example, I can make an OSError like this: (Ubuntu Linux) >>> import os >>> os.mkdir('foo') >>> os.mkdir('foo') Traceback (most recent call last): File "<stdin>", line 1, in <module> OSError: [Errno 17] File exists: 'foo' Now I can catch that error like this: >>> import os >>> os.mkdir('foo') >>> try: ... os.mkdir('foo') ... except OSError, e: ... print e.args ... (17, 'File exists') Is there a cross-platform way that I can know that that the 17 or the 'File Exists' will always mean the same thing so that I can act differently depending on the situation? (This came up during another question.)
The errno attribute on the error should be the same on all platforms. You will get WindowsError exceptions on Windows, but since this is a subclass of OSError the same "except OSError:" block will catch it. Windows does have its own error codes, and these are accessible as .winerror, but the .errno attribute should still be present, and usable in a cross-platform way. Symbolic names for the various error codes can be found in the errno module. For example, import os, errno try: os.mkdir('test') except OSError, e: if e.errno == errno.EEXIST: # Do something You can also perform the reverse lookup (to find out what code you should be using) with errno.errorcode. That is: >>> errno.errorcode[17] 'EEXIST'
How do I resize an image using PIL and maintain its aspect ratio?
Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.
Define a maximum size. Then, compute a resize ratio by taking min(maxwidth/width, maxheight/height). The proper size is oldsize*ratio. There is of course also a library method to do this: the method Image.thumbnail. Below is an (edited) example from the PIL documentation. import os, sys import Image size = 128, 128 for infile in sys.argv[1:]: outfile = os.path.splitext(infile)[0] + ".thumbnail" if infile != outfile: try: im = Image.open(infile) im.thumbnail(size, Image.ANTIALIAS) im.save(outfile, "JPEG") except IOError: print "cannot create thumbnail for '%s'" % infile
How can I remove (chomp) a newline in Python?
What is the Python equivalent of Perl's chomp function, which removes the last character of a value?
Try the rstrip method. >>> 'test string\n'.rstrip() 'test string' Note that Python's rstrip method strips all kinds of trailing whitespace by default, not just one newline as Perl does with chomp. To strip only newlines: >>> 'test string \n\n'.rstrip('\n') 'test string ' There is also the lstrip and strip methods. >>> s = " \n abc def " >>> s.strip() 'abc def' >>> s.rstrip() ' \n abc def' >>> s.lstrip() 'abc def ' >>>
How do I perform HTML decoding/encoding using Python/Django?
I have a string that is html encoded: &lt;img class=&quot;size-medium wp-image-113&quot; style=&quot;margin-left: 15px;&quot; title=&quot;su1&quot; src=&quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&quot; alt=&quot;&quot; width=&quot;300&quot; height=&quot;194&quot; /&gt; I want to change that to: <img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /> I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. I've found how to do this in C# but not in in Python. Can someone help me out? Thanks. Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format. Related Convert XML/HTML Entities into Unicode String in Python
Given the Django use case, there are two answers to this. Here is its django.utils.html.escape function, for reference: def escape(html): """Returns the given HTML with ampersands, quotes and carets encoded.""" return mark_safe(force_unicode(html).replace('&', '&amp;').replace('<', '&l t;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;')) To reverse this, the Cheetah function described in Jake's answer should work, but is missing the single-quote. This version includes an updated tuple, with the order of replacement reversed to avoid symmetric problems: def html_decode(s): """ Returns the ASCII decoded version of the given HTML string. This does NOT remove normal HTML tags like <p>. """ htmlCodes = ( ("'", '&#39;'), ('"', '&quot;'), ('>', '&gt;'), ('<', '&lt;'), ('&', '&amp;') ) for code in htmlCodes: s = s.replace(code[1], code[0]) return s unescaped = html_decode(my_string) This, however, is not a general solution; it is only appropriate for strings encoded with django.utils.html.escape. More generally, it is a good idea to stick with the standard library: # Python 2.x: import HTMLParser html_parser = HTMLParser.HTMLParser() unescaped = html_parser.unescape(my_string) # Python 3.x: import html.parser html_parser = html.parser.HTMLParser() unescaped = html_parser.unescape(my_string) As a suggestion: it may make more sense to store the HTML unescaped in your database. It'd be worth looking into getting unescaped results back from BeautifulSoup if possible, and avoiding this process altogether. With Django, escaping only occurs during template rendering; so to prevent escaping you just tell the templating engine not to escape your string. To do that, use one of these options in your template: {{ context_var|safe }} {% autoescape off %} {{ context_var }} {% endautoescape %}
How to get current CPU and RAM usage in Python?
What's your preferred way of getting current system status (current CPU, RAM, free disk space, etc.) in Python? Bonus points for *nix and Windows platforms. There seems to be a few possible ways of extracting that from my search: Using a library such as PSI (that currently seems not actively developed and not supported on multiple platform) or something like pystatgrab (again no activity since 2007 it seems and no support for Windows). Using platform specific code such as using a os.popen("ps") or similar for the *nix systems and MEMORYSTATUS in ctypes.windll.kernel32 (see this recipe on ActiveState) for the Windows platform. One could put a Python class together with all those code snippets. It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?
The psutil library will give you some system information (CPU / Memory usage) on a variety of platforms: psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many functionalities offered by tools like ps, top and Windows task manager. It currently supports Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.5 (users of Python 2.4 and 2.5 may use 2.1.3 version).
WCF and Python
Is there any example code of a cpython (not IronPython) client which can call Windows Communication Foundation (WCF) service?
I used suds. from suds.client import Client print "Connecting to Service..." wsdl = "http://serviceurl.com/service.svc?WSDL" client = Client(wsdl) result = client.service.Method(variable1, variable2) print result That should get you started. I'm able to connect to exposed services from WCF and a RESTful layer. There needs to be some data massaging to help do what you need, especially if you need to bind to several namespaces.
What's a cross platform way to play a sound file in python?
I tried playing a .wav file using pyaudio. It works great on windows, but doesn't work in Ubuntu when another device is using sound. The error is "IOError: [Errorno Invalid output device (no default output device)] -9996 Is there another library I could try to use? Another method?
You can use wxPython sound = wx.Sound('sound.wav') sound.Play(wx.SOUND_SYNC) or sound.Play(wx.SOUND_ASYNC) Here is an example from the wxPython demo.
CPU Usage Per Process in Python
Is it possible for me to see the amount of processor usage (% of maximum) that the current, python, app is using? Scenario: My host will allow me to run my app as long as it does not consume more then X% of the CPU power, so I would like it to 'keep an eye on itself' and slowdown. So how can I know how much CPU the app is using? Target platform is *nix, however I would like to do it on a Win host also.
>>> import os >>> os.times() (1.296875, 0.765625, 0.0, 0.0, 0.0) >>> print os.times.__doc__ times() -> (utime, stime, cutime, cstime, elapsed_time) Return a tuple of floating point numbers indicating process times. From the (2.5) manual: times( ) Return a 5-tuple of floating point numbers indicating accumulated (processor or other) times, in seconds. The items are: user time, system time, children's user time, children's system time, and elapsed real time since a fixed point in the past, in that order. See the Unix manual page times(2) or the corresponding Windows Platform API documentation. Availability: Macintosh, Unix, Windows.
Can you achieve a case insensitive 'unique' constraint in Sqlite3 (with Django)?
So let's say I'm using Python 2.5's built-in default sqlite3 and I have a Django model class with the following code: class SomeEntity(models.Model): some_field = models.CharField(max_length=50, db_index=True, unique=True) I've got the admin interface setup and everything appears to be working fine except that I can create two SomeEntity records, one with some_field='some value' and one with some_field='Some Value' because the unique constraint on some_field appears to be case sensitive. Is there some way to force sqlite to perform a case insensitive comparison when checking for uniqueness? I can't seem to find an option for this in Django's docs and I'm wondering if there's something that I can do directly to sqlite to get it to behave the way I want. :-)
Yes this can easily be done by adding a unique index to the table with the following command: CREATE UNIQUE INDEX uidxName ON mytable (myfield COLLATE NOCASE) If you need case insensitivity for nonASCII letters, you will need to register your own COLLATION with commands similar to the following: The following example shows a custom collation that sorts “the wrong way”: import sqlite3 def collate_reverse(string1, string2): return -cmp(string1, string2) con = sqlite3.connect(":memory:") con.create_collation("reverse", collate_reverse) cur = con.cursor() cur.execute("create table test(x)") cur.executemany("insert into test(x) values (?)", [("a",), ("b",)]) cur.execute("select x from test order by x collate reverse") for row in cur: print row con.close() Additional python documentation for sqlite3 shown here
Exposing a C++ API to Python
I'm currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Python interpreter in our program. The alternatives I tried were: Boost.Python I liked the cleaner API produced by Boost.Python, but the fact that it would have required that users install an additional dependency made us switch to SWIG. SWIG SWIG's main advantage for us was that it doesn't require end users to install it to use the final program. What have you used to do this, and what has been your experience with it?
I've used both (for the same project): Boost is better integrated with the STL, and especially C++ exceptions. Also, its memory management mechanism (which tries to bridge C++ memory management and Python GC) is way more flexible than SWIG's. However, SWIG has much better documentation, no external dependencies, and if you get the library wrapped in SWIG for Python you're more than half-way there to getting a Java/Perl/Ruby wrapper as well. I don't think there's a clear-cut choice: for smaller projects, I'd go with Boost.Python again, for larger long-lived projects, the extra investment in SWIG is worth it.
How to expose std::vector as a Python list using SWIG?
I'm trying to expose this function to Python using SWIG: std::vector<int> get_match_stats(); And I want SWIG to generate wrapping code for Python so I can see it as a list of integers. Adding this to the .i file: %include "typemaps.i" %include "std_vector.i" namespace std { %template(IntVector) vector<int>; } I'm running SWIG Version 1.3.36 and calling swig with -Wall and I get no warnings. I'm able to get access to a list but I get a bunch of warnings when compiling with -Wall (with g++ (GCC) 4.2.4 ) the generated C++ code that say: warning: dereferencing type-punned pointer will break strict-aliasing rules Am I exposing the function correctly? If so, what does the warning mean? These are the lines before the offending line in the same function: SWIGINTERN PyObject *_wrap_IntVector_erase__SWIG_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; std::vector *arg1 = (std::vector *) 0 ; std::vector::iterator arg2 ; std::vector::iterator result; void *argp1 = 0 ; int res1 = 0 ; swig::PySwigIterator *iter2 = 0 ; int res2 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:IntVector_erase",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_std__vectorT_int_std__allocatorT_int_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "IntVector_erase" "', argument " "1"" of type '" "std::vector *""'"); } arg1 = reinterpret_cast * >(argp1); And this is the offending line: res2 = SWIG_ConvertPtr(obj1, SWIG_as_voidptrptr(&iter2), swig::PySwigIterator::descriptor(), 0); More code follows that. The warning generated when compiling with g++ 4.2.4 is: swig_iss_wrap.cxx: In function ‘PyObject* _wrap_IntVector_erase__SWIG_0(PyObject*, PyObject*)’: swig_iss_wrap.cxx:5885: warning: dereferencing type-punned pointer will break strict-aliasing rules
%template(IntVector) vector<int>;
Is there a good Python GUI shell?
I saw this the other day (scroll all the way down to see some of the clever stuff): http://www.mono-project.com/docs/tools+libraries/tools/repl/ And wondered whether something like this exists for Python. So, is there a good Python GUI shell that can do stuff like that C# shell can do? Edit: Here are links to screenshots from the article, showing what I'm interested in doing. An example of the type of things I'm interested: http://www.mono-project.com/archived/images/7/75/GSharpPlot.png They are able to add hooks to produce GUI elements like the plot, or even do silly things like: http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png I don't think this is possible with any of the console shells I've tried (the regular python shell, ipython). Edit: I'm not looking for an IDE. If you look at the link, you'll get an idea of what I want.
One project I'm aware of that provides similar features (inline plotting, customisable rendering) is Reinteract. Another (though possibly a bit heavyweight for general usage) is SAGE which provides functionality for web-based notebooks. These aren't quite shells - they're designed more as a mathematical notebook (so for instance, you can modify an earlier result and have the change propogate to later calculations), but they're close to what you're looking for, and could probably be modified to be used as such.
Python Argument Binders
How can I bind arguments to a Python method to store a nullary functor for later invocation? Similar to C++'s boost::bind.
functools.partial returns a callable wrapping a function with some or all of the arguments frozen. import sys import functools print_hello = functools.partial(sys.stdout.write, "Hello world\n") print_hello() Hello world The above usage is equivalent to the following lambda. print_hello = lambda *a, **kw: sys.stdout.write("Hello world\n", *a, **kw)
Import a module from a relative path
How do I import a python module given its relative path? For example, if dirFoo contains Foo.py and dirBar, and dirBar contains Bar.py, how do I import Bar.py into Foo.py? Here's a visual representation: dirFoo\ Foo.py dirBar\ Bar.py Foo wishes to include Bar, but restructuring the folder hierarchy is not an option.
Be sure that dirBar has the __init__.py file -- this makes a directory into a Python package.
What is the Python equivalent of static variables inside a function?
What is the idiomatic Python equivalent of this C/C++ code? void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
A bit reversed, but this should work: def foo(): foo.counter += 1 print "Counter is %d" % foo.counter foo.counter = 0 If you want the counter initialization code at the top instead of the bottom, you can create a decorator: def static_var(varname, value): def decorate(func): setattr(func, varname, value) return func return decorate Then use the code like this: @static_var("counter", 0) def foo(): foo.counter += 1 print "Counter is %d" % foo.counter It'll still require you to use the foo. prefix, unfortunately. EDIT (thanks to ony): This looks even nicer: def static_vars(**kwargs): def decorate(func): for k in kwargs: setattr(func, k, kwargs[k]) return func return decorate @static_vars(counter=0) def foo(): foo.counter += 1 print "Counter is %d" % foo.counter
PyOpenGl or pyglet?
I am looking to do some tinkering with openGL and Python and haven't been able to find good reasons for using PyOpenGl versus pyglet Which would you recommend and why?
As Tony said, this is really going to depend on your goals. If you're "tinkering" to try to learn about OpenGL or 3D rendering in general that I would dispense with all pleasantries and start working with PyOpenGL, which is as close are you're going to get to "raw" 3D programming using Python. On the other hand, if you're "tinkering" by way of mocking up a game or multimedia application, or trying to learn about programming practices in general than Pyglet will save you lots of up-front development time by providing hooks for input events, sounds, text/billboarding, etc. Often, this up-front investment is what prevents people from completing their projects, so having it done for you is not something to be ignored. (It is also very Pythonic to avoid reinventing the wheel.) If you are looking to do any sort of heavy-duty lifting (which normally falls outside my definition of "tinkering", but maybe not if you're tinkering with 3D engine design) then you might want to take a look at Python-Ogre, which wraps the very full-featured and robust OGRE 3D graphics engine.
Python - sort a list of nested lists
I have input consisting of a list of nested lists like this: l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]] I want to sort this list based on the sum of all the numbers in the nested lists... so, the values I want to sort by of l would look like this: [39, 6, 13, 50] Then I want to sort based on these. So the output should be: [[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]] What's a nice pythonic way of doing this?
A slight simplification and generalization to the answers provided so far, using a recent addition to python's syntax: >>> l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]] >>> def asum(t): return sum(map(asum, t)) if hasattr(t, '__iter__') else t ... >>> sorted(l, key=asum) [[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]]
Python Linked List
What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by '(1 2 3 4 5). Python's lists, [1, 2, 3, 4, 5], and tuples, (1, 2, 3, 4, 5), are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!
For some needs, a deque may also be useful. You can add and remove items on both ends of a deque at O(1) cost. from collections import deque d = deque([1,2,3,4]) print d for x in d: print x print d.pop(), d
Escaping regex string in Python
I want to use input from a user as a regex pattern for a search over some text. It works, but how I can handle cases where user puts characters that have meaning in regex? For example, the user wants to search for Word (s): regex engine will take the (s) as a group. I want it to treat it like a string "(s)" . I can run replace on user input and replace the ( with \( and the ) with \) but the problem is I will need to do replace for every possible regex symbol. Do you know some better way ?
Use the re.escape() function for this: 4.2.3 re Module Contents escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it. A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object. def simplistic_plural(word, text): word_or_plural = re.escape(word) + 's?' return re.match(word_or_plural, text)
Calculate poisson probability percentage
When you use the POISSON function in Excel (or in OpenOffice Calc), it takes two arguments: an integer an 'average' number and returns a float. In Python (I tried RandomArray and NumPy) it returns an array of random poisson numbers. What I really want is the percentage that this event will occur (it is a constant number and the array has every time different numbers - so is it an average?). for example: print poisson(2.6,6) returns [1 3 3 0 1 3] (and every time I run it, it's different). The number I get from calc/excel is 3.19 (POISSON(6,2.16,0)*100). Am I using the python's poisson wrong (no pun!) or am I missing something?
scipy has what you want >>> scipy.stats.distributions <module 'scipy.stats.distributions' from '/home/coventry/lib/python2.5/site-packages/scipy/stats/distributions.pyc'> >>> scipy.stats.distributions.poisson.pmf(6, 2.6) array(0.031867055625524499) It's worth noting that it's pretty easy to calculate by hand, too.
Controlling the mouse from Python in OS X
What would be the easiest way to move the mouse around (and possibly click) using python on OS X? This is just for rapid prototyping, it doesn't have to be elegant. Thanks!
Try the code at http://www.geekorgy.com/index.php/2010/06/python-mouse-click-and-move-mouse-in-apple-mac-osx-snow-leopard-10-6-x/, pasted below in case the site disappears. It defines a couple of functions, mousemove and mouseclick, which hook into Apple's integration between Python and the platform's Quartz libraries. This code works on 10.6, and I'm using it on 10.7. The nice thing about this code is that it generates mouse events, which some solutions don't. I use it to control BBC iPlayer by sending mouse events to known button positions in their Flash player (very brittle I know). The mouse move events, in particular, are required as otherwise the Flash player never hides the mouse cursor. Functions like CGWarpMouseCursorPosition will not do this. from Quartz.CoreGraphics import CGEventCreateMouseEvent from Quartz.CoreGraphics import CGEventPost from Quartz.CoreGraphics import kCGEventMouseMoved from Quartz.CoreGraphics import kCGEventLeftMouseDown from Quartz.CoreGraphics import kCGEventLeftMouseDown from Quartz.CoreGraphics import kCGEventLeftMouseUp from Quartz.CoreGraphics import kCGMouseButtonLeft from Quartz.CoreGraphics import kCGHIDEventTap def mouseEvent(type, posx, posy): theEvent = CGEventCreateMouseEvent( None, type, (posx,posy), kCGMouseButtonLeft) CGEventPost(kCGHIDEventTap, theEvent) def mousemove(posx,posy): mouseEvent(kCGEventMouseMoved, posx,posy); def mouseclick(posx,posy): # uncomment this line if you want to force the mouse # to MOVE to the click location first (I found it was not necessary). #mouseEvent(kCGEventMouseMoved, posx,posy); mouseEvent(kCGEventLeftMouseDown, posx,posy); mouseEvent(kCGEventLeftMouseUp, posx,posy);
Open explorer on a file
In Python, how do I jump to a file in the Windows Explorer? I found a solution for jumping to folders: import subprocess subprocess.Popen('explorer "C:\path\of\folder"') but I have no solution for files.
From Explorer.exe Command-Line Options for Windows XP import subprocess subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"')
Django debugging with Emacs
I found a lot of info about how to debug simple Python programs with Emacs. But what if I want to debug a Django application? I run the development server and I would like to somehow attach to the process from Emacs and then set breakpoints, etc. Similar to Visual Studio's "attach to process". How to do that?
This isn't emacs specific, but you can use the Python debugger by adding the following to a Django view function: import pdb; pdb.set_trace() Now when you run the development server and view the page, your browser will appear to hang or load very slowly - switch over to your console, and you have access to the full debugger. You can inspect AND modify state of your application via an interactive shell - check out the Python documentation for the debugger, or this link for some Python debugging examples If all you need is logging, add the following to your settings.py: logging.basicConfig( level = logging.DEBUG, format = '%(asctime)s %(levelname)s %(message)s', filename = '/tmp/mylog.log', filemode = 'w' ) Now you can log messages to /tmp/mylog.log by adding the following to any view function: import logging logging.debug("Something happened")
python list in sql query as parameter
I have a python list, say l l = [1,5,8] I want to write a sql query to get the data for all the elements of the list, say "select name from studens where id = |IN THE LIST l|" How do i accomlish this?
Answers so far have been templating the values into a plain SQL string. That's absolutely fine for integers, but if we wanted to do it for strings we get the escaping issue. Here's a variant using a parameterised query that would work for both: placeholder= '?' # For SQLite. See DBAPI paramstyle. placeholders= ', '.join(placeholder for unused in l) query= 'SELECT name FROM students WHERE id IN (%s)' % placeholders cursor.execute(query, l)
Size of an open file object
Is there a way to find the size of a file object that is currently open? Specifically, I am working with the tarfile module to create tarfiles, but I don't want my tarfile to exceed a certain size. As far as I know, tarfile objects are file-like objects, so I imagine a generic solution would work.
$ ls -la chardet-1.0.1.tgz -rwxr-xr-x 1 vinko vinko 179218 2008-10-20 17:49 chardet-1.0.1.tgz $ python Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('chardet-1.0.1.tgz','rb') >>> f.seek(0,2) >>> f.tell() 179218L Adding ChrisJY's idea to the example >>> import os >>> os.fstat(f.fileno()).st_size 179218L >>>
Outputting data from unit test in python
If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string. For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata: class TestBar(unittest.TestCase): def runTest(self): for t1, t2 in testdata: f = Foo(t1) self.assertEqual(f.bar(t2), 2) If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.
We use the logging module for this. For example: import logging class SomeTest( unittest.TestCase ): def testSomething( self ): log= logging.getLogger( "SomeTest.testSomething" ) log.debug( "this= %r", self.this ) log.debug( "that= %r", self.that ) # etc. self.assertEquals( 3.14, pi ) if __name__ == "__main__": logging.basicConfig( stream=sys.stderr ) logging.getLogger( "SomeTest.testSomething" ).setLevel( logging.DEBUG ) unittest.main() That allows us to turn on debugging for specific tests which we know are failing and for which we want additional debugging information. My preferred method, however, isn't to spent a lot of time on debugging, but spend it writing more fine-grained tests to expose the problem.
Cross platform hidden file detection
What is the best way to do cross-platform handling of hidden files? (preferably in Python, but other solutions still appreciated) Simply checking for a leading '.' works for *nix/Mac, and file attributes work on Windows. However, this seems a little simplistic, and also doesn't account for alternative methods of hiding things (.hidden files, etc.). Is there a standard way to deal with this?
Here's a script that runs on Python 2.5+ and should do what you're looking for: import ctypes import os def is_hidden(filepath): name = os.path.basename(os.path.abspath(filepath)) return name.startswith('.') or has_hidden_attribute(filepath) def has_hidden_attribute(filepath): try: attrs = ctypes.windll.kernel32.GetFileAttributesW(unicode(filepath)) assert attrs != -1 result = bool(attrs & 2) except (AttributeError, AssertionError): result = False return result I added something similar to has_hidden_attribute to jaraco.windows. If you have jaraco.windows >= 2.3: from jaraco.windows import filesystem def has_hidden_attribute(filepath): return filesystem.GetFileAttributes(filepath).hidden As Ben has pointed out, on Python 3.5, you can use the stdlib: import os, stat def has_hidden_attribute(filepath): return bool(os.stat(filepath).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN) Though you may still want to use jaraco.windows for the more Pythonic API.
How do you programmatically set an attribute in Python?
Suppose I have a python object x and a string s, how do I set the attribute s on x? So: >>> x = SomeObject() >>> attr = 'myAttr' >>> # magic goes here >>> x.myAttr 'magic' What's the magic? The goal of this, incidentally, is to cache calls to x.__getattr__().
setattr(x, attr, 'magic') For help on it: >>> help(setattr) Help on built-in function setattr in module __builtin__: setattr(...) setattr(object, name, value) Set a named attribute on an object; setattr(x, 'y', v) is equivalent to ``x.y = v''. Edit: However, you should note (as pointed out in comment) that you can't do that to a "pure" instance of object. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.
Exit codes in Python
I got a message saying script xyz.py returned exit code 0. What does this mean? What do the exit codes in Python mean? How many are there? Which ones are important?
What you're looking for in the script is calls to sys.exit(). The argument to that method is returned to the environment as the exit code. It's fairly likely that the script is never calling the exit method, and that 0 is the default exit code.
Python module to extract probable dates from strings?
I'm looking for a Python module that would take an arbitrary block of text, search it for something that looks like a date string, and build a DateTime object out of it. Something like Date::Extract in Perl Thank you in advance.
The nearest equivalent is probably the dateutil module. Usage is: >>> from dateutil.parser import parse >>> parse("Wed, Nov 12") datetime.datetime(2008, 11, 12, 0, 0) Using the fuzzy parameter should ignore extraneous text. ie >>> parse("the date was the 1st of December 2006 2:30pm", fuzzy=True) datetime.datetime(2006, 12, 1, 14, 30)
Parse HTML via XPath
In .Net, I found this great library, HtmlAgilityPack that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?
I'm surprised there isn't a single mention of lxml. It's blazingly fast and will work in any environment that allows CPython libraries. Here's how you can parse HTML via XPATH using lxml. >>> from lxml import etree >>> doc = '<foo><bar></bar></foo>' >>> tree = etree.HTML(doc) >>> r = tree.xpath('/foo/bar') >>> len(r) 1 >>> r[0].tag 'bar' >>> r = tree.xpath('bar') >>> r[0].tag 'bar'
Any AOP support library for Python?
I am trying to use some AOP in my Python programming, but I do not have any experience of the various libs that exists. So my question is : What AOP support exists for Python, and what are the advantages of the differents libraries between them ? Edit : I've found some, but I don't know how they compare : Aspyct Lightweight AOP for Python Edit2 : In which context will I use this ? I have two applications, written in Python, which have typically methods which compute taxes and other money things. I'd like to be able to write a "skeleton" of a functionnality, and customize it at runtime, for example changing the way local taxes are applied (by country, or state, or city, etc.) without having to overload the full stack.
See S.Lott's link about Python decorators for some great examples, and see the defining PEP for decorators. Python had AOP since the beginning, it just didn't have an impressive name. In Python 2.4 the decorator syntax was added, which makes applying decorators very nice syntactically. Maybe if you want to apply decorators based on rules you would need a library, but if you're willing to mark the relevant functions/methods when you declare them you probably don't. Here's an example for a simple caching decorator (I wrote it for this question): import pickle, functools def cache(f): _cache = {} def wrapper(*args, **kwargs): key = pickle.dumps((args, kwargs)) if key not in _cache: _cache[key] = f(*args, **kwargs) # call the wrapped function, save in cache return _cache[key] # read value from cache functools.update_wrapper(wrapper, f) # update wrapper's metadata return wrapper import time @cache def foo(n): time.sleep(2) return n*2 foo(10) # first call with parameter 10, sleeps foo(10) # returns immediately
Python program start
Should I start a Python program with: if__name__ == '__main__': some code... And if so, why? I saw it many times but don't have a clue about it.
If your program is usable as a library but you also have a main program (e.g. to test the library), that construct lets others import the file as a library and not run your main program. If your program is named foo.py and you do "import foo" from another python file, __name__ evaluates to 'foo', but if you run "python foo.py" from the command line, __name__ evaluates to '__main__'. Note that you do need to insert a space between if and _, and indent the main program: if __name__ == '__main__': main program here