text
stringlengths
226
34.5k
Create an encrypted ZIP file in Python Question: I'm creating an ZIP file with ZipFile in Python 2.5, it works ok so far: import zipfile, os locfile = "test.txt" loczip = os.path.splitext (locfile)[0] + ".zip" zip = zipfile.ZipFile (loczip, "w") zip.write (locfile) zip.close() but I couldn't find how to encrypt the files in the ZIP file. I could use system and call PKZIP -s, but I suppose there must be a more "Pythonic" way. I'm looking for an open source solution. Answer: I created a simple library to create a password encrypted zip file in python. - [**here**](https://github.com/smihica/pyminizip) import pyminizip compression_level = 5 # 1-9 pyminizip.compress("src.txt", "dst.zip", "password", compression_level) **The library requires zlib.** I have checked that the file can be extracted in WINDOWS/MAC.
Are there static analysis tools for Python? Question: I am starting to use Python (specifically because of Django) and I would like to remove the burden for exhaustive testing by performing some static analysis. What tools/parameters/etc. exist to detect issues at compile time that would otherwise show up during runtime? (type errors are probably the most obvious case of this, but undefined variables are another big one that could be avoided with an in-depth analysis of the AST.) Obviously testing is important, and I don't imply that tests can be obviated entirely; however, there are many runtime errors in python that are not possible in other languages that perform stricter run-time checking -- I'm hoping that there are tools to bring at least some of these capabilities to python as well. Answer: [pylint](http://www.logilab.org/857) is the best such tool I've found. Due to Python's nature it's difficult to statically analyze it, but it will catch undefined variables, basic type errors, unused code, etc. You'll want to tweak the configuration file, as by default it outputs many warnings I consider useless or harmful. Here's part of my `.pylintrc` dealing with warning silencing: [MESSAGES CONTROL] # Brain-dead errors regarding standard language features # W0142 = *args and **kwargs support # W0403 = Relative imports # Pointless whinging # R0201 = Method could be a function # W0212 = Accessing protected attribute of client class # W0613 = Unused argument # W0232 = Class has no __init__ method # R0903 = Too few public methods # C0301 = Line too long # R0913 = Too many arguments # C0103 = Invalid name # R0914 = Too many local variables # PyLint's module importation is unreliable # F0401 = Unable to import module # W0402 = Uses of a deprecated module # Already an error when wildcard imports are used # W0614 = Unused import from wildcard # Sometimes disabled depending on how bad a module is # C0111 = Missing docstring # Disable the message(s) with the given id(s). disable=W0142,W0403,R0201,W0212,W0613,W0232,R0903,W0614,C0111,C0301,R0913,C0103,F0401,W0402,R0914
Get Last Day of the Month in Python Question: Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month? If the standard library doesn't support that, does the dateutil package support this? Answer: I didn't notice this earlier when I was looking at the [documentation for the calendar module](https://docs.python.org/2/library/calendar.html), but a method called [monthrange](http://docs.python.org/library/calendar.html#calendar.monthrange) provides this information: > **monthrange(year, month)** > Returns weekday of first day of the month and number of days in month, > for the specified year and month. >>> import calendar >>> calendar.monthrange(2002,1) (1, 31) >>> calendar.monthrange(2008,2) (4, 29) >>> calendar.monthrange(2100,2) (0, 28) so: calendar.monthrange(year, month)[1] seems like the simplest way to go. Just to be clear, `monthrange` supports leap years as well: >>> from calendar import monthrange >>> monthrange(2012, 2) (2, 29) [My previous answer](http://stackoverflow.com/questions/42950/get-last-day-of- the-month-in-python#43088) still works, but is clearly suboptimal.
How to find the mime type of a file in python? Question: Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer. Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response. Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type. How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. Does the browser add this information when posting the file to the web page? Is there a neat python library for finding this information? A WebService or (even better) a downloadable database? Answer: The python-magic method suggested by toivotuo is outdated. [Python- magic's](http://github.com/ahupp/python-magic) current trunk is at Github and based on the readme there, finding the MIME-type, is done like this. # For MIME types >>> import magic >>> mime = magic.Magic(mime=True) >>> mime.from_file("testdata/test.pdf") 'application/pdf' >>>
How to know whether a window with a given title is already open in Tk? Question: I’ve writen a little python script that just pops up a message box containing the text passed on the command line. I want to pop it up only when the window —resulting from a previous call— is not open. from Tkinter import * import tkMessageBox root = Tk() root.withdraw() # TODO not if a window with this title exists tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:])) Any idea how to check that? Answer: I believe you want: if 'normal' != root.state(): tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:]))
What is the simplest way to find the difference between 2 times in python? Question: I have 2 time values which have the type `datetime.time`. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type `datetime.datetime` but not for `datetime.time`. So what is the best way to do this? Answer: Also a little silly, but you could try picking an arbitrary day and embedding each time in it, using `datetime.datetime.combine`, then subtracting: >>> import datetime >>> t1 = datetime.time(2,3,4) >>> t2 = datetime.time(18,20,59) >>> dummydate = datetime.date(2000,1,1) >>> datetime.datetime.combine(dummydate,t2) - datetime.datetime.combine(dummydate,t1) datetime.timedelta(0, 58675)
How to get an absolute file path in Python Question: Given a path such as `"mydir/myfile.txt"`, how do I find the absolute filepath relative to the current working directory in Python? E.g. on Windows, I might end up with: "C:/example/cwd/mydir/myfile.txt" Answer: >>> import os >>> os.path.abspath("mydir/myfile.txt")
How do I write a python HTTP server to listen on multiple ports? Question: I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port? What I'm doing now: class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def doGET [...] class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): pass server = ThreadingHTTPServer(('localhost', 80), MyRequestHandler) server.serve_forever() Answer: Sure; just start two different servers on two different ports in two different threads that each use the same handler. Here's a complete, working example that I just wrote and tested. If you run this code then you'll be able to get a Hello World webpage at both <http://localhost:1111/> and <http://localhost:2222/> from threading import Thread from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() self.wfile.write("Hello World!") class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): pass def serve_on_port(port): server = ThreadingHTTPServer(("localhost",port), Handler) server.serve_forever() Thread(target=serve_on_port, args=[1111]).start() serve_on_port(2222)
Random in python 2.5 not working? Question: I am trying to use the `import random` statement in python, but it doesn't appear to have any methods in it to use. Am I missing something? Answer: You probably have a file named random.py or random.pyc in your working directory. That's shadowing the built-in random module. You need to rename random.py to something like my_random.py and/or remove the random.pyc file. To tell for sure what's going on, do this: >>> import random >>> print random.__file__ That will show you exactly which file is being imported.
Why learn Perl, Python, Ruby if the company is using C++, C# or Java as the application language? Question: I wonder why would a C++, C#, Java developer want to learn a dynamic language? Assuming the company won't switch its main development language from C++/C#/Java to a dynamic one what use is there for a dynamic language? What helper tasks can be done by the dynamic languages faster or better after only a few days of learning than with the static language that you have been using for several years? ## Update After seeing the first few responses it is clear that there are two issues. My main interest would be something that is justifiable to the employer as an expense. That is, I am looking for justifications for the employer to finance the learning of a dynamic language. Aside from the obvious that the employee will have broader view, the employers are usually looking for some "real" benefit. Answer: A lot of times some quick task comes up that isn't part of the main software you are developing. Sometimes the task is one off ie compare this file to the database and let me know the differences. It is a lot easier to do text parsing in Perl/Ruby/Python than it is in Java or C# (partially because it is a lot easier to use regular expressions). It will probably take a lot less time to parse the text file using Perl/Ruby/Python (or maybe even vbscript _cringe_ and then load it into the database than it would to create a Java/C# program to do it or to do it by hand. Also, due to the ease at which most of the dynamic languages parse text, they are great for code generation. Sure your final project must be in C#/Java/Transact SQL but instead of cutting and pasting 100 times, finding errors, and cutting and pasting another 100 times it is often (but not always) easier just to use a code generator. A recent example at work is we needed to get data from one accounting system into our accounting system. The system has an import format, but the old system had a completely different format (fixed width although some things had to be matched). The task is not to create a program to migrate the data over and over again. It is to shove the data into our system and then maintain it there going forward. So even though we are a C# and SQL Server shop, I used Python to convert the data into the format that could be imported by our application. Ultimately it doesn't matter that I used python, it matters that the data is in the system. My boss was pretty impressed. Where I often see the dynamic languages used for is testing. It is much easier to create a Python/Perl/Ruby program to link to a web service and throw some data against it than it is to create the equivalent Java program. You can also use python to hit against command line programs, generate a ton of garbage (but still valid) test data, etc.. quite easily. The other thing that dynamic languages are big on is code generation. Creating the C#/C++/Java code. Some examples follow: The first code generation task I often see is people using dynamic languages to maintain constants in the system. Instead of hand coding a bunch of enums, a dynamic language can be used to fairly easily parse a text file and create the Java/C# code with the enums. SQL is a whole other ball game but often you get better performance by cut and pasting 100 times instead of trying to do a function (due to caching of execution plans or putting complicated logic in a function causing you to go row by row instead of in a set). In fact it is quite useful to use the table definition to create certain stored procedures automatically. It is always better to get buy in for a code generator. But even if you don't, is it more fun to spend time cutting/pasting or is it more fun to create a Perl/Python/Ruby script once and then have that generate the code? If it takes you hours to hand code something but less time to create a code generator, then even if you use it once you have saved time and hence money. If it takes you longer to create a code generator than it takes to hand code once but you know you will have to update the code more than once, it may still make sense. If it takes you 2 hours to hand code, 4 hours to do the generator but you know you'll have to hand code equivalent work another 5 or 6 times than it is obviously better to create the generator. Also some things are easier with dynamic languages than Java/C#/C/C++. In particular regular expressions come to mind. If you start using regular expressions in Perl and realize their value, you may suddenly start making use of the Java regular expression library if you haven't before. If you have then there may be something else. I will leave you with one last example of a task that would have been great for a dynamic language. My work mate had to take a directory full of files and burn them to various cd's for various customers. There were a few customers but a lot of files and you had to look in them to see what they were. He did this task by hand....A Java/C# program would have saved time, but for one time and with all the development overhead it isn't worth it. However slapping something together in Perl/Python/Ruby probably would have been worth it. He spent several hours doing it. It would have taken less than one to create the Python script to inspect each file, match which customer it goes to, and then move the file to the appropriate place.....Again, not part of the standard job. But the task came up as a one off. Is it better to do it yourself, spend the larger amount of time to make Java/C# do the task, or spend a much smaller amount of time doing it in Python/Perl/Ruby. If you are using C or C++ the point is even more dramatic due to the extra concerns of programming in C or C++ (pointers, no array bounds checking, etc.).
Is there a pretty printer for python data? Question: Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.) The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it. Is there something that will take any python object and display it in a more rational manner. e.g. [0, 1, [a, b, c], 2, 3, 4] instead of: [0, 1, [a, b, c], 2, 3, 4] I know that's not a very good example, but I think you get the idea. Answer: from pprint import pprint a = [0, 1, ['a', 'b', 'c'], 2, 3, 4] pprint(a) Note that for a short list like my example, pprint will in fact print it all on one line. However, for more complex structures it does a pretty good job of pretty printing data.
Python sockets suddenly timing out? Question: I came back today to an old script I had for logging into Gmail via SSL. The script worked fine last time I ran it (several months ago) but now it dies immediately with: <urlopen error The read operation timed out> If I set the timeout (no matter how long), it dies even more immediately with: <urlopen error The connect operation timed out> The latter is reproducible with: import socket socket.setdefaulttimeout(30000) sock = socket.socket() sock.connect(('www.google.com', 443)) ssl = socket.ssl(sock) returning: socket.sslerror: The connect operation timed out but I can't seem to reproduce the former and, after much stepping thru the code, I have no clue what's causing any of this. Answer: import socket socket.setdefaulttimeout(30000) sock = socket.socket() sock.connect(('www.google.com', 443)) ssl = socket.ssl(sock) ssl.server() --> '/C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com' It works just fine. I can't reproduce your error.
What's the easiest non-memory intensive way to output XML from Python? Question: Basically, something similar to System.Xml.XmlWriter - A streaming XML Writer that doesn't incur much of a memory overhead. So that rules out xml.dom and xml.dom.minidom. Suggestions? Answer: I think you'll find XMLGenerator from xml.sax.saxutils is the closest thing to what you want. import time from xml.sax.saxutils import XMLGenerator from xml.sax.xmlreader import AttributesNSImpl LOG_LEVELS = ['DEBUG', 'WARNING', 'ERROR'] class xml_logger: def __init__(self, output, encoding): """ Set up a logger object, which takes SAX events and outputs an XML log file """ logger = XMLGenerator(output, encoding) logger.startDocument() attrs = AttributesNSImpl({}, {}) logger.startElementNS((None, u'log'), u'log', attrs) self._logger = logger self._output = output self._encoding = encoding return def write_entry(self, level, msg): """ Write a log entry to the logger level - the level of the entry msg - the text of the entry. Must be a Unicode object """ #Note: in a real application, I would use ISO 8601 for the date #asctime used here for simplicity now = time.asctime(time.localtime()) attr_vals = { (None, u'date'): now, (None, u'level'): LOG_LEVELS[level], } attr_qnames = { (None, u'date'): u'date', (None, u'level'): u'level', } attrs = AttributesNSImpl(attr_vals, attr_qnames) self._logger.startElementNS((None, u'entry'), u'entry', attrs) self._logger.characters(msg) self._logger.endElementNS((None, u'entry'), u'entry') return def close(self): """ Clean up the logger object """ self._logger.endElementNS((None, u'log'), u'log') self._logger.endDocument() return if __name__ == "__main__": #Test it out import sys xl = xml_logger(sys.stdout, 'utf-8') xl.write_entry(2, u"Vanilla log entry") xl.close() You'll probably want to look at the rest of the article I got that from at <http://www.xml.com/pub/a/2003/03/12/py-xml.html>.
How do I read selected files from a remote Zip archive over HTTP using Python? Question: I need to read selected files, matching on the file name, from a remote zip archive using Python. I don't want to save the full zip to a temporary file (it's not that large, so I can handle everything in memory). I've already written the code and it works, and I'm answering this myself so I can search for it later. But since evidence suggests that I'm one of the dumber participants on Stackoverflow, I'm sure there's room for improvement. Answer: Here's how I did it (grabbing all files ending in ".ranks"): import urllib2, cStringIO, zipfile try: remotezip = urllib2.urlopen(url) zipinmemory = cStringIO.StringIO(remotezip.read()) zip = zipfile.ZipFile(zipinmemory) for fn in zip.namelist(): if fn.endswith(".ranks"): ranks_data = zip.read(fn) for line in ranks_data.split("\n"): # do something with each line except urllib2.HTTPError: # handle exception
Python reading Oracle path Question: On my desktop I have written a small Pylons app that connects to Oracle. I'm now trying to deploy it to my server which is running Win2k3 x64. (My desktop is 32-bit XP) The Oracle installation on the server is also 64-bit. I was getting errors about loading the OCI dll, so I installed the 32 bit client into `C:\oracle32`. If I add this to the `PATH` environment variable, it works great. But I also want to run the Pylons app as a service ([using this recipe](http://wiki.pylonshq.com/display/pylonscookbook/How+to+run+Pylons+as+a+Windows+service)) and don't want to put this 32-bit library on the path for all other applications. I tried using `sys.path.append("C:\\oracle32\\bin")` but that doesn't seem to work. Answer: sys.path is python's internal representation of the PYTHONPATH, it sounds to me like you want to modify the PATH. I'm not sure that this will work, but you can try: import os os.environ['PATH'] += os.pathsep + "C:\\oracle32\\bin"
What is the standard way to add N seconds to datetime.time in Python? Question: Given a `datetime.time` value in Python, is there a standard way to add an integer number of seconds to it, so that `11:34:59` \+ 3 = `11:35:02`, for example? These obvious ideas don't work: >>> datetime.time(11, 34, 59) + 3 TypeError: unsupported operand type(s) for +: 'datetime.time' and 'int' >>> datetime.time(11, 34, 59) + datetime.timedelta(0, 3) TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta' >>> datetime.time(11, 34, 59) + datetime.time(0, 0, 3) TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time' In the end I have written functions like this: def add_secs_to_time(timeval, secs_to_add): secs = timeval.hour * 3600 + timeval.minute * 60 + timeval.second secs += secs_to_add return datetime.time(secs // 3600, (secs % 3600) // 60, secs % 60) I can't help thinking that I'm missing an easier way to do this though. ### Related * [python time + timedelta equivalent](http://stackoverflow.com/questions/656297/python-time-timedelta-equivalent) Answer: You can use full `datetime` variables with `timedelta`, and by providing a dummy date then using `time` to just get the time value. For example: import datetime a = datetime.datetime(100,1,1,11,34,59) b = a + datetime.timedelta(0,3) # days, seconds, then other fields. print a.time() print b.time() results in the two values, three seconds apart: 11:34:59 11:35:02 You could also opt for the more readable b = a + datetime.timedelta(seconds=3) if you're so inclined. * * * If you're after a function that can do this, you can look into using `addSecs` below: import datetime def addSecs(tm, secs): fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second) fulldate = fulldate + datetime.timedelta(seconds=secs) return fulldate.time() a = datetime.datetime.now().time() b = addSecs(a, 300) print a print b This outputs: 09:11:55.775695 09:16:55
How to generate all permutations of a list in Python Question: How do you generate all the permutations of a list in Python, independently of the type of elements in that list? For example: permutations([]) [] permutations([1]) [1] permutations([1, 2]) [1, 2] [2, 1] permutations([1, 2, 3]) [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] EDIT: Eliben pointed to a solution that's similar to mine although simpler, so I'm choosing it as the accepted answer, although Python 2.6+ has a builtin solution in the **itertools** module: import itertools itertools.permutations([1, 2, 3]) Answer: And in [Python 2.6](http://docs.python.org/dev/whatsnew/2.6.html) onwards: import itertools itertools.permutations([1,2,3]) (returned as a generator. Use `list(permutations(l))` to return as a list.)
How do I get a decimal value when using the division operator in Python? Question: For example, the standard division symbol '/' rounds to zero: >>> 4 / 100 0 However, I want it to return 0.04. What do I use? Answer: There are three options: >>> 4 / float(100) 0.04 >>> 4 / 100.0 0.04 which is the same behavior as the C, C++, Java etc, or >>> from __future__ import division >>> 4 / 100 0.04 You can also activate this behavior by passing the argument `-Qnew` to the Python interpreter: $ python -Qnew >>> 4 / 100 0.04 The second option will be the default in Python 3.0. If you want to have the old integer division, you have to use the `//` operator. **Edit** : added section about `-Qnew`, thanks to [ΤΖΩΤΖΙΟΥ](http://stackoverflow.com/users/6899/)!
How do you use the ellipsis slicing syntax in Python? Question: This came up in [Hidden features of Python](http://stackoverflow.com/questions/101268/hidden-features-of-python), but I can't see good documentation or examples that explain how the feature works. Answer: The ellipsis is used to slice higher-dimensional data structures. It's designed to mean _at this point, insert as many full slices (`:`) to extend the multi-dimensional slice to all dimensions_. **Example** : >>> from numpy import arange >>> a = arange(16).reshape(2,2,2,2) Now, you have a 4-dimensional matrix of order 2x2x2x2. To select all first elements in the 4th dimension, you can use the ellipsis notation >>> a[..., 0].flatten() array([ 0, 2, 4, 6, 8, 10, 12, 14]) which is equivalent to >>> a[:,:,:,0].flatten() array([ 0, 2, 4, 6, 8, 10, 12, 14]) In your own implementations, you're free to ignore the contract mentioned above and use it for whatever you see fit.
Short Integers in Python Question: Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory. So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')? Answer: Nope. But you can use short integers in arrays: from array import array a = array("h") # h = signed short, H = unsigned short As long as the value stays in that array it will be a short integer. * documentation for the [array module](http://docs.python.org/dev/library/array)
How can I read the RGB value of a given pixel in Python? Question: If I open an image with `open("image.jpg")`, how can I get the RGB values of a pixel, if I have the coordinates of the pixel? Then how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value? It would be so much better if I didn't have to download any additional libraries. Answer: It's probably best to use the [Python Image Library](http://www.pythonware.com/products/pil/) to do this which I'm afraid is a separate download. The easiest way to do what you want is via the [load() method on the Image object](http://effbot.org/imagingbook/image.htm) which returns a pixel access object which you can manipulate like an array: from PIL import Image im = Image.open("dead_parrot.jpg") #Can be many different formats. pix = im.load() print im.size #Get the width and hight of the image for iterating over print pix[x,y] #Get the RGBA Value of the a pixel of an image pix[x,y] = value # Set the RGBA Value of the image (tuple) Alternatively, look at [ImageDraw](http://effbot.org/imagingbook/imagedraw.htm) which gives a much richer API for creating images.
listing all functions in a python module Question: I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python? eg. something like: from somemodule import foo print foo.methods # or whatever is the correct method to call Answer: You can use `dir(module)` to see all available methods/attributes. Also check out PyDocs.
Calling C/C++ from python? Question: What would be the quickest way to construct a python binding to a C or C++ library? (using windows if this matters) Answer: I like [ctypes](http://docs.python.org/2/library/ctypes.html) a lot, [swig](http://www.swig.org/) always tended to give me [problems](http://groups.google.com/group/comp.lang.python/browse_thread/thread/d94badd9847fe43a?pli=1). Also ctypes has the advantage that you don't need to satisfy any compile time dependency on python, and your binding will work on any python that has ctypes, not just the one it was compiled against. Suppose you have a simple C++ example class you want to talk to in a file called foo.cpp: #include <iostream> class Foo{ public: void bar(){ std::cout << "Hello" << std::endl; } }; Since ctypes can only talk to C functions, you need to provide those declaring them as extern "C" extern "C" { Foo* Foo_new(){ return new Foo(); } void Foo_bar(Foo* foo){ foo->bar(); } } Next you have to compile this to a shared library g++ -c -fPIC foo.cpp -o foo.o g++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o And finally you have to write your python wrapper (e.g. in fooWrapper.py) from ctypes import cdll lib = cdll.LoadLibrary('./libfoo.so') class Foo(object): def __init__(self): self.obj = lib.Foo_new() def bar(self): lib.Foo_bar(self.obj) Once you have that you can call it like f = Foo() f.bar() #and you will see "Hello" on the screen
Python - How do I write a decorator that restores the cwd? Question: How do I write a decorator that restores the current working directory to what it was before the decorated function was called? In other words, if I use the decorator on a function that does an os.chdir(), the cwd will not be changed after the function is called. Answer: The answer for a decorator has been given; it works at the function definition stage as requested. With Python 2.5+, you also have an option to do that at the function _call_ stage using a context manager: from __future__ import with_statement # needed for 2.5 ≤ Python < 2.6 import contextlib, os @contextlib.contextmanager def remember_cwd(): curdir= os.getcwd() try: yield finally: os.chdir(curdir) which can be used if needed at the function call time as: print "getcwd before:", os.getcwd() with remember_cwd(): walk_around_the_filesystem() print "getcwd after:", os.getcwd() It's a nice option to have. EDIT: I added error handling as suggested by codeape. Since my answer has been voted up, it's fair to offer a complete answer, all other issues aside.
Python - Py2exe can't build .exe using the 'email' module Question: py2exe does not work with the standard email module Hello. I am trying to use py2exe for converting a script into an exe. The build process shows this: * * * The following modules appear to be missing ## ['email.Encoders', 'email.Generator', 'email.Iterators', 'email.MIMEBase', 'email.MIMEMultipart', 'email.MIMEText', 'email.Utils', 'email.base64MIME'] The executable does not work. The referenced modules are not included. I researched this on the Internet and I found out that py2exe has a problem with the Lazy import used in the standard lib email module. Unfortunately I have not succeeded in finding a workaround for this problem. Can anyone help? Thank you, P.S. Imports in the script look like this: Code: Select all import string,time,sys,os,smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email import Encoders Answer: Have a look at this question [how-to-package-twisted-program-with- py2exe](http://stackoverflow.com/questions/169897/how-to-package-twisted- program-with-py2exe) it seems to be the same problem. The answer given there is to explicitly include the modules on the command line to py2exe.
How do I convert a file's format from Unicode to ASCII using Python? Question: I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format. What is the best way to convert the entire file format using Python? Answer: You can convert the file easily enough just using the `unicode` function, but you'll run into problems with Unicode characters without a straight ASCII equivalent. [This blog](http://www.peterbe.com/plog/unicode-to-ascii) recommends the `[unicodedata ](http://www.python.org/doc/2.5.2/lib/module-unicodedata.html)` module, which seems to take care of roughly converting characters without direct corresponding ASCII values, e.g. >>> title = u"Klüft skräms inför på fédéral électoral große" is typically converted to Klft skrms infr p fdral lectoral groe which is pretty wrong. However, using the `unicodedata` module, the result can be much closer to the original text: >>> import unicodedata >>> unicodedata.normalize('NFKD', title).encode('ascii','ignore') 'Kluft skrams infor pa federal electoral groe'
Accessing python egg's own metadata Question: I've produced a python egg using setuptools and would like to access it's metadata at runtime. I currently got working this: import pkg_resources dist = pkg_resources.get_distribution("my_project") print(dist.version) but this would probably work incorrectly if I had multiple versions of the same egg installed. And if I have both installed egg and development version, then running this code from development version would pick up version of the installed egg. So, how do I get metadata for _my_ egg not some random matching egg installed on my system? Answer: I am somewhat new to Python as well, but from what I understand: Although you can install multiple versions of the "same" egg (having the same name), only one of them will be available to any particular piece of code at runtime (based on your discovery method). So if your egg is the one calling this code, it must have already been selected as _the_ version of `my_project` for this code, and your access will be to your own version.
How to check if OS is Vista in Python? Question: How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)? Essentially, I need a function that called will return True iff current OS is Vista: >>> isWindowsVista() True Answer: Python has the lovely 'platform' module to help you out. >>> import platform >>> platform.win32_ver() ('XP', '5.1.2600', 'SP2', 'Multiprocessor Free') >>> platform.system() 'Windows' >>> platform.version() '5.1.2600' >>> platform.release() 'XP' NOTE: As mentioned in the comments proper values may not be returned when using older versions of python.
Can you list the keyword arguments a Python function receives? Question: I have a dict, which I need to pass key/values as keyword arguments.. For example.. d_args = {'kw1': 'value1', 'kw2': 'value2'} example(**d_args) This works fine, _but_ if there are values in the d_args dict that are not accepted by the `example` function, it obviously dies.. Say, if the example function is defined as `def example(kw2):` This is a problem since I don't control either the generation of the `d_args`, or the `example` function.. They both come from external modules, and `example` only accepts some of the keyword-arguments from the dict.. Ideally I would just do parsed_kwargs = feedparser.parse(the_url) valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2) PyRSS2Gen.RSS2(**valid_kwargs) I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: **Is there a way to programatically list the keyword arguments the a specific function takes?** Answer: A little nicer than inspecting the code object directly and working out the variables is to use the inspect module. >>> import inspect >>> def func(a,b,c=42, *args, **kwargs): pass >>> inspect.getargspec(func) (['a', 'b', 'c'], 'args', 'kwargs', (42,)) If you want to know if its callable with a particular set of args, you need the args without a default already specified. These can be got by: def getRequiredArgs(func): args, varargs, varkw, defaults = inspect.getargspec(func) if defaults: args = args[:-len(defaults)] return args # *args and **kwargs are not required, so ignore them. Then a function to tell what you are missing from your particular dict is: def missingArgs(func, argdict): return set(getRequiredArgs(func)).difference(argdict) Similarly, to check for invalid args, use: def invalidArgs(func, argdict): args, varargs, varkw, defaults = inspect.getargspec(func) if varkw: return set() # All accepted return set(argdict) - set(args) And so a full test if it is callable is : def isCallableWithArgs(func, argdict): return not missingArgs(func, argdict) and not invalidArgs(func, argdict) (This is good only as far as python's arg parsing. Any runtime checks for invalid values in kwargs obviously can't be detected.)
Design question: How can I access an IPC mechanism transparently? Question: I want to do this (no particular language): print(foo.objects.bookdb.books[12].title); or this: book = foo.objects.bookdb.book.new(); book.title = 'RPC for Dummies'; book.save(); Where foo actually is a service connected to my program via some IPC, and to access its methods and objects, some layer actually sends and receives messages over the network. Now, I'm not really looking for an IPC mechanism, as there are plenty to choose from. It's likely not to be XML based, but rather s. th. like Google's protocol buffers, dbus or CORBA. What I'm unsure about is how to structure the application so I can access the IPC just like I would any object. In other words, how can I have OOP that maps transparently over process boundaries? Not that this is a design question and I'm still working at a pretty high level of the overall architecture. So I'm pretty agnostic yet about which language this is going to be in. C#, Java and Python are all likely to get used, though. Answer: I think the way to do what you are requesting is to have all object communication regarded as message passing. This is how object methods are handled in ruby and smalltalk, among others. With message passing (rather than method calling) as your object communication mechanism, then operations such as calling a method that didn't exist when you wrote the code becomes sensible as the object can do something sensible with the message anyway (check for a remote procedure, return a value for a field with the same name from a database, etc, or throw a 'method not found' exception, or anything else you could think of). It's important to note that for languages that don't use this as a default mechanism, you can do message passing anyway (every object has a 'handleMessage' method) but you won't get the syntax niceties, and you won't be able to get IDE help without some extra effort on your part to get the IDE to parse your handleMessage method to check for valid inputs.
Is there any way to get python omnicomplete to work with non-system modules in vim? Question: The only thing I can get python omnicomplete to work with are system modules. I get nothing for help with modules in my site-packages or modules that I'm currently working on. Answer: Once I generated ctags for one of my site-packages, it started working for that package -- so I'm guessing that the omnicomplete function depends on ctags for non-sys modules. EDIT: Not true at all. Here's the problem -- poor testing on my part -- omnicomplete WAS working for parts of my project, just not most of it. The issue was that I'm working on a django project, and in order to import django.db, you need to have an environment variable set. Since I couldn't import django.db, any class that inherited from django.db, or any module that imported a class that inherited from django.db wouldn't complete.
extracting a parenthesized Python expression from a string Question: I've been wondering about how hard it would be to write some Python code to search a string for the index of a substring of the form `${`_expr_`}`, for example, where _expr_ is meant to be a Python expression or something resembling one. Given such a thing, one could easily imagine going on to check the expression's syntax with `compile()`, evaluate it against a particular scope with `eval()`, and perhaps even substitute the result into the original string. People must do very similar things all the time. I could imagine solving such a problem using a third-party parser generator [oof], or by hand-coding some sort of state machine [eek], or perhaps by convincing Python's own parser to do the heavy lifting somehow [hmm]. Maybe there's a third-party templating library somewhere that can be made to do exactly this. Maybe restricting the syntax of _expr_ is likely to be a worthwhile compromise in terms of simplicity or execution time or cutting down on external dependencies -- for example, maybe all I really need is something that matches any _expr_ that has balanced curly braces. What's your sense? ## Update: Thanks very much for your responses so far! Looking back at what I wrote yesterday, I'm not sure I was sufficiently clear about what I'm asking. Template substitution is indeed an interesting problem, and probably much more useful to many more people than the expression extraction subproblem I'm wondering about, but I brought it up only as a simple example of how the answer to my question might be useful in real life. Some other potential applications might include passing the extracted expressions to a syntax highlighter; passing the result to a real Python parser and looking at or monkeying with the parse tree; or using the sequence of extracted expressions to build up a larger Python program, perhaps in conjunction with some information taken from the surrounding text. The `${`_expr_`}` syntax I mentioned is also intended as an example, and in fact I wonder if I shouldn't have used `$(`_expr_`)` as my example instead, because it makes the potential drawbacks of the obvious approach, along the lines of `re.finditer(r'$\{([^}]+)\}', s)`, a bit easier to see. Python expressions can (and often do) contain the `)` (or `}`) character. It seems possible that handling any of those cases might be much more trouble than it's worth, but I'm not convinced of that yet. Please feel free to try to make this case! Prior to posting this question, I spent quite a bit of time looking at Python template engines hoping that one might expose the sort of low-level functionality I'm asking about -- namely, something that can find expressions in a variety of contexts and tell me where they are rather than being limited to finding expressions embedded using a single hard-coded syntax, always evaluating them, and always substituting the results back into the original string. I haven't figured out how to use any of them to solve my problem yet, but I do very much appreciate the suggestions regarding more to look at (can't believe I missed that wonderful list on the wiki!). The API documentation for these things tends to be pretty high-level, and I'm not too familiar with the internals of any of them, so I'm sure I could use help looking at those and figuring out how to get them to do this sort of thing. Thanks for your patience! Answer: I think what you're asking about is being able to insert Python code into text files to be evaluated. There are several modules that already exist to provide this kind of functionality. You can check the Python.org [**Templating wiki page**](http://wiki.python.org/moin/Templating) for a comprehensive list. Some google searching also turned up a few other modules you might be interested in: * [texttemplate](http://py-templates.sourceforge.net/texttemplate/index.html) (part of py-templates project) * [template module](http://www.embl-heidelberg.de/~chenna/pythonpages/template.html) If you're really looking just into writing this yourself for whatever reason, you can also dig into this Python cookbook solution [Yet Another Python Templating Utility (YAPTU) ](http://code.activestate.com/recipes/52305/): > _"Templating" (copying an input file to output, on the fly inserting Python > expressions and statements) is a frequent need, and YAPTU is a small but > complete Python module for that; expressions and statements are identified > by arbitrary user-chosen regular-expressions._ **EDIT** : Just for the heck of it, I whipped up a severely simplistic code sample for this. I'm sure it has bugs but it illustrates a simplified version of the concept at least: #!/usr/bin/env python import sys import re FILE = sys.argv[1] handle = open(FILE) fcontent = handle.read() handle.close() for myexpr in re.finditer(r'\${([^}]+)}', fcontent, re.M|re.S): text = myexpr.group(1) try: exec text except SyntaxError: print "ERROR: unable to compile expression '%s'" % (text) Tested against the following text: This is some random text, with embedded python like ${print "foo"} and some bogus python like ${any:thing}. And a multiline statement, just for kicks: ${ def multiline_stmt(foo): print foo multiline_stmt("ahem") } More text here. Output: [user@host]$ ./exec_embedded_python.py test.txt foo ERROR: unable to compile expression 'any:thing' ahem
Python's __import__ doesn't work as expected Question: When using `__import__` with a dotted name, something like: `somepackage.somemodule`, the module returned isn't `somemodule`, whatever is returned seems to be mostly empty! what's going on here? Answer: From the python docs on `__import__`: > > __import__( name[, globals[, locals[, fromlist[, level]]]]) > > > ... > > When the name variable is of the form package.module, normally, the top- > level package (the name up till the first dot) is returned, not the module > named by name. However, when a non-empty fromlist argument is given, the > module named by name is returned. This is done for compatibility with the > bytecode generated for the different kinds of import statement; when using > "import spam.ham.eggs", the top-level package spam must be placed in the > importing namespace, but when using "from spam.ham import eggs", the > spam.ham subpackage must be used to find the eggs variable. As a workaround > for this behavior, use getattr() to extract the desired components. For > example, you could define the following helper: > > > def my_import(name): > mod = __import__(name) > components = name.split('.') > for comp in components[1:]: > mod = getattr(mod, comp) > return mod > **To paraphrase:** When you ask for `somepackage.somemodule`, `__import__` returns `somepackage.__init__.py`, which is often empty. It will return `somemodule` if you provide `fromlist` (a list of the variable names inside `somemodule` you want, which are not actually returned) You can also, as I did, use the function they suggest. Note: I asked this question fully intending to answer it myself. There was a big bug in my code, and having misdiagnosed it, it took me a long time to figure it out, so I figured I'd help the SO community out and post the gotcha I ran into here.
Python Inverse of a Matrix Question: How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it. Answer: You should have a look at [numpy](http://www.scipy.org/Tentative_NumPy_Tutorial) if you do matrix manipulation. This is a module mainly written in C, which will be much faster than programming in pure python. Here is an example of how to invert a matrix, and do other matrix manipulation. from numpy import matrix from numpy import linalg A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix. x = matrix( [[1],[2],[3]] ) # Creates a matrix (like a column vector). y = matrix( [[1,2,3]] ) # Creates a matrix (like a row vector). print A.T # Transpose of A. print A*x # Matrix multiplication of A and x. print A.I # Inverse of A. print linalg.solve(A, x) # Solve the linear equation system. You can also have a look at the [array](http://www.python.org/doc/2.5.2/lib/module-array.html) module, which is a much more efficient implementation of lists when you have to deal with only one data type.
how to generate unit test code for methods Question: i want to write code for unit test to test my application code. I have different methods and now want to test these methods one by one in python script. but i do not how to i write. can any one give me example of small code for unit testing in python. i am thankful Answer: Read the [unit testing framework section](http://www.python.org/doc/2.5.2/lib/module-unittest.html) of the [Python Library Reference](http://www.python.org/doc/2.5.2/lib/lib.html). A [basic example](http://www.python.org/doc/2.5.2/lib/minimal-example.html) from the documentation: import random import unittest class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = range(10) def testshuffle(self): # make sure the shuffled sequence does not lose any elements random.shuffle(self.seq) self.seq.sort() self.assertEqual(self.seq, range(10)) def testchoice(self): element = random.choice(self.seq) self.assert_(element in self.seq) def testsample(self): self.assertRaises(ValueError, random.sample, self.seq, 20) for element in random.sample(self.seq, 5): self.assert_(element in self.seq) if __name__ == '__main__': unittest.main()
How Python web frameworks, WSGI and CGI fit together Question: I have a [Bluehost](http://en.wikipedia.org/wiki/Bluehost) account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in `.htaccess`: Options +ExecCGI AddType text/html py AddHandler cgi-script .py Now, whenever I look up web programming with Python, I hear a lot about WSGI and how most frameworks use it. But I just don't understand how it all fits together, especially when my web server is given (Apache running at a host's machine) and not something I can really play with (except defining `.htaccess` commands). How are [WSGI](http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface), CGI, and the frameworks all connected? What do I need to know, install, and do if I want to run a web framework (say [web.py](http://webpy.org/) or [CherryPy](http://en.wikipedia.org/wiki/CherryPy)) on my basic CGI configuration? How to install WSGI support? Answer: **How WSGI, CGI, and the frameworks are all connected ?** Apache listens on port 80. It gets an HTTP request. It parses the request to find a way to respond. Apache has a LOT of choices for responding. One way to respond is to use CGI to run a script. Another way to respond is to simply serve a file. In the case of CGI, Apache prepares an environment and invokes the script through the CGI protocol. This is a standard Unix Fork/Exec situation -- the CGI subprocess inherits an OS environment including the socket and stdout. The CGI subprocess writes a response, which goes back to Apache; Apache sends this response to the browser. CGI is primitive and annoying. Mostly because it forks a subprocess for every request, and subprocess must exit or close stdout and stderr to signify end of response. WSGI is an interface that is based on the CGI design pattern. It is not necessarily CGI -- it does not have to fork a subprocess for each request. It can be CGI, but it doesn't have to be. WSGI adds to the CGI design pattern in several important ways. It parses the HTTP Request Headers for you and adds these to the environment. It supplies any POST-oriented input as a file-like object in the environment. It also provides you a function that will formulate the response, saving you from a lot of formatting details. **What do I need to know / install / do if I want to run a web framework (say web.py or cherrypy) on my basic CGI configuration ?** Recall that forking a subprocess is expensive. There are two ways to work around this. 1. **Embedded** `mod_wsgi` or `mod_python` embeds Python inside Apache; no process is forked. Apache runs the Django application directly. 2. **Daemon** `mod_wsgi` or `mod_fastcgi` allows Apache to interact with a separate daemon (or "long-running process"), using the WSGI protocol. You start your long-running Django process, then you configure Apache's mod_fastcgi to communicate with this process. Note that `mod_wsgi` can work in either mode: embedded or daemon. When you read up on mod_fastcgi, you'll see that Django uses [flup](http://pypi.python.org/pypi/flup/) to create a WSGI-compatible interface from the information provided by mod_fastcgi. The pipeline works like this. Apache -> mod_fastcgi -> FLUP (via FastCGI protocol) -> Django (via WSGI protocol) Django has several "django.core.handlers" for the various interfaces. For mod_fastcgi, Django provides a `manage.py runfcgi` that integrates FLUP and the handler. For mod_wsgi, there's a core handler for this. **How to install WSGI support ?** Follow these instructions. <http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango> For background see this <http://docs.djangoproject.com/en/dev/howto/deployment/#howto-deployment- index>
How to script Visual Studio 2008 from Python? Question: I'd like to write Python scripts that drive Visual Studio 2008 and Visual C++ 2008. All the examples I've found so far use `win32com.client.Dispatch`. This works fine for Excel 2007 and Word 2007 but fails for Visual Studio 2008: import win32com.client app1 = win32com.client.Dispatch( 'Excel.Application' ) # ok app2 = win32com.client.Dispatch( 'Word.Application' ) # ok app3 = win32com.client.Dispatch( 'MSDev.Application' ) # error Any ideas? Does Visual Studio 2008 use a different string to identify itself? Is the above method out-dated? Answer: Depending on what exactly you're trying to do, [AutoIt](http://www.autoitscript.com/autoit3/index.shtml) may meet your needs. In fact, I'm sure it will do anything you need it to do. Taken from my [other post](http://stackoverflow.com/questions/151846/get- other-running-processes-window-sizes-in-python#155587) about how to use AutoIt with Python: import win32com.client oAutoItX = win32com.client.Dispatch( "AutoItX3.Control" ) oAutoItX.Opt("WinTitleMatchMode", 2) #Match text anywhere in a window title width = oAutoItX.WinGetClientSizeWidth("Firefox") height = oAutoItX.WinGetClientSizeHeight("Firefox") print width, height You can of course use any of the [AutoItX functions](http://www.autoitscript.com/autoit3/docs/functions.htm) (note that that link goes to the AutoIt function reference, the com version of AutoIt - AutoItX has a subset of that list...the documentation is included in the download) in this way. I don't know what you're wanting to do, so I can't point you towards the appropriate functions, but this should get you started.
Incoming poplib refactoring using windows python 2.3 Question: Hi Guys could you please help me refactor this so that it is sensibly pythonic. import sys import poplib import string import StringIO, rfc822 import datetime import logging def _dump_pop_emails(self): self.logger.info("open pop account %s with username: %s" % (self.account[0], self.account[1])) self.popinstance = poplib.POP3(self.account[0]) self.logger.info(self.popinstance.getwelcome()) self.popinstance.user(self.account[1]) self.popinstance.pass_(self.account[2]) try: (numMsgs, totalSize) = self.popinstance.stat() for thisNum in range(1, numMsgs+1): (server_msg, body, octets) = self.popinstance.retr(thisNum) text = string.join(body, '\n') mesg = StringIO.StringIO(text) msg = rfc822.Message(mesg) name, email = msg.getaddr("From") emailpath = str(self._emailpath + self._inboxfolder + "\\" + email + "_" + msg.getheader("Subject") + ".eml") emailpath = self._replace_whitespace(emailpath) file = open(emailpath,"wb") file.write(text) file.close() self.popinstance.dele(thisNum) finally: self.logger.info(self.popinstance.quit()) def _replace_whitespace(self,name): name = str(name) return name.replace(" ", "_") Also in the _replace_whitespace method I would like to have some kind of cleaning routine which takes out all illegal characters which could cause processing. Basically I want to write the email to the inbox directory in a standard way. Am i doing something wrong here? Answer: I don't see anything significant wrong with that code -- is it behaving incorrectly, or are you just looking for general style guidelines? A few notes: 1. Instead of `logger.info ("foo %s %s" % (bar, baz))`, use `"foo %s %s", bar, baz`. This avoids the overhead of string formatting if the message won't be printed. 2. Put a `try...finally` around opening `emailpath`. 3. Use `'\n'.join (body)`, instead of `string.join (body, '\n')`. 4. Instead of `msg.getaddr("From")`, just `msg.From`.
How do I iterate through a string in Python? Question: As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it? This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python. def alphCount(text): lowerText = text.lower() for letter in allTheLetters: print letter + ":", lowertext.count(letter) Answer: The question you've asked (how to iterate through the alphabet) is not the same question as the problem you're trying to solve (how to count the frequency of letters in a string). You can use string.lowercase, as other posters have suggested: import string allTheLetters = string.lowercase To do things the way you're "used to", treating letters as numbers, you can use the "ord" and "chr" functions. There's absolutely no reason to ever do exactly this, but maybe it comes closer to what you're actually trying to figure out: def getAllTheLetters(begin='a', end='z'): beginNum = ord(begin) endNum = ord(end) for number in xrange(beginNum, endNum+1): yield chr(number) You can tell it does the right thing because this code prints `True`: import string print ''.join(getAllTheLetters()) == string.lowercase But, to solve the problem you're actually trying to solve, you want to use a dictionary and collect the letters as you go: from collections import defaultdict def letterOccurrances(string): frequencies = defaultdict(lambda: 0) for character in string: frequencies[character.lower()] += 1 return frequencies Use like so: occs = letterOccurrances("Hello, world!") print occs['l'] print occs['h'] This will print '3' and '1' respectively. Note that this works for unicode as well: # -*- coding: utf-8 -*- occs = letterOccurrances(u"héĺĺó, ẃóŕĺd!") print occs[u'l'] print occs[u'ĺ'] If you were to try the other approach on unicode (incrementing through every character) you'd be waiting a long time; there are millions of unicode characters. To implement your original function (print the counts of each letter in alphabetical order) in terms of this: def alphCount(text): for character, count in sorted(letterOccurrances(text).iteritems()): print "%s: %s" % (character, count) alphCount("hello, world!")
Cannot import SQLite with Python 2.6 Question: I'm running Python 2.6 on Unix and when I run the interactive prompt ([SQLite](http://en.wikipedia.org/wiki/SQLite) is supposed to be preinstalled) I get: [root@idev htdocs]# python Python 2.6 (r26:66714, Oct 23 2008, 16:25:34) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named sqlite >>> How do I resolve this? Answer: The error: ImportError: No module named _sqlite3 means that [SQLite](http://en.wikipedia.org/wiki/SQLite) 3 does not find the associated shared library. On Mac OS X it's _sqlite3.so and it should be the same on other Unix systems. To resolve the error you have to locate the _sqlite3.so library on your computer and then check your PYTHONPATH for this directory location. To print the Python search path enter the following in the Python shell: import sys print sys.path If the directory containing your library is missing you can try adding it interactively with sys.path.append('/your/dir/here') and try import sqlite3 again. If this works you have to add this directory permanently to your PYTHONPATH environment variable. PS: If the library is missing you should (re-)install the module.
How can I call a DLL from a scripting language? Question: I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth). I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Perl) so that we don't have to compile and send out executables to our customers whenever there's a problem found. We also want the customers to be able to write their own scripts using ours as baselines and they won't entertain the idea of writing and compiling C code. What's a good way of getting Python/Perl to interface to a Windows DLL. My first thought was to write a server program and have a Python script communicate with it via TCP but there's got to be an easier solution. Answer: One way to call C libraries from Python is to use [ctypes](https://docs.python.org/library/ctypes.html): >>> from ctypes import * >>> windll.user32.MessageBoxA(None, "Hello world", "ctypes", 0);
Retrieving python module path Question: 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? Answer: 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.
Is it possible to communicate with a sub subprocess with subprocess.Popen? Question: I'm trying to write a python script that packages our software. This script needs to build our product, and package it. Currently we have other scripts that do each piece individually which include csh, and perl scripts. One such script is run like: sudo mod args where mod is a perl script; so in python I would do proc = Popen(['sudo', 'mod', '-p', '-c', 'noresource', '-u', 'dtt', '-Q'], stderr=PIPE, stdout=PIPE, stdin=PIPE) The problem is that this mod script needs a few questions answered. For this I thought that the traditional (stdout, stderr) = proc.communicate(input='y') would work. I don't think it's working because the process that Popen is controlling is sudo, not the mod script that is asking the question. Is there any way to communicate with the mod script and still run it through sudo? Answer: I would choose to go with Pexpect. import pexpect child = pexpect.spawn ('sudo mod -p -c noresource -u dtt -Q') child.expect ('First question:') child.sendline ('Y') child.expect ('Second question:') child.sendline ('Yup')
In Python, is there a concise way of comparing whether the contents of two text files are the same? Question: I don't care what the differences are. I just want to know whether the contents are different. Answer: 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): ...
Python vs Groovy vs Ruby? (based on criteria listed in question) Question: Considering the criteria listed below, which of Python, Groovy or Ruby would you use? * _Criteria (Importance out of 10, 10 being most important)_ * Richness of API/libraries available (eg. maths, plotting, networking) (9) * Ability to embed in desktop (java/c++) applications (8) * Ease of deployment (8) * Ability to interface with DLLs/Shared Libraries (7) * Ability to generate GUIs (7) * Community/User support (6) * Portability (6) * Database manipulation (3) * Language/Semantics (2) Answer: I think it's going to be difficult to get an objective comparison. I personally prefer Python. To address one of your criteria, Python was designed from the start to be an embeddable language. It has a very rich C API, and the interpreter is modularized to make it easy to call from C. If Java is your host environment, you should look at Jython, an implementation of Python inside the Java environment (VM and libs).
How to build Python C extension modules with autotools Question: Most of the documentation available for building Python extension modules uses distutils, but I would like to achieve this by using the appropriate python autoconf & automake macros instead. I'd like to know if there is an open source project out there that does exactly this. Most of the ones I've found end up relying on a setup.py file. Using that approach works, but unfortunately ends up rebuilding the entire source tree any time I make a modification to the module source files. Answer: Supposing that you have a project with a directory called `src`, so let's follow the follow steps to get a python extension built and packaged using autotools: ## Create the Makefile.am files First, you need to create one Makefile.am in the root of your project, basically (but not exclusively) listing the subdirectories that should also be processed. You will end up with something like this: SUBDIRS = src The second one, inside the `src` directory will hold the instructions to actually compile your python extension. It will look like this: myextdir = $(pkgpythondir) myext_PYTHON = file1.py file2.py pyexec_LTLIBRARIES = _myext.la _myext_la_SOURCES = myext.cpp _myext_la_CPPFLAGS = $(PYTHON_CFLAGS) _myext_la_LDFLAGS = -module -avoid-version -export-symbols-regex initmyext _myext_la_LIBADD = $(top_builddir)/lib/libhollow.la EXTRA_DIST = myext.h ## Write the configure.ac This file must be created in the root directory of the project and must list all libraries, programs or any kind of tool that your project needs to be built, such as a compiler, linker, libraries, etc. Lazy people, like me, usually don't create it from scratch, I prefer to use the `autoscan` tool, that looks for things that you are using and generate a `configure.scan` file that can be used as the basis for your real `configure.ac`. To inform `automake` that you will need python stuff, you can add this to your `configure.ac`: dnl python checks (you can change the required python version bellow) AM_PATH_PYTHON(2.7.0) PY_PREFIX=`$PYTHON -c 'import sys ; print sys.prefix'` PYTHON_LIBS="-lpython$PYTHON_VERSION" PYTHON_CFLAGS="-I$PY_PREFIX/include/python$PYTHON_VERSION" AC_SUBST([PYTHON_LIBS]) AC_SUBST([PYTHON_CFLAGS]) ## Wrap up Basically, `automake` has a built-in extension that knows how to deal with python stuff, you just need to add it to your `configure.ac` file and then take the advantage of this feature in your `Makefile.am`. PyGtk is definitely an awesome example, but it's pretty big, so maybe you will want to check another project, like [Guake](http://github.com/Guake/Guake)
using jython and open office 2.4 to convert docs to pdf Question: I completed a python script using pyuno which successfully converted a document/ xls / rtf etc to a pdf. Then I needed to update a mssql database, due to open office currently supporting python 2.3, it's ancientness, lacks support for decent database libs. So I have resorted to using Jython, this way im not burdened down by running inside OO python environment using an old pyuno. This also means that my conversion code is broken, and I need to now make use of the java libraries instead of the pyuno libs. > import com.sun.star.beans.PropertyValue as PropertyValue > import com.sun.star.bridge.XUnoUrlResolver as XUnoUrlResolver > import com.sun.star.comp.helper.Bootstrap as Bootstrap > ->> import com.sun.star.frame.XComponentLoader as XComponentLoader > ->> import com.sun.star.frame.XStorable as XStorable > import com.sun.star.lang.XMultiComponentFactory as XMultiComponentFactory > import com.sun.star.uno.UnoRuntime as UnoRuntime > import com.sun.star.uno.XComponentContext as XComponentContext The includes with the '->>' do not import the compiler does not recognise the com.sun.star.frame cant see the 'frame' bit. These are the libs I have included. ![alt text](http://www.freeimagehosting.net/uploads/eda5cda76d.jpg) Some advice on this matter would be well received > context = XComponentContext > xMultiCompFactory = XMultiComponentFactory > xcomponentloader = XComponentLoader > > //used in python > ctx = None > smgr = None > doc = None > url = None > > context = Bootstrap.bootstrap() > xMultiCompFactory = self.context.getServiceManager() > xcomponentloader = UnoRuntime.queryInterface(XComponentLoader.class, > ....xMultiCompFactory.createInstanceWithContext("com.sun.star.frame.Desktop", > context)) > > file = "file:\\\" + file > // also what is the equivalent of url = uno.systemPathToFileUrl(file) in > Java so that I can make use of it to nicely format my path > properties = [] > p = PropertyValue() > p.Name = "Hidden" > p.Value = True > properties.append(p) > properties = tuple(properties) > doc = xcomponentloader.loadComponentFromURL(file, "_blank",0, properties) Answer: And so it goes, according to this guy, you need some oil.... and it works like a charm <http://www.oooforum.org/forum/viewtopic.phtml?p=304263#304263> include this lib C:\OpenOffice_24\program\classes\unoil.jar
HTTP Request Timeout Question: In Python 2.6, a new "timeout" parameter was added to the httplib.HTTPConnection class: <http://docs.python.org/library/httplib.html#httplib.HTTPConnection> However, this is only a timeout for the connection to a server. I am looking to set a timeout value for the **request** , not the connection. This doesn't seem to be supported by httplib. Is there any way to emulate this behavior? Answer: You can set a global socket timeout (*): import socket timeout = 10 socket.setdefaulttimeout(timeout) * * * (*) **EDIT** : As people in the comments correctly point out: This is technically true, but it only has predictable results for tasks that involve a single socket operation. An HTTP request consists of multiple socket operations (e.g. DNS requests or other things that might be abstracted away from an HTTP client). The timeout of the overall operation becomes unpredictable because of that.
Best way to strip punctuation from a string in Python Question: 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? Answer: 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
import mechanize module to python script Question: I tried to import mechanize module to my python script like this, from mechanize import Browser But, Google appengine throws HTTP 500 when accessing my script. To make things more clear, Let me give you the snapshot of my package structure, root ....mechanize(where all the mechanize related files there) ....main.py ....app.yaml ....image ....script Can anyone help me out to resolve this issue? Thanks, Ponmalar Answer: The mechanize main page says: > mechanize.Browser is a subclass of mechanize.UserAgentBase, which is, in > turn, a subclass of urllib2.OpenerDirector My understanding is that urllib2 is one of the sandboxed modules in GAE, with its functionality being replaced by the Google-provided urlfetch. You'd need to re-implement the mechanize.UserAgentBase class to use urlfetch, if that's at all possible.
Parse HTML via XPath Question: In .Net, I found this great library, [HtmlAgilityPack](http://www.codeplex.com/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? Answer: 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](http://codespeak.net/lxml/xpathxslt.html). >>> 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'
How to split a web address Question: So I'm using python to do some parsing of web pages and I want to split the full web address into two parts. Say I have the address <http://www.stackoverflow.com/questions/ask>. I would need the protocol and domain (e.g. <http://www.stackoverflow.com>) and the path (e.g. /questions/ask). I figured this might be solved by some regex, however I'm not so handy with that. Any suggestions? Answer: Dan is right: urlparse is your friend: >>> from urlparse import urlparse >>> >>> parts = urlparse("http://www.stackoverflow.com/questions/ask") >>> parts.scheme + "://" + parts.netloc 'http://www.stackoverflow.com' >>> parts.path '/questions/ask'
How do I find userid by login (Python under *NIX) Question: I need to set my process to run under 'nobody', I've found os.setuid(), but how do I find `uid` if I have `login`? I've found out that uids are in /etc/passwd, but maybe there is a more pythonic way than scanning /etc/passwd. Anybody? Answer: You might want to have a look at the [pwd](http://docs.python.org/library/pwd.html) module in the python stdlib, for example: import pwd pw = pwd.getpwnam("nobody") uid = pw.pw_uid it uses /etc/passwd (well, technically it uses the posix C API, so I suppose it might work on an OS if it didn't use /etc/passwd but exposed the needed functions) but is cleaner than parsing it manually
Pycurl WRITEDATA WRITEFUNCTION collision/crash Question: How do I turnoff WRITEFUNCTION and WRITEDATA? Using pycurl I have a class call curlUtil. In it I have pageAsString (self, URL) which returns a string. To do this I setopt WRITEFUNCTION. Now in downloadFile (self, URL, fn, overwrite=0) I do an open and self.c.Setopt (pycurl.WRITEFUNCTION, 0) which cause problems. Int is not a valid argument. I then assumed WRITEDATA would overwrite the value or there would be a NOWRITEFUNCTION commend. NOWRITEFUNCTION didn't exist so I just used WRITEDATA and Python crashed. I wrote a quick func called reboot() which closes curl, opens it again, and calls reset to put it in the default state. I call it in both pageAsString and downloadFile and there is no problem at all. But, I don't want to reinitialize curl. There might be some special options I set. How do I turnoff WRITEFUNCTION and WRITEDATA? Answer: using the writefunction, instead of turning it off would save you a lot off trouble. you might want to rewrite your pageAsString by utilizing WRITEFUNCTION.. as an example: from cStringIO import StringIO c = pycurl.Curl() buffer = StringIO() c.setopt(pycurl.WRITEFUNCTION, buffer.write) c.setopt(pycurl.URL, "http://example.com") c.perform() ... buffer.getvalue() # will return the data fetched.
Which is more efficient in Python: standard imports or contextual imports? Question: I apologize in advance if this question seems remedial. Which would be considered more efficient in Python: **Standard import** import logging try: ...some code... exception Exception, e: logging.error(e) ...or... **Contextual import** try: ...some code... exception Exception, e: import logging logging.error(e) Answer: Contextual imports are technically more efficient, but I think they can create other problems. Later, if you want to add a similar except clause, you now have two places to maintain the same block of code. You also now have the problem of testing the exception, to make sure that the first import doesn't cause any unforeseen issues in your code.
How do I remove/delete a folder that is not empty with Python? Question: I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: `os.remove("/folder_name")`. What is the most effective way of removing/deleting a folder/directory that is not empty? Answer: import shutil shutil.rmtree('/folder_name') [Standard Library Reference: shutil.rmtree](http://docs.python.org/library/shutil.html#shutil.rmtree).
Is there a better StringCollection editor for use in PropertyGrids? Question: I'm making heavy use of PropertySheets in my application framework's configuration editor. I like them a lot because it's pretty easy to work with them (once you learn how) and make the editing bulletproof. One of the things that I'm storing in my configuration are Python scripts. It's possible to edit a Python script in a StringCollection editor, which is what I've been using, but there's a long distance between "possible" and "useable." I'd like to have an editor that actually supported resizeable and monospace fonts, preserved blank lines, and - hey, let's go crazy with the wishlist - did syntax coloring. I can certainly write this if I really have to, but I'd prefer not to. I've poked around on the Google and can't find anything like what I'm describing, so I thought I'd ask here. Is this a solved problem? Has anyone out there already taken a crack at building a better editor? Answer: You can create your own string collection editor easily, following these simple steps. _This example uses C#._ 1) You must create an editor control and derive it from `System.Drawing.Design.UITypeEditor`. I called mine `StringArrayEditor`. Thus my class starts with public class StringArrayEditor : System.Drawing.Design.UITypeEditor The `PropertyGrid` control needs to know that the editor is modal and it will show the ellipses button when the property in question is selected. So you must override `GetEditStyle` as follows: public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } Lastly the editor control must override the `EditValue` operation so that it knows how you want to proceed when the user clicks on the ellipses button for your property. Here is the full code for the override: public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { var editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; if (editorService != null) { var selectionControl = new TextArrayPropertyForm((string[])value, "Edit the lines of text", "Label Editor"); editorService.ShowDialog(selectionControl); if (selectionControl.DialogResult == DialogResult.OK) value = selectionControl.Value; } return value ?? new string[] {}; } So what is happening? When the user clicks on the ellipses, this override is called. `editorService` is set as the interface for our editing form. It is set to the form which we haven't yet created that I call `TextArrayPropertyForm`. `TextArrayPropertyForm` is instantiated, passing the value to be edited. For good measure I am also passing 2 strings, one for the form title and the other for a label at the top explaining what the user should do. It is shown modally and if the OK button was clicked then the value is updated with whatever the value was set in `selectionControl.Value` from the form we will create. Finally this value is returned at the end of the override. Step 2) Create the editor form. In my case I created a form with 2 Buttons (`buttonOK` and `buttonCancel`) a Label (`labelInstructions`) and a TextBox (`textValue`) to mimic the default StringCollection editor. The code is pretty straight-forward, but in case you're interested, here it is. using System; using System.Windows.Forms; namespace MyNamespace { /// <summary> /// Alternate form for editing string arrays in PropertyGrid control /// </summary> public partial class TextArrayPropertyForm : Form { public TextArrayPropertyForm(string[] value, string instructions = "Enter the strings in the collection (one per line):", string title = "String Collection Editor") { InitializeComponent(); Value = value; textValue.Text = string.Join("\r\n", value); labelInstructions.Text = instructions; Text = title; } public string[] Value; private void buttonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; } private void buttonOK_Click(object sender, EventArgs e) { Value = textValue.Text.Split(new[] { "\r\n" }, StringSplitOptions.None); DialogResult = DialogResult.OK; } } } Step 3)Tell the PropertyGrid to use the alternate editor. The change between this property and any other that is used in the PropertyGrid control is the [Editor] line. [Description("The name or text to appear on the layout.")] [DisplayName("Text"), Browsable(true), Category("Design")] [Editor(typeof(StringArrayEditor), typeof(System.Drawing.Design.UITypeEditor))] public string[] Text {get; set;} Now when you create a PropertyGrid on a form and set to the class containing this Text property it will edit in your custom made form. There are countless opportunities to change your custom form in ways you choose. With modifications this will work for editing any type you like. The important thing is that the editor control returns the same type as is the property in the overridden `EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)` Hope this helps!
Python decorator makes function forget that it belongs to a class Question: I am trying to write a decorator to do logging: def logger(myFunc): def new(*args, **keyargs): print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__) return myFunc(*args, **keyargs) return new class C(object): @logger def f(): pass C().f() I would like this to print: Entering C.f but instead I get this error message: AttributeError: 'function' object has no attribute 'im_class' Presumably this is something to do with the scope of 'myFunc' inside 'logger', but I've no idea what. Answer: Claudiu's answer is correct, but you can also cheat by getting the class name off of the `self` argument. This will give misleading log statements in cases of inheritance, but will tell you the class of the object whose method is being called. For example: from functools import wraps # use this to preserve function signatures and docstrings def logger(func): @wraps(func) def with_logging(*args, **kwargs): print "Entering %s.%s" % (args[0].__class__.__name__, func.__name__) return func(*args, **kwargs) return with_logging class C(object): @logger def f(self): pass C().f() As I said, this won't work properly in cases where you've inherited a function from a parent class; in this case you might say class B(C): pass b = B() b.f() and get the message `Entering B.f` where you actually want to get the message `Entering C.f` since that's the correct class. On the other hand, this might be acceptable, in which case I'd recommend this approach over Claudiu's suggestion.
How do I randomly select an item from a list using Python? Question: Assume I have the following list: foo = ['a', 'b', 'c', 'd', 'e'] What is the simplest way to retrieve an item at random from this list? Answer: Use [`random.choice`](https://docs.python.org/2/library/random.html#random.choice): import random foo = ['a', 'b', 'c', 'd', 'e'] print(random.choice(foo))
How can I dynamically get the set of classes from the current python module? Question: I have a python module that defines a number of classes: class A(object): def __call__(self): print "ran a" class B(object): def __call__(self): print "ran b" class C(object): def __call__(self): print "ran c" From within the module, how might I add an attribute that gives me all of the classes? dir() gives me the names of everything from within my module, but I can't seem to figure out how to go from the name of a class to the class itself from _within_ the module. From outside of the module, I can simply use `getattr(mod, 'A')`, but I don't have a `self` kind of module from within the module itself. This seems pretty obvious. Can someone tell me what I'm missing? Answer: import sys getattr(sys.modules[__name__], 'A')
Need skeleton code to call Excel VBA from PythonWin Question: I need to invoke a VBA macro within an Excel workbook from a python script. Someone else has provided the Excel workbook with the macro. The macro grabs updated values from an external database, and performs some fairly complex massaging of the data. I need the results from this massaging, and I don't really want to duplicate this in my Python script, if I can avoid it. So, it would be great if I could just invoke the macro from my script, and grab the massaged results. Everything I know about COM I learned from "Python Programming on Win32". Good book, but not enough for my task at hand. I searched, but haven't found any good examples on how to do this. Does anyone have any good examples, or perhaps some skeleton code of how to address/invoke the VBA macro? A general reference (book, web link, etc) on the Excel COM interfaces would also help here. Thanks. Answer: OK, I got it! Thanks for the help on the Application.Run method. This info, plus the "Microsoft Excel Visual Basic Reference": <http://msdn.microsoft.com/en-us/library/aa209782(office.10).aspx>\--as recommended by Hammond & Robinson in "Python Programming on Win32"--was what was needed. Here's the skeleton code: import win32com.client xl=win32com.client.Dispatch("Excel.Application") xl.Workbooks.Open(Filename="<your Excel File>",ReadOnly=1) xl.Application.Run("<your macro name>") #...access spreadsheet data... xl.Workbooks(1).Close(SaveChanges=0) xl.Application.Quit() xl=0
Why are .Net programmers so afraid of exceptions? Question: First of all, I'm not trying to be critical of anyone here or saying that all .Net programmers are this way. But I'm definitely noticing a trend: .Net programmers seem to avoid exceptions like they're the plague. Of course, there's always the [Raymond Chen](http://blogs.msdn.com/oldnewthing/archive/2004/04/22/118161.aspx) blog post about how hard exceptions can be to handle. But that doesn't just apply to .Net. In a lot of other languages/environments, I don't notice that programmers are as likely to avoid exceptions as they are in .Net. Heck, in Python, exceptions are thrown in normal program execution (iterators throw StopIteration exceptions). So what am I missing here? Or am I totally off base in thinking that .net programmers avoid exceptions more than others? Answer: Performance is the fear monger's buzzword when it comes to exceptions - but that really only applies to throwing them or handling them in tight loops, or for when relying on them for control flow. Personally I see exceptions as another tool in my toolbox; I'm not scared of them at all. Ideally when you use exceptions you're using them in exceptional circumstances - that is, should no longer be concerned with performance, but rather with fixing the problem (rare) or failing fast and notifying the user / logging / etc. Edit: JaredPar mentioned a great quote regarding this that I feel is important enough to repeat: "If you're worried about Exception performance, you're using them incorrectly." Once we find attribution I'll amend this post to include it.
A small question about python's variable scope Question: I am a beginner of python and have a question, very confusing for me. If I define a function first but within the function I have to use a variable which is defined in another function below, can I do it like this? Or how can I import the return things of another function into a function? for example: def hello(x,y): good=hi(iy,ix) "then do somethings,and use the parameter'good'." return something def hi(iy,ix): "code" return good Answer: The scope of functions `hello` and `hi` are entirely different. They do not have any variables in common. Note that the result of calling `hi(x,y)` is some object. You save that object with the name `good` in the function `hello`. The variable named `good` in `hello` is a different variable, unrelated to the variable named `good` in the function `hi`. They're spelled the same, but the exist in different namespaces. To prove this, change the spelling the `good` variable in one of the two functions, you'll see that things still work. * * * Edit. Follow-up: "so what should i do if i want use the result of `hi` function in `hello` function?" Nothing unusual. Look at `hello` closely. def hello(x,y): fordf150 = hi(y,x) "then do somethings,and use the variable 'fordf150'." return something def hi( ix, iy ): "compute some value, good." return good Some script evaluates `hello( 2, 3)`. 1. Python creates a new namespace for the evaluation of `hello`. 2. In `hello`, `x` is bound to the object `2`. Binding is done position order. 3. In `hello`, `y` is bound to the object `3`. 4. In `hello`, Python evaluates the first statement, `fordf150 = hi( y, x )`, `y` is 3, `x` is 2. a. Python creates a new namespace for the evaluation of `hi`. b. In `hi`, `ix` is bound to the object `3`. Binding is done position order. c. In `hi`, `iy` is bound to the object `2`. d. In `hi`, something happens and `good` is bound to some object, say `3.1415926`. e. In `hi`, a `return` is executed; identifying an object as the value for `hi`. In this case, the object is named by `good` and is the object `3.1415926`. f. The `hi` namespace is discarded. `good`, `ix` and `iy` vanish. The object (`3.1415926`), however, remains as the value of evaluating `hi`. 5. In `hello`, Python finishes the first statement, `fordf150 = hi( y, x )`, `y` is 3, `x` is 2. The value of `hi` is `3.1415926`. a. `fordf150` is bound to the object created by evaluating `hi`, `3.1415926`. 6. In `hello`, Python moves on to other statements. 7. At some point `something` is bound to an object, say, `2.718281828459045`. 8. In `hello`, a `return` is executed; identifying an object as the value for `hello`. In this case, the object is named by `something` and is the object `2.718281828459045 `. 9. The namespace is discarded. `fordf150` and `something` vanish, as do `x` and `y`. The object (`2.718281828459045 `), however, remains as the value of evaluating `hello`. Whatever program or script called `hello` gets the answer.
How to organize python test in a way that I can run all tests in a single command? Question: Currently my code is organized in the following tree structure: src/ module1.py module2.py test_module1.py test_module2.py subpackage1/ __init__.py moduleA.py moduleB.py test_moduleA.py test_moduleB.py Where the `module*.py` files contains the source code and the `test_module*.py` contains the `TestCase`s for the relevant module. With the following comands I can run the tests contained in a single file, for example: $ cd src $ nosetests test_filesystem.py .................. ---------------------------------------------------------------------- Ran 18 tests in 0.390s OK How can I run all tests? I tried with `nosetests -m 'test_.*'` but it doesn't work. $cd src $ nosetests -m 'test_.*' ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK Thanks Answer: Whether you seperate or mix tests and modules is probably a matter of taste, although I would strongly advocate for keeping them apart (setup reasons, code stats etc). When you're using nosetests, make sure that all directories with tests are real packages: src/ module1.py module2.py subpackage1/ __init__.py moduleA.py moduleB.py tests/ __init__.py test_module1.py test_module2.py subpackage1/ __init__.py test_moduleA.py test_moduleB.py This way, you can just run `nosetests` in the toplevel directory and all tests will be found. You need to make sure that `src/` is on the `PYTHONPATH`, however, otherwise all the tests will fail due to missing imports.
Finding the Current Active Window in Mac OS X using Python Question: Is there a way to find the application name of the current active window at a given time on Mac OS X using Python? Answer: This should work: #!/usr/bin/python from AppKit import NSWorkspace activeAppName = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName'] print activeAppName Only works on Leopard, or on Tiger if you have PyObjC installed and happen to point at the right python binary in line one (not the case if you've installed universal MacPython, which you'd probably want to do on Tiger). But Peter's answer with the Carbon way of doing this will probably be quite a bit faster, since importing anything from AppKit in Python takes a while, or more accurately, importing something from AppKit for the first time in a Python process takes a while. If you need this inside a PyObjC app, what I describe will work great and fast, since you only experience the lag of importing AppKit once. If you need this to work as a command-line tool, you'll notice the performance hit. If that's relevant to you, you're probably better off building a 10 line Foundation command line tool in Xcode using Peter's code as a starting point.
How do I create a wx.Image object from in-memory data? Question: I'm writing a GUI application in Python using wxPython and I want to display an image in a static control (`wx.StaticBitmap`). I can use [`wx.ImageFromStream`](http://www.wxpython.org/docs/api/wx- module.html#ImageFromStream) to load an image from a file, and this works OK: static_bitmap = wx.StaticBitmap(parent, wx.ID_ANY) f = open("test.jpg", "rb") image = wx.ImageFromStream(f) bitmap = wx.BitmapFromImage(image) static_bitmap.SetBitmap(bitmap) But, what I really want to be able to do is create the image from data in memory. So, if I write f = open("test.jpg", "rb") data = f.read() how can I create a `wx.Image` object from `data`? Thanks for your help! Answer: You should be able to use `StringIO` to wrap the buffer in a memory file object. ... import StringIO buf = open("test.jpg", "rb").read() # buf = get_image_data() sbuf = StringIO.StringIO(buf) image = wx.ImageFromStream(sbuf) ... `buf` can be replaced with any data string.
Python: single instance of program Question: Is there a Pythonic way to have only one instance of a program running? The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? (Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work) **Update** : the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one. Answer: The following code should do the job, it is cross-platform and runs on Python 2.4-3.2. I tested it on Windows, OS X and Linux. from tendo import singleton me = singleton.SingleInstance() # will sys.exit(-1) if other instance is running The latest code version is available [singleton.py](https://github.com/pycontribs/tendo/blob/master/tendo/singleton.py). Please [file bugs here](https://github.com/pycontribs/tendo/issues). You can install tend using one of the following methods: * `easy_install tendo` * `pip install tendo` * manually by getting it from <http://pypi.python.org/pypi/tendo>
Elegant ways to support equivalence ("equality") in Python classes Question: When writing custom classes it is often important to allow equivalence by means of the `==` and `!=` operators. In Python, this is made possible by implementing the `__eq__` and `__ne__` special methods, respectively. The easiest way I've found to do this is the following method: class Foo: def __init__(self, item): self.item = item def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False def __ne__(self, other): return not self.__eq__(other) Do you know of more elegant means of doing this? Do you know of any particular disadvantages to using the above method of comparing `__dict__`s? **Note** : A bit of clarification--when `__eq__` and `__ne__` are undefined, you'll find this behavior: >>> a = Foo(1) >>> b = Foo(1) >>> a is b False >>> a == b False That is, `a == b` evaluates to `False` because it really runs `a is b`, a test of identity (i.e., "Is `a` the same object as `b`?"). When `__eq__` and `__ne__` are defined, you'll find this behavior (which is the one we're after): >>> a = Foo(1) >>> b = Foo(1) >>> a is b False >>> a == b True Answer: You need to be careful with inheritance: >>> class Foo: def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False >>> class Bar(Foo):pass >>> b = Bar() >>> f = Foo() >>> f == b True >>> b == f False Check types more strictly, like this: def __eq__(self, other): if type(other) is type(self): return self.__dict__ == other.__dict__ return False Besides that, your approach will work fine, that's what special methods are there for.
wxPython and sharing objects between windows Question: I've been working with python for a while now and am just starting to learn wxPython. After creating a few little programs, I'm having difficulty understanding how to create objects that can be shared between dialogs. Here's some code as an example (apologies for the length - I've tried to trim): import wx class ExampleFrame(wx.Frame): """The main GUI""" def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(200,75)) mainSizer = wx.BoxSizer(wx.VERTICAL) # Setup buttons buttonSizer = wx.BoxSizer(wx.HORIZONTAL) playerButton = wx.Button(self, wx.ID_ANY, "Player number", wx.DefaultPosition, wx.DefaultSize, 0) buttonSizer.Add(playerButton, 1, wx.ALL | wx.EXPAND, 0) nameButton = wx.Button(self, wx.ID_ANY, "Player name", wx.DefaultPosition, wx.DefaultSize, 0) buttonSizer.Add(nameButton, 1, wx.ALL | wx.EXPAND, 0) # Complete layout and add statusbar mainSizer.Add(buttonSizer, 1, wx.EXPAND, 5) self.SetSizer(mainSizer) self.Layout() # Deal with the events playerButton.Bind(wx.EVT_BUTTON, self.playerButtonEvent) nameButton.Bind(wx.EVT_BUTTON, self.nameButtonEvent) self.Show(True) return def playerButtonEvent(self, event): """Displays the number of game players""" playerDialog = PlayerDialogWindow(None, -1, "Player") playerDialogResult = playerDialog.ShowModal() playerDialog.Destroy() return def nameButtonEvent(self, event): """Displays the names of game players""" nameDialog = NameDialogWindow(None, -1, "Name") nameDialogResult = nameDialog.ShowModal() nameDialog.Destroy() return class PlayerDialogWindow(wx.Dialog): """Displays the player number""" def __init__(self, parent, id, title): wx.Dialog.__init__(self, parent, id, title, size=(200,120)) # Setup layout items self.SetAutoLayout(True) mainSizer = wx.BoxSizer(wx.VERTICAL) dialogPanel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL) dialogSizer = wx.BoxSizer(wx.VERTICAL) # Display player number playerNumber = "Player number is %i" % gamePlayer.number newLabel = wx.StaticText(dialogPanel, wx.ID_ANY, playerNumber, wx.DefaultPosition, wx.DefaultSize, 0) dialogSizer.Add(newLabel, 0, wx.ALL | wx.EXPAND, 5) # Setup buttons buttonSizer = wx.StdDialogButtonSizer() okButton = wx.Button(dialogPanel, wx.ID_OK) buttonSizer.AddButton(okButton) buttonSizer.Realize() dialogSizer.Add(buttonSizer, 1, wx.EXPAND, 5) # Complete layout dialogPanel.SetSizer(dialogSizer) dialogPanel.Layout() dialogSizer.Fit(dialogPanel) mainSizer.Add(dialogPanel, 1, wx.ALL | wx.EXPAND, 5) self.SetSizer(mainSizer) self.Layout() # Deal with the button events okButton.Bind(wx.EVT_BUTTON, self.okClick) return def okClick(self, event): """Deals with the user clicking the ok button""" self.EndModal(wx.ID_OK) return class NameDialogWindow(wx.Dialog): """Displays the player name""" def __init__(self, parent, id, title): wx.Dialog.__init__(self, parent, id, title, size=(200,120)) # Setup layout items self.SetAutoLayout(True) mainSizer = wx.BoxSizer(wx.VERTICAL) dialogPanel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL) dialogSizer = wx.BoxSizer(wx.VERTICAL) # Display player number playerNumber = "Player name is %s" % gamePlayer.name newLabel = wx.StaticText(dialogPanel, wx.ID_ANY, playerNumber, wx.DefaultPosition, wx.DefaultSize, 0) dialogSizer.Add(newLabel, 0, wx.ALL | wx.EXPAND, 5) # Setup buttons buttonSizer = wx.StdDialogButtonSizer() okButton = wx.Button(dialogPanel, wx.ID_OK) buttonSizer.AddButton(okButton) buttonSizer.Realize() dialogSizer.Add(buttonSizer, 1, wx.EXPAND, 5) # Complete layout dialogPanel.SetSizer(dialogSizer) dialogPanel.Layout() dialogSizer.Fit(dialogPanel) mainSizer.Add(dialogPanel, 1, wx.ALL | wx.EXPAND, 5) self.SetSizer(mainSizer) self.Layout() # Deal with the button events okButton.Bind(wx.EVT_BUTTON, self.okClick) return def okClick(self, event): """Deals with the user clicking the ok button""" self.EndModal(wx.ID_OK) return class Player(object): """A game player""" def __init__(self, number, name): self.number = number self.name = name return def main(): # Start GUI global gamePlayer gamePlayer = Player(1, "John Smith") app = wx.App(redirect=False) frame = ExampleFrame(None, -1, "Example frame") frame.Show(True) app.MainLoop() return 0 if __name__ == '__main__': main() So, I want both of the dialogs to access the gamePlayer object. At the moment, the only way I can think of doing it is to create the gamePlayer object as a global object, but these are normally frowned upon - is there a better way to do this? There is a method of passing objects in event bindings in [this question](http://stackoverflow.com/questions/173687?sort=votes), but it doesn't feel quite right. Is learning to implement the MVC pattern the way forward here? Thanks. Answer: You can pass a gamePlayer object to `__init__` as another argument. def __init__(self, parent, id, title, gamePlayer ): ...etc... In the long run, this isn't ideal. You should separate building an empty panel from loading that panel with data. The empty panel is one thing, populating it with data from the model is unrelated. Populating a frame with data is where you must be given the gamePlayer object which will be used to update the various display widgets. I'd suggest you look at the Document-View framework for guidance on this. <http://docs.wxwidgets.org/stable/wx_docviewoverview.html#docviewoverview>. Unfortunately, there aren't any good Python examples of this, so it can be confusing to convert from the C++ code to Python. Ultimately, you have a "document" which is the main object ("gamePlayer") that is being displayed. Each Frame is a view of that document.
python introspection not showing functions for Lock Question: When I try to use introspection to look at what methods are available on threading.Lock I don't see what I would expect. Specifically I don't see acquire, release or locked. Why is this? Here's what I do see: >>> dir (threading.Lock) ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__str__'] Answer: You're doing it wrong. `threading.Lock` is not an object. >>> import threading >>> threading.Lock <built-in function allocate_lock> >>> type(threading.Lock) <type 'builtin_function_or_method'> >>> x=threading.Lock() >>> type(x) <type 'thread.lock'> >>> dir(x) ['__enter__', '__exit__', 'acquire', 'acquire_lock', 'locked', 'locked_lock', 'release', 'release_lock'] >>>
Reading and running a mathematical expression in Python Question: Using Python, how would I go about reading in (be from a string, file or url) a mathematical expression (1 + 1 is a good start) and executing it? Aside from grabbing a string, file or url I have no idea of where to start with this. Answer: Because python supports some algebraic forms, you could do: eval("1 + 1") But this allows the input to execute about anything defined in your env: eval("__import__('sys').exit(1)") Also, if you want to support something python doesn't support, the approach fails: x³ + y² + c ----------- = 0 z Instead of doing this, you can implement a tokenizer and a parser with [ply](http://www.dabeaz.com/ply/). Evaluating a thing like '1 + 1' ought not take more than ten lines or so. You could also implement the tokenizer and the parser by hand. Read about LL and LR parsers. Before attempting this it's also better to learn using parser generators first.
Sorting and Grouping Nested Lists in Python Question: I have the following data structure (a list of lists) [ ['4', '21', '1', '14', '2008-10-24 15:42:58'], ['3', '22', '4', '2somename', '2008-10-24 15:22:03'], ['5', '21', '3', '19', '2008-10-24 15:45:45'], ['6', '21', '1', '1somename', '2008-10-24 15:45:49'], ['7', '22', '3', '2somename', '2008-10-24 15:45:51'] ] I would like to be able to 1. Use a function to reorder the list so that I can group by each item in the list. For example I'd like to be able to group by the second column (so that all the 21's are together) 2. Use a function to only display certain values from each inner list. For example i'd like to reduce this list to only contain the 4th field value of '2somename' so the list would look like this [ ['3', '22', '4', '2somename', '2008-10-24 15:22:03'], ['7', '22', '3', '2somename', '2008-10-24 15:45:51'] ] Answer: For the first question, the first thing you should do is sort the list by the second field: x = [ ['4', '21', '1', '14', '2008-10-24 15:42:58'], ['3', '22', '4', '2somename', '2008-10-24 15:22:03'], ['5', '21', '3', '19', '2008-10-24 15:45:45'], ['6', '21', '1', '1somename', '2008-10-24 15:45:49'], ['7', '22', '3', '2somename', '2008-10-24 15:45:51'] ] from operator import itemgetter x.sort(key=itemgetter(1)) Then you can use itertools' groupby function: from itertools import groupby y = groupby(x, itemgetter(1)) Now y is an iterator containing tuples of (element, item iterator). It's more confusing to explain these tuples than it is to show code: for elt, items in groupby(x, itemgetter(1)): print(elt, items) for i in items: print(i) Which prints: 21 <itertools._grouper object at 0x511a0> ['4', '21', '1', '14', '2008-10-24 15:42:58'] ['5', '21', '3', '19', '2008-10-24 15:45:45'] ['6', '21', '1', '1somename', '2008-10-24 15:45:49'] 22 <itertools._grouper object at 0x51170> ['3', '22', '4', '2somename', '2008-10-24 15:22:03'] ['7', '22', '3', '2somename', '2008-10-24 15:45:51'] For the second part, you should use list comprehensions as mentioned already here: from pprint import pprint as pp pp([y for y in x if y[3] == '2somename']) Which prints: [['3', '22', '4', '2somename', '2008-10-24 15:22:03'], ['7', '22', '3', '2somename', '2008-10-24 15:45:51']]
Unit testing and mocking email sender in Python with Google AppEngine Question: I'm a newbie to python and the app engine. I have this code that sends an email based on request params after some auth logic. in my Unit tests (i'm using [GAEUnit](http://code.google.com/p/gaeunit/)), how do I confirm an email with specific contents were sent? - i.e. how do I mock the emailer with a fake emailer to verify send was called? class EmailHandler(webapp.RequestHandler): def bad_input(self): self.response.set_status(400) self.response.headers['Content-Type'] = 'text/plain' self.response.out.write("<html><body>bad input </body></html>") def get(self): to_addr = self.request.get("to") subj = self.request.get("subject") msg = self.request.get("body") if not mail.is_email_valid(to_addr): # Return an error message... # self.bad_input() pass # authenticate here message = mail.EmailMessage() message.sender = "my.company@gmail.com" message.to = to_addr message.subject = subj message.body = msg message.send() self.response.headers['Content-Type'] = 'text/plain' self.response.out.write("<html><body>success!</body></html>") And the unit tests, import unittest from webtest import TestApp from google.appengine.ext import webapp from email import EmailHandler class SendingEmails(unittest.TestCase): def setUp(self): self.application = webapp.WSGIApplication([('/', EmailHandler)], debug=True) def test_success(self): app = TestApp(self.application) response = app.get('http://localhost:8080/send?to=vijay.santhanam@gmail.com&body=blah_blah_blah&subject=mySubject') self.assertEqual('200 OK', response.status) self.assertTrue('success' in response) # somehow, assert email was sent Answer: You could also override the `_GenerateLog` method in the `mail_stub` inside AppEngine. Here is a parent TestCase class that I use as a mixin when testing that e-mails are sent: from google.appengine.api import apiproxy_stub_map, mail_stub __all__ = ['MailTestCase'] class MailTestCase(object): def setUp(self): super(MailTestCase, self).setUp() self.set_mail_stub() self.clear_sent_messages() def set_mail_stub(self): test_case = self class MailStub(mail_stub.MailServiceStub): def _GenerateLog(self, method, message, log, *args, **kwargs): test_case._sent_messages.append(message) return super(MailStub, self)._GenerateLog(method, message, log, *args, **kwargs) if 'mail' in apiproxy_stub_map.apiproxy._APIProxyStubMap__stub_map: del apiproxy_stub_map.apiproxy._APIProxyStubMap__stub_map['mail'] apiproxy_stub_map.apiproxy.RegisterStub('mail', MailStub()) def clear_sent_messages(self): self._sent_messages = [] def get_sent_messages(self): return self._sent_messages def assertEmailSent(self, to=None, sender=None, subject=None, body=None): for message in self.get_sent_messages(): if to and to not in message.to_list(): continue if sender and sender != message.sender(): continue if subject and subject != message.subject(): continue if body and body not in message.textbody(): continue return failure_message = "Expected e-mail message sent." args = [] if to: args.append('To: %s' % to) if sender: args.append('From: %s' % sender) if subject: args.append('Subject: %s' % subject) if body: args.append('Body (contains): %s' % body) if args: failure_message += ' Arguments expected: ' + ', '.join(args) self.fail(failure_message) After that, a sample test case might look like: import unittest, MailTestCase class MyTestCase(unittest.TestCase, MailTestCase): def test_email_sent(self): send_email_to('test@example.org') # Some method that would send an e-mail. self.assertEmailSent(to='test@example.org') self.assertEqual(len(self.get_sent_messages()), 1)
unicode() vs. str.decode() for a utf8 encoded byte string (python 2.x) Question: Is there any reason to prefer `unicode(somestring, 'utf8')` as opposed to `somestring.decode('utf8')`? My only thought is that `.decode()` is a bound method so python may be able to resolve it more efficiently, but correct me if I'm wrong. Answer: It's easy to benchmark it: >>> from timeit import Timer >>> ts = Timer("s.decode('utf-8')", "s = 'ééé'") >>> ts.timeit() 8.9185450077056885 >>> tu = Timer("unicode(s, 'utf-8')", "s = 'ééé'") >>> tu.timeit() 2.7656929492950439 >>> Obviously, `unicode()` is faster. FWIW, I don't know where you get the impression that methods would be faster - it's quite the contrary.
Using "with" statement for CSV files in Python Question: Is it possible to use the `with` statement directly with CSV files? It seems natural to be able to do something like this: import csv with csv.reader(open("myfile.csv")) as reader: # do things with reader But csv.reader doesn't provide the `__enter__` and `__exit__` methods, so this doesn't work. I can however do it in two steps: import csv with open("myfile.csv") as f: reader = csv.reader(f) # do things with reader Is this second way the ideal way to do it? Why wouldn't they make csv.reader directly compatible with the with statement? Answer: The primary use of `with` statement is an exception-safe cleanup of an object used in the statement. `with` makes sure that files are closed, locks are released, contexts are restored, etc. Does [csv.reader](http://docs.python.org/library/csv.html#csv.reader) have things to cleanup in case of exception? I'd go with: with open("myfile.csv") as f: for row in csv.reader(f): # process row You don't need to submit the patch to use `csv.reader` and `with` statement together. import contextlib Help on function contextmanager in module [contextlib](http://docs.python.org/library/contextlib.html): contextmanager(func) @contextmanager decorator. Typical usage: @contextmanager def some_generator(<arguments>): <setup> try: yield <value> finally: <cleanup> This makes this: with some_generator(<arguments>) as <variable>: <body> equivalent to this: <setup> try: <variable> = <value> <body> finally: <cleanup> Here's a concrete example how I've used it: [curses_screen](http://stackoverflow.com/questions/327026/attribute-bold- doesnt-seem-to-work-in-my-curses#327072).
decrypting pdf protected by aes-256bit using the right password Question: Is there any way to decrypting a pdf protected by an aes-256 bit key? I have the correct password and I need a command-line tool (or library - perhaps in python :P ) for decrypting the file and then doing some operation over it. The best thing could be if the file could be saved decrypted, then I elaborate it and then I can remove it... Does anyone know something about it? Answer: import pyPdf pdf = pyPdf.PdfFileReader(open("file.pdf")) pdf.decrypt("password") You can then do whatever you want with the contents. This will work with either the user or owner passwords.
How do I determine the size of an object in Python? Question: In C, we can find the size of an `int`, `char`, etc. I want to know how to get size of objects like a string, integer, etc. in Python. Related question: [How many bytes per element are there in a Python list (tuple)?](http://stackoverflow.com/questions/135664/how-many-bytes-per- element-are-there-in-a-python-list-tuple) I am using an XML file which contains size fields that specify the size of value. I must parse this XML and do my coding. When I want to change the value of a particular field, I will check the size field of that value. Here I want to compare whether the new value that I'm gong to enter is of the same size as in XML. I need to check the size of new value. In case of a string I can say its the length. But in case of int, float, etc. I am confused. Answer: Just use the [sys.getsizeof](http://docs.python.org/library/sys.html#sys.getsizeof) function defined in the `sys` module. > `sys.getsizeof(object[, default])`: > > Return the size of an object in bytes. The object can be any type of object. > All built-in objects will return correct results, but this does not have to > hold true for third-party extensions as it is implementation specific. > > The `default` argument allows to define a value which will be returned if > the object type does not provide means to retrieve the size and would cause > a `TypeError`. > > `getsizeof` calls the object’s `__sizeof__` method and adds an additional > garbage collector overhead if the object is managed by the garbage > collector. Usage example, in python 3.0: >>> import sys >>> x = 2 >>> sys.getsizeof(x) 14 >>> sys.getsizeof(sys.getsizeof) 32 >>> sys.getsizeof('this') 38 >>> sys.getsizeof('this also') 48 If you are in python < 2.6 and don't have `sys.getsizeof` you can use [this extensive module](http://code.activestate.com/recipes/546530/) instead. Never used it though.
Python Path Question: I am installing active python, django. I really dont know how to set the python path in vista environment system. first of all will it work in vista. Answer: # Temporary Change To change the python path temporarily (i.e., for one interactive session), just append to `sys.path` like this: >>> import sys >>> sys.path ['', 'C:\\Program Files\\PyScripter\\Lib\\rpyc.zip', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages'] >>> sys.path.append(directory_to_be_added) # Permanent (More or Less) Change Go to `Computer -> System Properties (Either by the big button near the title bar or in the context-menu by right-clicking) -> Advanced Settings (in the right-hand nav bar) -> Environment Variables`. In the `System Variables`, either add a variable called `PYTHONPATH` (if it's not already there, i.e., if you haven't done this before) or edit the existing variable. You should enter the directories normally (take care to use backslashes, not the normal ones) separated by a semicolon (`;`) w/o a space. Be careful not to end with a semicolon. The directories that you just entered now will be _added_ to `sys.path` whenever you open a interpreter, they won't replace it. Also, the changes will take place only after you've restarted the interpreter. * * * Source: <http://greeennotebook.com/2010/06/how-to-change-pythonpath-in- windows-and-ubuntu/>
PHP Get Source and Search for Word Question: I need help i want to code a program that search for a word inside the source code. Here a Example in Python: import urllib2, re site = "http://stackoverflow.com/" tosearch = "Questions" source = urllib2.urlopen(site).read() if re.search(tosearch,source): print "Found The Word", tosearch Answer: <?php $site = "http://stackoverflow.com/"; $tosearch = "Questions"; $source = file_get_contents($site); if(preg_match("/{$tosearch}/", $source)): // fixed, thanks meouw echo "Found the the word {$tosearch}"; endif; ?>
Python object.__repr__(self) should be an expression? Question: I was looking at the builtin object methods in the [Python documentation](http://docs.python.org/reference/datamodel.html#objects-values- and-types), and I was interested in the documentation for `object.__repr__(self)`. Here's what it says: > Called by the repr() built-in function and by string conversions (reverse > quotes) to compute the “official” string representation of an object. If at > all possible, this should look like a valid Python expression that could be > used to recreate an object with the same value (given an appropriate > environment). If this is not possible, a string of the form <...some useful > description...> should be returned. The return value must be a string > object. If a class defines **repr**() but not **str**(), then **repr**() is > also used when an “informal” string representation of instances of that > class is required. > > This is typically used for debugging, so it is important that the > representation is information-rich and unambiguous The most interesting part to me, was... > If at all possible, this should look like a valid Python expression that > could be used to recreate an object with the same value ... but I'm not sure exactly what this means. It says it should _look_ like an expression which can be used to recreate the object, but does that mean it should just be an example of the sort of expression you could use, or should it be an actual expression, that can be executed (eval etc..) to recreate the object? Or... should it be just a rehasing of the actual expression which was used, for pure information purposes? In general I'm a bit confused as to exactly what I should be putting here. Answer: >>> from datetime import date >>> >>> repr(date.today()) # calls date.today().__repr__() 'datetime.date(2009, 1, 16)' >>> eval(_) # _ is the output of the last command datetime.date(2009, 1, 16) The output is a string that can be parsed by the python interpreter and results in an equal object. If that's not possible, it should return a string in the form of `<...some useful description...>`.
How can I test that I have a Python module successfully installed? Question: I tried to install beautifulsoup. I get such an error: <\-- snip --> raise MissingSectionHeaderError(fpname, lineno, line) ConfigParser.MissingSectionHeaderError: File contains no section headers. file: /Users/Sam/.pydistutils.cfg, line: 1 'install_lib = ~/Library/Python/$py_version_short/site-packages\n' I get an similar error as I run my Python code in vim by: :!python % Answer: You can test if a module is installed like so: $ python >>> import modulename
Standard way to embed version into python package? Question: Is there a standard way to associate version string with a python package in such way that I could do the following? import foo print foo.version I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in `setup.py` already. Alternative solution that I found was to have `import __version__` in my `foo/__init__.py` and then have `__version__.py` generated by `setup.py`. Answer: Here is how I do this. Advantages of the following method: 1. It provides a `__version__` attribute. 2. It provides the standard metadata version. Therefore it will be detected by `pkg_resources` or other tools that parse the package metadata (EGG-INFO and/or PKG-INFO, PEP 0345). 3. It doesn't import your package (or anything else) when building your package, which can cause problems in some situations. (See the comments below about what problems this can cause.) 4. There is only one place that the version number is written down, so there is only one place to change it when the version number changes, and there is less chance of inconsistent versions. Here is how it works: the "one canonical place" to store the version number is a .py file, named "_version.py" which is in your Python package, for example in `myniftyapp/_version.py`. This file is a Python module, but your setup.py doesn't import it! (That would defeat feature 3.) Instead your setup.py knows that the contents of this file is very simple, something like: __version__ = "3.6.5" And so your setup.py opens the file and parses it, with code like: import re VERSIONFILE="myniftyapp/_version.py" verstrline = open(VERSIONFILE, "rt").read() VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]" mo = re.search(VSRE, verstrline, re.M) if mo: verstr = mo.group(1) else: raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,)) Then your setup.py passes that string as the value of the "version" argument to `setup()`, thus satisfying feature 2. To satisfy feature 1, you can have your package (at run-time, not at setup time!) import the _version file from `myniftyapp/__init__.py` like this: from _version import __version__ Here is [an example of this technique](https://tahoe- lafs.org/trac/zfec/browser/trunk/zfec/setup.py?rev=390#L84) that I've been using for years. The code in that example is a bit more complicated, but the simplified example that I wrote into this comment should be a complete implementation. Here is [example code of importing the version](https://tahoe- lafs.org/trac/zfec/browser/trunk/zfec/zfec/__init__.py?rev=363). If you see anything wrong with this approach, please let me know: zooko at zooko dot com. If you don't see anything wrong with this approach then use it! Because the more packages come with their version numbers in the expected places the better!
Can I get the matrix determinant using Numpy? Question: I read in the manual of Numpy that there is function `det(M)` that can calculate the determinant. However, I can't find the `det()` method in Numpy. By the way, I use Python 2.5. There should be no compatibility problems with Numpy. Answer: You can use [`numpy.linalg.det`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.det.html) to compute the determinant of an array: In [1]: import numpy In [2]: M = [[1, 2], [3, 4]] In [3]: print numpy.linalg.det(M) Out[3]: -2.0000000000000004
How are POST and GET variables handled in Python? Question: In PHP you can just use `$_POST` for POST and `$_GET` for GET (Query string) variables. What's the equivalent in Python? Answer: suppose you're posting a html form with this: <input type="text" name="username"> If using [raw cgi](http://docs.python.org/library/cgi.html): import cgi form = cgi.FieldStorage() print form["username"] If using [Django](http://docs.djangoproject.com/), [Pylons](http://pylonshq.com/), [Flask](http://flask.pocoo.org/) or [Pyramid](http://www.pylonsproject.org/projects/pyramid/about): print request.GET['username'] # for GET form method print request.POST['username'] # for POST form method Using [Turbogears](http://turbogears.org/), [Cherrypy](http://www.cherrypy.org/): from cherrypy import request print request.params['username'] [Web.py](http://webpy.org): form = web.input() print form.username [Werkzeug](http://werkzeug.pocoo.org/): print request.form['username'] If using Cherrypy or Turbogears, you can also define your handler function taking a parameter directly: def index(self, username): print username [Google App Engine](https://developers.google.com/appengine/docs/python/gettingstartedpython27/introduction): class SomeHandler(webapp2.RequestHandler): def post(self): name = self.request.get('username') # this will get the value from the field named username self.response.write(name) # this will write on the document So you really will have to choose one of those frameworks.
Any Python OLAP/MDX ORM engines? Question: I'm new to the MDX/OLAP and I'm wondering if there is any ORM similar like Django ORM for Python that would support OLAP. I'm a Python/Django developer and if there would be something that would have some level of integration with Django I would be much interested in learning more about it. Answer: Django has some OLAP features that are nearing release. Read <http://www.eflorenzano.com/blog/post/secrets-django-orm/> <http://doughellmann.com/2007/12/30/using-raw-sql-in-django.html>, also If you have a proper star schema design in the first place, then one- dimensional results can have the following form. from myapp.models import SomeFact from collections import defaultdict facts = SomeFact.objects.filter( dimension1__attribute=this, dimension2__attribute=that ) myAggregates = defaultdict( int ) for row in facts: myAggregates[row.dimension3__attribute] += row.someMeasure If you want to create a two-dimensional summary, you have to do something like the following. facts = SomeFact.objects.filter( dimension1__attribute=this, dimension2__attribute=that ) myAggregates = defaultdict( int ) for row in facts: key = ( row.dimension3__attribute, row.dimension4__attribute ) myAggregates[key] += row.someMeasure To compute multiple SUM's and COUNT's and what-not, you have to do something like this. class MyAgg( object ): def __init__( self ): self.count = 0 self.thisSum= 0 self.thatSum= 0 myAggregates= defaultdict( MyAgg ) for row in facts: myAggregates[row.dimension3__attr].count += 1 myAggregates[row.dimension3__attr].thisSum += row.this myAggregates[row.dimension3__attr].thatSum += row.that This -- at first blush -- seems inefficient. You're trolling through the fact table returning lots of rows which you are then aggregating in your application. In some cases, this may be _faster_ than the RDBMS's native sum/group_by. Why? You're using a simple mapping, not the more complex sort-based grouping operation that the RDBMS often has to use for this. Yes, you're getting a lot of rows; but you're doing less to get them. This has the disadvantage that it's not so declarative as we'd like. It has the advantage that it's pure Django ORM.
problem using an instance in a with_statement Question: I've recently started to learn python , and I reached the **with** statement . I've tried to use it with a class instance , but I think I'm doing something wrong . Here is the code : from __future__ import with_statement import pdb class Geo: def __init__(self,text): self.text = text def __enter__(self): print "entering" def __exit__(self,exception_type,exception_value,exception_traceback): print "exiting" def ok(self): print self.text def __get(self): return self.text with Geo("line") as g : g.ok() The thing is that when the interpreter reaches the **ok** method inside the with statement , the following exception is raised : Traceback (most recent call last): File "dec.py", line 23, in g.ok() AttributeError: 'NoneType' object has no attribute 'ok' Why does the g object have the type NoneType ? How can I use an instance with the **with** statement ? Answer: Your `__enter__` method needs to return the object that should be used for the "`as g`" part of the with statement. See the [documentation](http://docs.python.org/reference/compound_stmts.html#with), where it states: * If a target was included in the with statement, the return value from `__enter__()` is assigned to it. Currently, it has no return statement, so g gets bound to `None` (the default return value)
How do I remove VSS hooks from a VS Web Site? Question: I have a Visual Studio 2008 solution with 7 various projects included with it. 3 of these 'projects' are Web Sites (the kind of project without a project file). I have stripped all the various Visual Sourcesafe files from all the directories, removed the Scc references in the SLN file and all the project files that exist. I deleted the SUO file and all the USER files also. Visual Studio still thinks that 2 of the Web Sites are still under source control, and it adds the Scc entries back into the SLN file for me. **Does anybody know _how_ VS still knows about the old source control?** _Edit:_ Another thing that I didn't mention is that the files I'm trying to remove VSS hooks from has been copied outside of VSS's known working directories, the python script run and manual edits to files made before the solution is opened in VS 2008 or VS 2005 (I had the problem with both). Here is a python script that I used to weed out these files and let me know which files needed manually edited. import os, stat from os.path import join def main(): startDir = r"C:\Documents and Settings\user\Desktop\project" manualEdits = [] for root, dirs, files in os.walk(startDir, topdown=False): if '.svn' in dirs: dirs.remove('.svn') for name in files: os.chmod(join(root,name), stat.S_IWRITE) if name.endswith(".vssscc") or name.endswith(".scc") or name.endswith(".vspscc") or name.endswith(".suo") or name.endswith(".user"): print "Deleting:", join(root, name) os.remove(join(root,name)) if name.endswith("sln") or name.endswith("dbp") or name.endswith("vbproj") or name.endswith("csproj"): manualEdits.append(join(root, name)) print "Manual Edits are needed for these files:" for name in manualEdits: print name if __name__ == "__main__": main() Answer: It probably is only trying to add it on your instance of VS. You have to remove the cache so VS thinks its no longer under SS 1. under file -> SourceControl -> Workspaces 2. Select the SS location 3. Edit 4. Choose the working folder 5. Remove!
Incorrect answer in dll import in Python Question: In my Python script I'm importing a dll written in VB.NET. I'm calling a function of initialisation in my script. It takes 2 arguments: a path to XML file and a string. It returns an integer - 0 for success, else error. The second argument is passed by reference. So if success, it will get updated with success message. Otherwise, get updated with error message. When my script receives the integer, I should print the message in the second variable. I'm not able to do that. Answer: Python strings are immutable. There is no way the string can be changed inside the function. So what you really want is to pass a _char buffer_ of some sort. You can create those in python using the `ctypes` module. Please edit the question and paste a minimal snippet of the code so we can test and give more information.
What's the idiomatic Python equivalent to Django's 'regroup' template tag? Question: <http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup> I can think of a few ways of doing it with loops but I'd particularly like to know if there is a neat one-liner. Answer: Combine [`itertools.groupby`](http://docs.python.org/library/itertools.html#itertools.groupby) with [`operator.itemgetter`](http://docs.python.org/library/operator.html#operator.itemgetter) to get a pretty nice solution: from operator import itemgetter from itertools import groupby key = itemgetter('gender') iter = groupby(sorted(people, key=key), key=key) for gender, people in iter: print '===', gender, '===' for person in people: print person
How would you determine where each property and method of a Python class is defined? Question: Given an instance of some class in Python, it would be useful to be able to determine which line of source code _defined_ each method and property (e.g. to implement [1]). For example, given a module ab.py class A(object): z = 1 q = 2 def y(self): pass def x(self): pass class B(A): q = 4 def x(self): pass def w(self): pass define a function whither(class_, attribute) returning a tuple containing the filename, class, and line in the source code that defined or subclassed `attribute`. This means the definition in the class body, not the latest assignment due to overeager dynamism. It's fine if it returns 'unknown' for some attributes. >>> a = A() >>> b = B() >>> b.spigot = 'brass' >>> whither(a, 'z') ("ab.py", <class 'a.A'>, [line] 2) >>> whither(b, 'q') ("ab.py", <class 'a.B'>, 8) >>> whither(b, 'x') ("ab.py", <class 'a.B'>, 9) >>> whither(b, 'spigot') ("Attribute 'spigot' is a data attribute") I want to use this while introspecting Plone, where every object has hundreds of methods and it would be really useful to sort through them organized by class and not just alphabetically. Of course, in Python you can't always reasonably know, but it would be nice to get good answers in the common case of mostly-static code. Answer: This is more-or-less impossible without static analysis, and even then, it won't always work. You can get the line where a function was defined and in which file by examining its code object, but beyond that, there's not much you can do. The `inspect` module can help with this. So: import ab a = ab.A() meth = a.x # So, now we have the method. func = meth.im_func # And the function from the method. code = func.func_code # And the code from the function! print code.co_firstlineno, code.co_filename # Or: import inspect print inspect.getsource(meth), inspect.getfile(meth) But consider: def some_method(self): pass ab.A.some_method = some_method ab.A.some_class_attribute = None Or worse: some_cls = ab.A some_string_var = 'another_instance_attribute' setattr(some_cls, some_string_var, None) Especially in the latter case, what do you want or expect to get?
calculate exponential moving average in python Question: I have a range of dates and a measurement on each of those dates. I'd like to calculate an exponential moving average for each of the dates. Does anybody know how to do this? I'm new to python. It doesn't appear that averages are built into the standard python library, which strikes me as a little odd. Maybe I'm not looking in the right place. So, given the following code, how could I calculate the moving weighted average of IQ points for calendar dates? from datetime import date days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)] IQ = [110, 105, 90] (there's probably a better way to structure the data, any advice would be appreciated) Answer: EDIT: It seems that [`mov_average_expw()`](http://www.scipy.org/scipy/scikits/browser/trunk/timeseries/scikits/timeseries/lib/moving_funcs.py) function from [scikits.timeseries.lib.moving_funcs](http://pytseries.sourceforge.net/lib/moving_funcs.html) submodule from [SciKits](http://scikits.appspot.com/) (add-on toolkits that complement [SciPy](http://scipy.org/)) better suits the wording of your question. * * * To calculate an [exponential smoothing](http://en.wikipedia.org/wiki/Exponential_smoothing) of your data with a smoothing factor `alpha` (it is `(1 - alpha)` in Wikipedia's terms): >>> alpha = 0.5 >>> assert 0 < alpha <= 1.0 >>> av = sum(alpha**n.days * iq ... for n, iq in map(lambda (day, iq), today=max(days): (today-day, iq), ... sorted(zip(days, IQ), key=lambda p: p[0], reverse=True))) 95.0 The above is not pretty, so let's refactor it a bit: from collections import namedtuple from operator import itemgetter def smooth(iq_data, alpha=1, today=None): """Perform exponential smoothing with factor `alpha`. Time period is a day. Each time period the value of `iq` drops `alpha` times. The most recent data is the most valuable one. """ assert 0 < alpha <= 1 if alpha == 1: # no smoothing return sum(map(itemgetter(1), iq_data)) if today is None: today = max(map(itemgetter(0), iq_data)) return sum(alpha**((today - date).days) * iq for date, iq in iq_data) IQData = namedtuple("IQData", "date iq") if __name__ == "__main__": from datetime import date days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)] IQ = [110, 105, 90] iqdata = list(map(IQData, days, IQ)) print("\n".join(map(str, iqdata))) print(smooth(iqdata, alpha=0.5)) Example: $ python26 smooth.py IQData(date=datetime.date(2008, 1, 1), iq=110) IQData(date=datetime.date(2008, 1, 2), iq=105) IQData(date=datetime.date(2008, 1, 7), iq=90) 95.0
AJAX command-line interface in browser Question: I'm building a Web app to allow users to view and manipulate data, particularly numeric and geographic data. It's important that the output be clear and professional (data grids, Google Map overlays, etc.). But in terms of the user interface, I'd rather start with the flexibility of a command-line interface before building GUI-style forms. Can you offer any tips, tricks, or suggestions to create an AJAX-based command-line interface that can drive the rest of the interface? Pointers to existing applications would be great, too. The stack I'm using is Django/Python on the server side and ExtJS in the browser. If possible, I'd like to route commands to the Django shell and then just add some extra functions to output the results to a data grid, a map, etc. Thanks! **@Soviut** Thanks for the quick response. I'm afraid I must not be making myself that clear. I want to use a shell to fire off commands on the server side that'll then feed back to output on the client side. Here's an example I just found: <http://shell.appspot.com/> It's just that I'd like to have that not just produce text output inside the shell but also produce output that will be picked up by other AJAX listeners for data grids and maps. Answer: [goosh](http://www.goosh.org/) is a great example of a command line web application. I had nothing to do with it's creation but I have used parts of it's design for something at work.
How to clear python interpreter console? Question: Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc. Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console. I've heard about doing a system call and either calling `cls` on Windows or `clear` on Linux, but I was hoping there was something I could command the interpreter itself to do. **Note:** I'm running on Windows, so Ctrl+L doesn't work. Answer: As you mentioned, you can do a system call: >>> import os >>> clear = lambda: os.system('cls') >>> clear() I am not sure of any other way in Windows.
Is there a way to loop through a sub section of a list in Python Question: So for a list that has 1000 elements, I want to loop from 400 to 500. How do you do it? I don't see a way by using the for each and for range techniques. Answer: for x in thousand[400:500]: pass If you are working with an iterable instead of a list, you should use [itertools](http://docs.python.org/library/itertools): import itertools for x in itertools.islice(thousand, 400, 500): pass If you need to loop over `thousand[500]`, then use 501 as the latter index. This will work even if `thousand[501]` is not a valid index.
The right language for OpenGL UI prototyping. Ditching Python Question: So, I got this idea that I'd try to prototype an experimental user interface using OpenGL and some physics. I know little about either of the topics, but am pretty experienced with programming languages such as C++, Java and C#. After some initial research, I decided on using Python (with Eclipse/PyDev) and Qt, both new to me, and now have four different topics to learn more or less simultaneously. I've gotten quite far with both OpenGL and Python, but while Python and its ecosystem initially seemed perfect for the task, I've now discovered some serious drawbacks. Bad API documentation and lacking code completion (due to dynamic typing), having to import every module I use in every other module gets tedious when having one class per module, having to select the correct module to run the program, and having to wait 30 seconds for the program to start and obscure the IDE before being notified of many obvious typos and other mistakes. It gets really annoying really fast. Quite frankly, i don't get what all the fuzz is about. Lambda functions, list comprehensions etc. are nice and all, but there's certainly more important things. So, unless anyone can resolve at least some of these annoyances, Python is out. C++ is out as well, for obvious reasons, and C# is out, mainly for lack of portability. This leaves Java and JOGL as an attractive option, but I'm also curious about Ruby and Groovy. I'd like your opinion on these and others though, to keep my from making the same mistake again. The requirements are: * Keeping the hell out of my way. * Good code completion. Complete method signatures, including data types and parameter names. * Good OpenGL support. * Qt support is preferable. * Object Oriented * Suitable for RAD, prototyping * Cross-platform * Preferably Open-Source, but at least free. Answer: It seems you aren't mainly having a problem with Python itself, but instead with the IDE. _"Bad API documentation"_ To what API? Python itself, Qt or some other library you are using? _"lacking code completion (due to dynamic typing)"_ As long as you are not doing anything magic, I find that PyDev is pretty darn good at figuring these things out. If it gets lost, you can always typehint by doing: assert isinstance(myObj, MyClass) Then, PyDev will provide you with code completion even if myObj comes from a dynamic context. _"having to import every module I use in every other module gets tedious when having one class per module"_ Install PyDev Extensions, it has auto-import on the fly. Or collect all your imports in a separate module and do: from mymodulewithallimports import * _"having to select the correct module to run the program"_ In Eclipse, you can set up a default startup file, or just check "use last run configuration". Then you never have to select it again. _"before being notified of many obvious typos and other mistakes"_ Install PyDev Extensions, it has more advanced syntax checking and will happily notify you about unused imports/variables, uninitialized variables etc.
NumPy, PIL adding an image Question: I'm trying to add two images together using NumPy and PIL. The way I would do this in [MATLAB](http://en.wikipedia.org/wiki/MATLAB) would be something like: >> M1 = imread('_1.jpg'); >> M2 = imread('_2.jpg'); >> resM = M1 + M2; >> imwrite(resM, 'res.jpg'); I get something like this: ![alt text](http://www.deadlink.cc/matlab.jpg) Using a compositing program and adding the images the MATLAB result seems to be right. In Python I'm trying to do the same thing like this: from PIL import Image from numpy import * im1 = Image.open('/Users/rem7/Desktop/_1.jpg') im2 = Image.open('/Users/rem7/Desktop/_2.jpg') im1arr = asarray(im1) im2arr = asarray(im2) addition = im1arr + im2arr resultImage = Image.fromarray(addition) resultImage.save('/Users/rem7/Desktop/a.jpg') and I get something like this: ![alt text](http://www.deadlink.cc/python.jpg) Why am I getting all those funky colors? I also tried using `ImageMath.eval("a+b", a=im1, b=im2)`, but I get an error about RGB unsupported. I also saw that there is an `Image.blend()` but that requires an alpha. What's the best way to achieve what I'm looking for? Source Images (images have been removed): ![alt text](http://www.deadlink.cc/_1.jpg) ![alt text](http://www.deadlink.cc/_2.jpg) Humm, OK, well I added the source images using the add image icon and they show up when I'm editing the post, but for some reason the images don't show up in the post. (images have been removed) 2013 05 09 Answer: As everyone suggested already, the weird colors you're observing are overflow. And as you point out in the [comment of schnaader's answer](http://stackoverflow.com/questions/524930/numpy-pil-adding-an- image/524943#524943) you **still get overflow** if you add your images like this: addition=(im1arr+im2arr)/2 The reason for this overflow is that your NumPy arrays (_im1arr_ _im2arr_) are of the **uint8** type (i.e. 8-bit). This means each element of the array can only hold values up to 255, so when your sum exceeds 255, it loops back around 0: >>>array([255,10,100],dtype='uint8') + array([1,10,160],dtype='uint8') array([ 0, 20, 4], dtype=uint8) To avoid overflow, your arrays should be able to contain values beyond 255. You need to **convert them to floats** for instance, perform the blending operation and **convert the result back to uint8** : im1arrF = im1arr.astype('float') im2arrF = im2arr.astype('float') additionF = (im1arrF+im2arrF)/2 addition = additionF.astype('uint8') You **should not** do this: addition = im1arr/2 + im2arr/2 as you lose information, by squashing the dynamic of the image (you effectively make the images 7-bit) before you perform the blending information. **MATLAB note** : the reason you don't see this problem in MATLAB, is probably because MATLAB takes care of the overflow implicitly in one of its functions.
Do Python regexes support something like Perl's \G? Question: I have a Perl regular expression (shown [here](http://stackoverflow.com/questions/529657/how-do-i-write-a-regex-that- performs-multiple-substitutions-on-each-line-except/529735#529735), though understanding the whole thing isn't hopefully necessary to answering this question) that contains the \G metacharacter. I'd like to translate it into Python, but Python doesn't appear to support \G. What can I do? Answer: Try these: import re re.sub() re.findall() re.finditer() for example: # Finds all words of length 3 or 4 s = "the quick brown fox jumped over the lazy dogs." print re.findall(r'\b\w{3,4}\b', s) # prints ['the','fox','over','the','lazy','dogs']
Python 2.x gotcha's and landmines Question: The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter. I'm looking for something similar to what learned from my [PHP landmines](http://stackoverflow.com/questions/512120/php-landmines-in-general) question where some of the answers were well known to me but a couple were borderline horrifying. Update: Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL <http://www.ferg.org/projects/python_gotchas.html> Note that one or two answers here already are original from what was written on the site referenced above. Answer: **Expressions in default arguments are calculated when the function is defined,_not_ when it’s called.** **Example:** consider defaulting an argument to the current time: >>>import time >>> def report(when=time.time()): ... print when ... >>> report() 1210294387.19 >>> time.sleep(5) >>> report() 1210294387.19 The `when` argument doesn't change. It is evaluated when you define the function. It won't change until the application is re-started. **Strategy:** you won't trip over this if you default arguments to `None` and then do something useful when you see it: >>> def report(when=None): ... if when is None: ... when = time.time() ... print when ... >>> report() 1210294762.29 >>> time.sleep(5) >>> report() 1210294772.23 **Exercise:** to make sure you've understood: why is this happening? >>> def spam(eggs=[]): ... eggs.append("spam") ... return eggs ... >>> spam() ['spam'] >>> spam() ['spam', 'spam'] >>> spam() ['spam', 'spam', 'spam'] >>> spam() ['spam', 'spam', 'spam', 'spam']
Connecting to MS SQL Server using python on linux with 'Windows Credentials' Question: Is there any way to connect to an MS SQL Server database with python on linux using Windows Domain Credentials? I can connect perfectly fine from my windows machine using Windows Credentials, but attempting to do the same from a linux python with pyodbs + freetds + unixodbc >>import pyodbc >>conn = pyodbc.connect("DRIVER={FreeTDS};SERVER=servername;UID=username;PWD=password;DATABASE=dbname") results in this error: class 'pyodbc.Error'>: ('28000', '[28000] [unixODBC][FreeTDS][SQL Server]Login incorrect. (20014) (SQLDriverConnectW)') I'm sure the password is written correctly, but I've tried many different combinations of username: DOMAIN\username DOMAIN\\username or even UID=username;DOMAIN=domain to no avail. Any ideas? Answer: **As pointed out in one of the comments, this answer is quite stale by now. I regularly and routinely use GSSAPI to authenticate from Linux to SQL Server 2008 R2 but mostly with the EasySoft ODBC manager and the (commercial) EasySoft ODBC SQL Server driver.** In early 2009, a colleague and I managed to connect to a SQL Server 2005 instance from Solaris 10 using GSSAPI (Kerberos credentials) using DBB::Perl over a FreeTDS build linked against a particular version of the MIT kerberos libraries. The trick was -- and this is a little bit difficult to believe but I have verified it by looking through the FreeTDS source code -- to specify a _zero-length_ user_name. If the length of the user_name string is 0 then the FreeTDS code will attempt to use GSSAPI (if that support has been compiled in). I have not been able to do this via Python and pyodbc as I could not figure out a way of getting ODBC to pass down a zero-length user_name. Here in the perl code .. there are multiple opportunities for breakage wrt configuration files such as .freetds.conf etc. I seem to recall that the principal had to be in uppercase but my notes seem to be in disagreement with that. $serverprincipal = 'MSSQLSvc/foo.bar.yourdomain.com:1433@YOURDOMAIN.COM'; $dbh = DBI->connect("dbi:Sybase:server=THESERVERNAME;kerberos=$serverprincipal", '', ''); You will have to know how to use the setspn utility in order to get the SQL Server server to use the appropriate security principal name. I do not have any knowledge of the kerberos side of things because our environment was set up by an out and out Kerberos guru and has fancy stuff like mutual trust set up between the AD domain that the SQL Server is running in and the Kerberos domain that my client was running in. There is some code <http://code.google.com/p/libsqljdbc-auth/> which does GSSAPI authentication from Linux to SQL Server but it is Java only. The author (who seems to know his stuff) also has contributed a similar patch to the jTDS project which works with more recent versions of Java that have GSSAPI built in. So the pieces are all there, it is just a big tangled mess trying to get them all to work together. I found the pyodbc to unixODBC to FreeTDS odbc to TDS integration pretty hard to trace/debug. The perl stuff because it was a pretty thin wrapper on top to CT-Lib was much easier to get going.
Extracting extension from filename in Python Question: Is there a function to extract the extension from a filename? Answer: Yes. Use [`os.path.splitext`](https://docs.python.org/2/library/os.path.html#os.path.splitext): >>> import os >>> filename, file_extension = os.path.splitext('/path/to/somefile.ext') >>> filename '/path/to/somefile' >>> file_extension '.ext'

Stackoverflow Q&A about Python

This dataset is a subset of StackSample. Each row is a text containing a question and the highest rated answer - if it relates to Python.

The relatively contained size of this set might be helpful to deploy as a local RAG application.

Downloads last month
47