instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
base64 png in python on Windows
How do you encode a png image into base64 using python on Windows? iconfile = open("icon.png") icondata = iconfile.read() icondata = base64.b64encode(icondata) The above works fine in Linux and OSX, but on Windows it will encode the first few characters then cut short. Why is this?
Open the file in binary mode: open("icon.png", "rb") I'm not very familiar with Windows, but I'd imagine what's happening is that the file contains a character (0x1A) that Windows is interpreting as the end of the file (for legacy reasons) when it is opened in text mode. The other issue is that opening a file in text mode (without the 'b') on Windows will cause line endings to be rewritten, which will generally break binary files where those characters don't actually indicate the end of a line.
svg diagrams using python
I am looking for a library to generate svg diagrams in python (I fetch data from a sql database). I have found python-gd, but it has not much documentation and last update was in 2005 so I wonder if there are any other libraries that are good for this purpose. I am mostly thinking about simple line graphs, something like this:
As you're looking for simple line graphics, probably, CairoPlot will fit your needs as it can generate svg output files out of the box. Take a look at this. This example image shows only a few of its capabilities. Using the trunk version available at launchpad you'll be able to add a legend box and add axis titles. Besides that, using the trunk version, it's possible to generate: DotLine charts (the ones I believe you need) Scatter charts Pie/Donut charts Horizontal/Vertical Bar charts Gantt charts
Python urllib2, basic HTTP authentication, and tr.im
I'm playing around, trying to write some code to use the tr.im APIs to shorten a URL. After reading http://docs.python.org/library/urllib2.html, I tried: TRIM_API_URL = 'http://api.tr.im/api' auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm='tr.im', uri=TRIM_API_URL, user=USERNAME, passwd=PASSWORD) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() response.code is 200 (I think it should be 202). url is valid, but the basic HTTP authentication doesn't seem to have worked, because the shortened URL isn't in my list of URLs (at http://tr.im/?page=1). After reading http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly I also tried: TRIM_API_URL = 'api.tr.im/api' password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, TRIM_API_URL, USERNAME, PASSWORD) auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('http://%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() But I get the same results. (response.code is 200 and url is valid, but not recorded in my account at http://tr.im/.) If I use query string parameters instead of basic HTTP authentication, like this: TRIM_API_URL = 'http://api.tr.im/api' response = urllib2.urlopen('%s/trim_simple?url=%s&username=%s&password=%s' % (TRIM_API_URL, url_to_trim, USERNAME, PASSWORD)) url = response.read().strip() ...then not only is url valid but it's recorded in my tr.im account. (Though response.code is still 200.) There must be something wrong with my code though (and not tr.im's API), because $ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk ...returns: {"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"200","message":"tr.im URL Added."},"date_time":"2009-03-11T10:15:35-04:00"} ...and the URL does appear in my list of URLs on http://tr.im/?page=1. And if I run: $ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk ...again, I get: {"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"201","message":"tr.im URL Already Created [yacitus]."},"date_time":"2009-03-11T10:15:35-04:00"} Note code is 201, and message is "tr.im URL Already Created [yacitus]." I must not be doing the basic HTTP authentication correctly (in either attempt). Can you spot my problem? Perhaps I should look and see what's being sent over the wire? I've never done that before. Are there Python APIs I can use (perhaps in pdb)? Or is there another tool (preferably for Mac OS X) I can use?
This seems to work really well (taken from another thread) import urllib2, base64 request = urllib2.Request("http://api.foursquare.com/v1/user") base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') request.add_header("Authorization", "Basic %s" % base64string) result = urllib2.urlopen(request)
code documentation for python
What is out there on conventions and tools for documenting python source code?
Conventions: PEP 257 and PEP 8. Note, that docstrings can be written in reStructuredText Tools for generating documentation: for example Sphinx
What is the best way to implement nested dictionaries in Python?
I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this: {'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. I could also use tuples as keys, like such: {('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state). Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. How could I do this better? Addendum: I'm aware of setdefault() but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have setdefault() manually set.
class AutoVivification(dict): """Implementation of perl's autovivification feature.""" def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: value = self[item] = type(self)() return value Testing: a = AutoVivification() a[1][2][3] = 4 a[1][3][3] = 5 a[1][2]['test'] = 6 print a Output: {1: {2: {'test': 6, 3: 4}, 3: {3: 5}}}
What's different between Python and Javascript regular expressions?
Are Python and JavaScript regular expression syntax identical? If not, then: What are the important differences between them Is there a python library that "implements" JavaScript regexps?
There is a comparison table here: Regex Flavor Comparison
SELECT * in sqlalchemy?
Is it possible to do SELECT * in sqlalchemy? Edit: Specifically, SELECT * WHERE foo=1
Is no one feeling the ORM love of SQLALchemy today? The presented answers correctly describe the lower level interface that SQLAlchemy provides. Just for completeness this is the more-likely (for me) real-world situation where you have a session instance and a User class that is orm mapped to the users table. for user in session.query(User).filter_by(name='jack'): print user # ... And this does an explicit select on all columns.
How can I run an external command asynchronously from Python?
I need to run a shell command asynchronously from a Python script. By this I mean that I want my Python script to continue running while the external command goes off and does whatever it needs to do. I read this post: http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python I then went off and did some testing, and it looks like os.system() will do the job provided that I use & at the end of the command so that I don't have to wait for it to return. What I am wondering is if this is the proper way to accomplish such a thing? I tried commands.call() but it will not work for me because it blocks on the external command. Please let me know if using os.system() for this is advisable or if I should try some other route.
subprocess.Popen does exactly what you want. from subprocess import Popen p = Popen(['watch', 'ls']) # something long running # ... do other stuff while subprocess is running p.terminate() (Edit to complete the answer from comments) The Popen instance can do various other things like you can poll() it to see if it is still running, and you can communicate() with it to send it data on stdin, and wait for it to terminate.
Python Profiling in Eclipse
This questions is semi-based of this one here: http://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script I thought that this would be a great idea to run on some of my programs. Although profiling from a batch file as explained in the aforementioned answer is possible, I think it would be even better to have this option in Eclipse. At the same time, making my entire program a function and profiling it would mean I have to alter the source code? How can I configure eclipse such that I have the ability to run the profile command on my existing programs? Any tips or suggestions are welcomed!
if you follow the common python idiom to make all your code, even the "existing programs", importable as modules, you could do exactly what you describe, without any additional hassle. here is the specific idiom I am talking about, which turns your program's flow "upside-down" since the __name__ == '__main__' will be placed at the bottom of the file, once all your defs are done: # program.py file def foo(): """ analogous to a main(). do something here """ pass # ... fill in rest of function def's here ... # here is where the code execution and control flow will # actually originate for your code, when program.py is # invoked as a program. a very common Pythonism... if __name__ == '__main__': foo() In my experience, it is quite easy to retrofit any existing scripts you have to follow this form, probably a couple minutes at most. Since there are other benefits to having you program also a module, you'll find most python scripts out there actually do it this way. One benefit of doing it this way: anything python you write is potentially useable in module form, including cProfile-ing of your foo().
Django form - set label
I have a form that inherits from 2 other forms. In my form, I want to change the label of a field that was defined in one of the parent forms. Does anyone know how this can be done? I'm trying to do it in my __init__, but it throws an error saying that "'RegistrationFormTOS' object has no attribute 'email'". Does anyone know how I can do this? Thanks. Here is my form code: from django import forms from django.utils.translation import ugettext_lazy as _ from registration.forms import RegistrationFormUniqueEmail from registration.forms import RegistrationFormTermsOfService attrs_dict = { 'class': 'required' } class RegistrationFormTOS(RegistrationFormUniqueEmail, RegistrationFormTermsOfService): """ Subclass of ``RegistrationForm`` which adds a required checkbox for agreeing to a site's Terms of Service. """ email2 = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_(u'verify email address')) def __init__(self, *args, **kwargs): self.email.label = "New Email Label" super(RegistrationFormTOS, self).__init__(*args, **kwargs) def clean_email2(self): """ Verifiy that the values entered into the two email fields match. """ if 'email' in self.cleaned_data and 'email2' in self.cleaned_data: if self.cleaned_data['email'] != self.cleaned_data['email2']: raise forms.ValidationError(_(u'You must type the same email each time')) return self.cleaned_data
You should use: def __init__(self, *args, **kwargs): super(RegistrationFormTOS, self).__init__(*args, **kwargs) self.fields['email'].label = "New Email Label" Note first you should use the super call.
Showing page count with ReportLab
I'm trying to add a simple "page x of y" to a report made with ReportLab.. I found this old post about it, but maybe six years later something more straightforward has emerged? ^^; I found this recipe too, but when I use it, the resulting PDF is missing the images..
I was able to implement the NumberedCanvas approach from ActiveState. It was very easy to do and did not change much of my existing code. All I had to do was add that NumberedCanvas class and add the canvasmaker attribute when building my doc. I also changed the measurements of where the "x of y" was displayed: self.doc.build(pdf) became self.doc.build(pdf, canvasmaker=NumberedCanvas) doc is a BaseDocTemplate and pdf is my list of flowable elements.
How do I sum the first value in each tuple in a list of tuples in Python?
I have a list of tuples (always pairs) like this: [(0, 1), (2, 3), (5, 7), (2, 1)] I'd like to find the sum of the first items in each pair, i.e.: 0 + 2 + 5 + 2 How can I do this in Python? At the moment I'm iterating through the list: sum = 0 for pair in list_of_pairs: sum += pair[0] I have a feeling there must be a more Pythonic way.
A version compatible with Python 2.3 is sum([pair[0] for pair in list_of_pairs]) or in recent versions of Python, see this answer or this one.
Ruby on Rails versus Python
I am in the field of data crunching and very soon might make a move to the world of web programming. Although I am fascinated both by Python and Ruby as both of them seem to be having every similar styles when it comes to writing business logic or data crunching logic. But when I start googling for web development I start inclining towards Ruby on Rails my question is why is the web world obsessed with ruby on rails and active records so much? There seem to be so many screencasts to learn Ruby on Rails and plethora of good books too why is Python not able to pull the crowd when it comes to creating screencasts or ORM's like active record.
Ruby and Python are languages. Rails is a framework. So it is not really sensible to compare Ruby on Rails vs Python. There are Python Frameworks out there you should take a look at for a more direct comparison - http://wiki.python.org/moin/WebFrameworks (e.g. I know Django gets a lot of love, but there are others) Edit: I've just had a google, there seem to be loads of Django Screencasts.
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. For example: "This is a Test" -> "thisisatest" "A235th@#$&( er Ra{}|?>ndom" -> "atherrandom" I have a simple function to do this: import string import sys def strip_string_to_lowercase(s): tmpStr = s.lower().strip() retStrList = [] for x in tmpStr: if x in string.ascii_lowercase: retStrList.append(x) return ''.join(retStrList) But I cannot help thinking there is a more efficient, or more elegant, way. Thanks! Edit: Thanks to all those that answered. I learned, and in some cases re-learned, a good deal of python.
Another solution (not that pythonic, but very fast) is to use string.translate - though note that this will not work for unicode. It's also worth noting that you can speed up Dana's code by moving the characters into a set (which looks up by hash, rather than performing a linear search each time). Here are the timings I get for various of the solutions given: import string, re, timeit # Precomputed values (for str_join_set and translate) letter_set = frozenset(string.ascii_lowercase + string.ascii_uppercase) tab = string.maketrans(string.ascii_lowercase + string.ascii_uppercase, string.ascii_lowercase * 2) deletions = ''.join(ch for ch in map(chr,range(256)) if ch not in letter_set) s="A235th@#$&( er Ra{}|?>ndom" # From unwind's filter approach def test_filter(s): return filter(lambda x: x in string.ascii_lowercase, s.lower()) # using set instead (and contains) def test_filter_set(s): return filter(letter_set.__contains__, s).lower() # Tomalak's solution def test_regex(s): return re.sub('[^a-z]', '', s.lower()) # Dana's def test_str_join(s): return ''.join(c for c in s.lower() if c in string.ascii_lowercase) # Modified to use a set. def test_str_join_set(s): return ''.join(c for c in s.lower() if c in letter_set) # Translate approach. def test_translate(s): return string.translate(s, tab, deletions) for test in sorted(globals()): if test.startswith("test_"): assert globals()[test](s)=='atherrandom' print "%30s : %s" % (test, timeit.Timer("f(s)", "from __main__ import %s as f, s" % test).timeit(200000)) This gives me: test_filter : 2.57138351271 test_filter_set : 0.981806765698 test_regex : 3.10069885233 test_str_join : 2.87172979743 test_str_join_set : 2.43197956381 test_translate : 0.335367566218 [Edit] Updated with filter solutions as well. (Note that using set.__contains__ makes a big difference here, as it avoids making an extra function call for the lambda.
Unzipping directory structure with python
I have a zip file which contains the following directory structure: dir1\dir2\dir3a dir1\dir2\dir3b I'm trying to unzip it and maintain the directory structure however I get the error: IOError: [Errno 2] No such file or directory: 'C:\\\projects\\\testFolder\\\subdir\\\unzip.exe' where testFolder is dir1 above and subdir is dir2. Is there a quick way of unzipping the file and maintaining the directory structure?
The extract and extractall methods are great if you're on Python 2.6. I have to use Python 2.5 for now, so I just need to create the directories if they don't exist. You can get a listing of directories with the namelist() method. The directories will always end with a forward slash (even on Windows) e.g., import os, zipfile z = zipfile.ZipFile('myfile.zip') for f in z.namelist(): if f.endswith('/'): os.makedirs(f) You probably don't want to do it exactly like that (i.e., you'd probably want to extract the contents of the zip file as you iterate over the namelist), but you get the idea.
How can I remove text within parentheses with a regex?
I'm trying to handle a bunch of files, and I need to alter then to remove extraneous information in the filenames; notably, I'm trying to remove text inside parentheses. For example: filename = "Example_file_(extra_descriptor).ext" and I want to regex a whole bunch of files where the parenthetical expression might be in the middle or at the end, and of variable length. What would the regex look like? Perl or Python syntax would be preferred.
s/\([^)]*\)// So in Python, you'd do: re.sub(r'\([^)]*\)', '', filename)
What's the nearest equivalent of Beautiful Soup for Ruby?
I love the Beautiful Soup scraping library in Python. It just works. Is there a close equivalent in Ruby?
Nokogiri is another HTML/XML parser. It's faster than hpricot according to these benchmarks. Nokogiri uses libxml2 and is a drop in replacement for hpricot. It also has css3 selector support which is pretty nice. Edit: There's a new benchmark comparing nokogiri, libxml-ruby, hpricot and rexml here. Ruby Toolbox has a category on HTML parsers here.
Email integration
I was wondering if someone could help me out. In some web application, the app will send out emails, say when a new message has been posted. Then instead of signing into the application to post a reply you can just simply reply to the email and it will automatically update the web app with your response. My question is, how is this done and what is it called? Thanks
Generally: 1) Set up a dedicated email account for the purpose. 2) Have a programm monitor the mailbox (let's say fetchmail, since that's what I do). 3) When an email arrives at the account, fetchmail downloads the email, writes it to disk, and calls script or program you have written with the email file as an argument. 4) Your script or program parses the email and takes an appropriate action. The part that's usually mysterious to people is the fetchmail part (#2). Specifically on Mail Servers (iff you control the mailserver enough to redirect emails to scripts): 1-3) Configure an address to be piped to a script you have written. 4) Same as above.
How should I log while using multiprocessing in Python?
Right now I have a central module in a framework that spawns multiple processes using the Python 2.6 multiprocessing module. Because it uses multiprocessing, there is module-level multiprocessing-aware log, LOG = multiprocessing.get_logger(). Per the docs, this logger has process-shared locks so that you don't garble things up in sys.stderr (or whatever filehandle) by having multiple processes writing to it simultaneously. The issue I have now is that the other modules in the framework are not multiprocessing-aware. The way I see it, I need to make all dependencies on this central module use multiprocessing-aware logging. That's annoying within the framework, let alone for all clients of the framework. Are there alternatives I'm not thinking of?
I just now wrote a log handler of my own that just feeds everything to the parent process via a pipe. I've only been testing it for ten minutes but it seems to work pretty well. (Note: This is hardcoded to RotatingFileHandler, which is my own use case.) Update: Implementation! This now uses a queue for correct handling of concurrency, and also recovers from errors correctly. I've now been using this in production for several months, and the current version below works without issue. from logging.handlers import RotatingFileHandler import multiprocessing, threading, logging, sys, traceback class MultiProcessingLog(logging.Handler): def __init__(self, name, mode, maxsize, rotate): logging.Handler.__init__(self) self._handler = RotatingFileHandler(name, mode, maxsize, rotate) self.queue = multiprocessing.Queue(-1) t = threading.Thread(target=self.receive) t.daemon = True t.start() def setFormatter(self, fmt): logging.Handler.setFormatter(self, fmt) self._handler.setFormatter(fmt) def receive(self): while True: try: record = self.queue.get() self._handler.emit(record) except (KeyboardInterrupt, SystemExit): raise except EOFError: break except: traceback.print_exc(file=sys.stderr) def send(self, s): self.queue.put_nowait(s) def _format_record(self, record): # ensure that exc_info and args # have been stringified. Removes any chance of # unpickleable things inside and possibly reduces # message size sent over the pipe if record.args: record.msg = record.msg % record.args record.args = None if record.exc_info: dummy = self.format(record) record.exc_info = None return record def emit(self, record): try: s = self._format_record(record) self.send(s) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) def close(self): self._handler.close() logging.Handler.close(self)
Can 3D OpenGL game written in Python look good and run fast?
I am planning to write an simple 3d(isometric view) game in Java using jMonkeyEngine - nothing to fancy, I just want to learn something about OpenGL and writing efficient algorithms (random map generating ones). When I was planning what to do, I started wondering about switching to Python. I know that Python didn't come into existence to be a tool to write 3d games, but is it possible to write good looking games with this language? I have in mind 3d graphics, nice effects and free CPU time to power to rest of game engine? I had seen good looking java games - and too be honest, I was rather shocked when I saw level of detail achieved in Runescape HD. On the other hand, pygame.org has only 2d games, with some starting 3d projects. Are there any efficient 3d game engines for python? Is pyopengl the only alternative? Good looking games in python aren't popular or possible to achieve? I would be grateful for any information / feedback.
If you are worried about 3D performance: Most of the performance-critical parts will be handled by OpenGL (in a C library or even in hardware), so the language you use to drive it should not matter too much. To really find out if performance is a problem, you'd have to try it. But there is no reason why it cannot work in principle. At any rate, you could still optimize the critical parts, either in Python or by dropping to C. You still gain Python's benefit for most of the game engine which is less performance-critical.
Highlighting trailing whitespace in Textmate for Python?
I would like to do something like this Textmate tip, so that trailing whitespace are always highlighted in some way when I code something in Python - it makes it easier to correct it immediately and other editors such as Emacs can do it. Unfortunately the discussion after that post seems to suggest it's difficult to do. For me the invalid.trailing-whitespace scope selector is not even visible in the preferences after following this tip. Has anyone else had any success with this?
I don't know how to highlight the trailing space but you can remove it by going to Bundles -> Text -> Converting/Stripping -> Remove trailing spaces in document Also, because textmate has emacs bindings, you may be able to do it the same way you would do it in emacs.
How to convert strings into integers in Python?
I have a tuple of tuples from a MySQL query like this: T1 = (('13', '17', '18', '21', '32'), ('07', '11', '13', '14', '28'), ('01', '05', '06', '08', '15', '16')) I'd like to convert all the string elements into integers and put it back nicely to list of lists this time: T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]] I tried to achieve it with eval but didn't get any decent result yet.
int() is the Python standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an actual integer: print int("1") + 1 The above prints 2. If you know the structure of your list (that it simply contains lists, only one level), you could do this: T2 = [map(int, x) for x in T1]
How do I format positional argument help using Python's optparse?
As mentioned in the docs the optparse.OptionParser uses an IndentedHelpFormatter to output the formatted option help, for which which I found some API documentation. I want to display a similarly formatted help text for the required, positional arguments in the usage text. Is there an adapter or a simple usage pattern that can be used for similar positional argument formatting? Clarification Preferably only using the stdlib. Optparse does great except for this one formatting nuance, which I feel like we should be able to fix without importing whole other packages. :-)
The best bet would be to write a patch to the optparse module. In the meantime, you can accomplish this with a slightly modified OptionParser class. This isn't perfect, but it'll get what you want done. #!/usr/bin/env python from optparse import OptionParser, Option, IndentedHelpFormatter class PosOptionParser(OptionParser): def format_help(self, formatter=None): class Positional(object): def __init__(self, args): self.option_groups = [] self.option_list = args positional = Positional(self.positional) formatter = IndentedHelpFormatter() formatter.store_option_strings(positional) output = ['\n', formatter.format_heading("Positional Arguments")] formatter.indent() pos_help = [formatter.format_option(opt) for opt in self.positional] pos_help = [line.replace('--','') for line in pos_help] output += pos_help return OptionParser.format_help(self, formatter) + ''.join(output) def add_positional_argument(self, option): try: args = self.positional except AttributeError: args = [] args.append(option) self.positional = args def set_out(self, out): self.out = out def main(): usage = "usage: %prog [options] bar baz" parser = PosOptionParser(usage) parser.add_option('-f', '--foo', dest='foo', help='Enable foo') parser.add_positional_argument(Option('--bar', action='store_true', help='The bar positional argument')) parser.add_positional_argument(Option('--baz', action='store_true', help='The baz positional argument')) (options, args) = parser.parse_args() if len(args) != 2: parser.error("incorrect number of arguments") pass if __name__ == '__main__': main() And the output you get from running this: Usage: test.py [options] bar baz Options: -h, --help show this help message and exit -f FOO, --foo=FOO Enable foo Positional Arguments: bar The bar positional argument baz The baz positional argument
Is it possible to replace a function/method decorator at runtime? [ python ]
If I have a function : @aDecorator def myfunc1(): # do something here if __name__ = "__main__": # this will call the function and will use the decorator @aDecorator myfunc1() # now I want the @aDecorator to be replaced with the decorator @otherDecorator # so that when this code executes, the function no longer goes through # @aDecorator, but instead through @otherDecorator. How can I do this? myfunc1() Is it possible to replace a decorator at runtime?
As Miya mentioned, you can replace the decorator with another function any point before the interpreter gets to that function declaration. However, once the decorator is applied to the function, I don't think there is a way to dynamically replace the decorator with a different one. So for example: @aDecorator def myfunc1(): pass # Oops! I didn't want that decorator after all! myfunc1 = bDecorator(myfunc1) Won't work, because myfunc1 is no longer the function you originally defined; it has already been wrapped. The best approach here is to manually apply the decorators, oldskool-style, i.e: def myfunc1(): pass myfunc2 = aDecorator(myfunc1) myfunc3 = bDecorator(myfunc1) Edit: Or, to be a little clearer, def _tempFunc(): pass myfunc1 = aDecorator(_tempFunc) myfunc1() myfunc1 = bDecorator(_tempFunc) myfunc1()
Python - Intersection of two lists
I know how to get an intersection of two flat lists: b1 = [1,2,3,4,5,9,11,15] b2 = [4,5,6,7,8] b3 = [val for val in b1 if val in b2] or def intersect(a, b): return list(set(a) & set(b)) print intersect(b1, b2) But when I have to find intersection for nested lists then my problems starts: c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63] c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]] In the end I would like to receive: c3 = [[13,32],[7,13,28],[1,6]] Can you guys give me a hand with this? Related Flattening a shallow list in python
You don't need to define intersection. It's already a first-class part of set. >>> b1 = [1,2,3,4,5,9,11,15] >>> b2 = [4,5,6,7,8] >>> set(b1).intersection(b2) set([4, 5])
How can I use numpy.correlate to do autocorrelation?
I need to do auto-correlation of a set of numbers, which as I understand it is just the correlation of the set with itself. I've tried it using numpy's correlate function, but I don't believe the result, as it almost always gives a vector where the first number is not the largest, as it ought to be. So, this question is really two questions: What exactly is numpy.correlate doing? How can I use it (or something else) to do auto-correlation?
To answer your first question, numpy.correlate(a, v, mode) is performing the convolution of a with the reverse of v and giving the results clipped by the specified mode. The definition of convolution, C(t)=∑ -∞ < i < ∞ aivt+i where -∞ < t < ∞, allows for results from -∞ to ∞, but you obviously can't store an infinitely long array. So it has to be clipped, and that is where the mode comes in. There are 3 different modes: full, same, & valid: "full" mode returns results for every t where both a and v have some overlap. "same" mode returns a result with the same length as the shortest vector (a or v). "valid" mode returns results only when a and v completely overlap each other. The documentation for numpy.convolve gives more detail on the modes. For your second question, I think numpy.correlate is giving you the autocorrelation, it is just giving you a little more as well. The autocorrelation is used to find how similar a signal, or function, is to itself at a certain time difference. At a time difference of 0, the auto-correlation should be the highest because the signal is identical to itself, so you expected that the first element in the autocorrelation result array would be the greatest. However, the correlation is not starting at a time difference of 0. It starts at a negative time difference, closes to 0, and then goes positive. That is, you were expecting: autocorrelation(a) = ∑ -∞ < i < ∞ aivt+i where 0 <= t < ∞ But what you got was: autocorrelation(a) = ∑ -∞ < i < ∞ aivt+i where -∞ < t < ∞ What you need to do is take the last half of your correlation result, and that should be the autocorrelation you are looking for. A simple python function to do that would be: def autocorr(x): result = numpy.correlate(x, x, mode='full') return result[result.size/2:] You will, of course, need error checking to make sure that x is actually a 1-d array. Also, this explanation probably isn't the most mathematically rigorous. I've been throwing around infinities because the definition of convolution uses them, but that doesn't necessarily apply for autocorrelation. So, the theoretical portion of this explanation may be slightly wonky, but hopefully the practical results are helpful. These pages on autocorrelation are pretty helpful, and can give you a much better theoretical background if you don't mind wading through the notation and heavy concepts.
Python - list transformation
Does anyone knows what magic I have to use to change x list: x = [1,2,3,4,5,11] into y list? y = ['01','02','03','04','05','11'] Thank you all in advance for helping me...
You can use a list comprehension (Python 2.6+): y = ["{0:0>2}".format(v) for v in x] Or for Python prior to 2.6: y = ["%02d" % v for v in x] Edit: Missed the fact that you wanted zero-padding...
How does Python sort a list of tuples?
Empirically, it seems that Python's default list sorter, when passed a list of tuples, will sort by the first element in each tuple. Is that correct? If not, what's the right way to sort a list of tuples by their first elements?
It automatically sorts a list of tuples by the first elements in the tuples, then by the second elements and so on tuple([1,2,3]) will go before tuple([1,2,4]). If you want to override this behaviour pass a callable as the second argument to the sort method. This callable should return 1, -1, 0.
How do I re-map python dict keys
I am working on a program that (among other things) reads a CSV file in (it gets stored as an array of dicts in the form [{col1:data1a,col2:data2a},{col1:data1b,col2:data2b}] ). For each row, as part of other processing, I need to remap those keys to user entered values, which are provided in another dict so they can be used as parameters in an API call. The mapping array is in the form: {badname1:goodname1, badname2:goodname2,...}. So I'd like to get from: {badname1:data1, badname2:data2,...} to {goodname1:data1, goodname2:data2,...} I'd like to use something like zip() (although zip() yields {badname1:badname1,...}). Seems like there should be an obvious solution that is alluding me. EDIT: If the data is in a and the mapping in b: dict(zip(b,a.itervalues())) I get close, but it will only work in cases where the fields are known to be in the same order I think.
name_map = {'oldcol1': 'newcol1', 'oldcol2': 'newcol2', 'oldcol3': 'newcol3'...} for row in rows: # Each row is a dict of the form: {'oldcol1': '...', 'oldcol2': '...'} row = dict((name_map[name], val) for name, val in row.iteritems()) ... Or in Python2.7+ with Dict Comprehensions: for row in rows: row = {name_map[name]: val for name, val in row.items()}
Converting from mod_python to mod_wsgi
My website is written in Python and currently runs under mod_python with Apache. Lately I've had to put in a few ugly hacks that make me think it might be worth converting the site to mod_wsgi. But I've gotten used to using some of mod_python's utility classes, especially FieldStorage and Session (and sometimes Cookie), and from a scan of PEP 333, I don't see any equivalents to these. (Not surprising, because I understand that those kinds of utilities don't belong in the WSGI spec) Question is, are there "standard" (i.e. commonly accepted) replacements for these mod_python utility classes that I can use in WSGI, or could I/should I write my own? (FYI: currently using Python 2.5)
Look at Werkzeug. You may have to do some rewriting. You will probably be pleased with the results of imposing the WSGI world-view on your application.
Python: How to run unittest.main() for all source files in a subdirectory?
I am developing a Python module with several source files, each with its own test class derived from unittest right in the source. Consider the directory structure: dirFoo\ test.py dirBar\ __init__.py Foo.py Bar.py To test either Foo.py or Bar.py, I would add this at the end of the Foo.py and Bar.py source files: if __name__ == "__main__": unittest.main() And run Python on either source, i.e. $ python Foo.py ........... ---------------------------------------------------------------------- Ran 11 tests in 2.314s OK Ideally, I would have "test.py" automagically search dirBar for any unittest derived classes and make one call to "unittest.main()". What's the best way to do this in practice? I tried using Python to call execfile for every *.py file in dirBar, which runs once for the first .py file found & exits the calling test.py, plus then I have to duplicate my code by adding unittest.main() in every source file--which violates DRY principles.
As of Python 2.7, test discovery is automated in the unittest package. From the docs: Unittest supports simple test discovery. In order to be compatible with test discovery, all of the test files must be modules or packages importable from the top-level directory of the project (this means that their filenames must be valid identifiers). Test discovery is implemented in TestLoader.discover(), but can also be used from the command line. The basic command-line usage is: cd project_directory python -m unittest discover By default it looks for packages named test*.py, but this can be changed so you might use something like python -m unittest discover --pattern=*.py In place of your test.py script.
What is the quickest way to HTTP GET in Python?
What is the quickest way to HTTP GET in Python if I know the Content will be a string? I am searching the docs for a quick one-liner like: contents = url.get("http://example.com/foo/bar") But all I can find using Google are httplib and urllib - and I am unable to find a shortcut in those libraries. Does standard Python 2.5 have a shortcut in some form as above, or should I write a function url_get? I would prefer not to capture the output of shelling out to wget or curl.
Python 2.x: import urllib2 urllib2.urlopen("http://example.com/foo/bar").read() Python 3.x: import urllib.request urllib.request.urlopen("http://example.com/foo/bar").read() Documentation for urllib.request and read. How is that?
Discussion of multiple inheritance vs Composition for a project (+other things)
I am writing a python platform for the simulation of distributed sensor swarms. The idea being that the end user can write a custom Node consisting of the SensorNode behaviour (communication, logging, etc) as well as implementing a number of different sensors. The example below briefly demonstrates the concept. #prewritten class Sensor(object): def __init__(self): print "Hello from Sensor" #... #prewritten class PositionSensor(Sensor): def __init__(self): print "Hello from Position" Sensor.__init__(self) #... #prewritten class BearingSensor(Sensor): def __init__(self): print "Hello from Bearing" Sensor.__init__(self) #... #prewritten class SensorNode(object): def __init__(self): print "Hello from SensorNode" #... #USER WRITTEN class MySensorNode(SensorNode,BearingSensor,PositionSensor): def CustomMethod(self): LogData={'Position':position(), 'Bearing':bearing()} #position() from PositionSensor, bearing() from BearingSensor Log(LogData) #Log() from SensorNode NEW EDIT: Firstly an overview of what I am trying to achieve: I am writing a simulator to simulate swarm intelligence algorithms with particular focus on mobile sensor networks. These networks consist of many small robots communicating individual sensor data to build a complex sensory map of the environment. The underlying goal of this project is to develop a simulation platform that provides abstracted interfaces to sensors such that the same user-implemented functionality can be directly ported to a robotic swarm running embedded linux. As robotic implementation is the goal, I need to design such that the software node behaves the same, and only has access to information that an physical node would have. As part of the simulation engine, I will be providing a set of classes modelling different types of sensors and different types of sensor node. I wish to abstract all this complexity away from the user such that all the user must do is define which sensors are present on the node, and what type of sensor node (mobile, fixed position) is being implemented. My initial thinking was that every sensor would provide a read() method which would return the relevant values, however having read the responses to the question, I see that perhaps more descriptive method names would be beneficial (.distance(), .position(), .bearing(), etc). I initially wanted use separate classes for the sensors (with common ancestors) so that a more technical user can easily extend one of the existing classes to create a new sensor if they wish. For example: Sensor | DistanceSensor(designed for 360 degree scan range) | | | IR Sensor Ultrasonic SickLaser (narrow) (wider) (very wide) The reason I was initially thinking of Multiple Inheritance (although it semi-breaks the IS-A relationship of inheritance) was due to the underlying principle behind the simulation system. Let me explain: The user-implemented MySensorNode should not have direct access to its position within the environment (akin to a robot, the access is indirect through a sensor interface), similarly, the sensors should not know where they are. However, this lack of direct knowledge poses a problem, as the return values of the sensors are all dependent on their position and orientation within the environment (which needs to be simulated to return the correct values). SensorNode, as a class implemented within the simulation libraries, is responsible for drawing the MySensorNode within the pygame environment - thus, it is the only class that should have direct access to the position and orientation of the sensor node within the environment. SensorNode is also responsible for translation and rotation within the environment, however this translation and rotation is a side effect of motor actuation. What I mean by this is that robots cannot directly alter their position within the world, all they can do is provide power to motors, and movement within the world is a side-effect of the motors interaction with the environment. I need to model this accurately within the simulation. So, to move, the user-implemented functionality may use: motors(50,50) This call will, as a side-effect, alter the position of the node within the world. If SensorNode was implemented using composition, SensorNode.motors(...) would not be able to directly alter instance variables (such as position), nor would MySensorNode.draw() be resolved to SensorNode.draw(), so SensorNode imo should be implemented using inheritance. In terms of the sensors, the benefit of composition for a problem like this is obvious, MySensorNode is composed of a number of sensors - enough said. However the problem as I see it is that the Sensors need access to their position and orientation within the world, and if you use composition you will end up with a call like: >>> PosSensor.position((123,456)) (123,456) Then again - thinking, you could pass self to the sensor upon initialisation, eg: PosSensor = PositionSensor(self) then later PosSensor.position() however this PosSensor.position() would then need to access information local to the instance (passed as self during init()), so why call PosSensor at all when you can access the information locally? Also passing your instance to an object you are composed of just seems not quite right, crossing the boundaries of encapsulation and information hiding (even though python doesn't do much to support the idea of information hiding). If the solution was implemented using multiple inheritance, these problems would disappear: class MySensorNode(SensorNode,PositionSensor,BearingSensor): def Think(): while bearing()>0: # bearing() is provided by BearingSensor and in the simulator # will simply access local variables provided by SensorNode # to return the bearing. In robotic implementation, the # bearing() method will instead access C routines to read # the actual bearing from a compass sensor motors(100,-100) # spin on the spot, will as a side-effect alter the return # value of bearing() (Ox,Oy)=position() #provided by PositionSensor while True: (Cx,Cy)=position() if Cx>=Ox+100: break else: motors(100,100) #full speed ahead!will alter the return value of position() Hopefully this edit has clarified some things, if you have any questions I'm more than happy to try and clarify them OLD THINGS: When an object of type MySensorNode is constructed, all constructors from the superclasses need to be called. I do not want to complicate the user with having to write a custom constructor for MySensorNode which calls the constructor from each superclass. Ideally, what I would like to happen is: mSN = MySensorNode() # at this point, the __init__() method is searched for # and SensorNode.__init__() is called given the order # of inheritance in MySensorNode.__mro__ # Somehow, I would also like to call all the other constructors # that were not executed (ie BearingSensor and PositionSensor) Any insight or general comments would be appreciated, Cheers :) OLD EDIT: Doing something like: #prewritten class SensorNode(object): def __init__(self): print "Hello from SensorNode" for clss in type(self).__mro__: if clss!=SensorNode and clss!=type(self): clss.__init__(self) This works, as self is an instance of MySensorNode. However this solution is messy.
The sensor architecture can be solved by using composition if you want to stick to your original map-of-data design. You seem to be new to Python so I'll try to keep idioms to a minimum. class IRSensor: def read(self): return {'ir_amplitude': 12} class UltrasonicSensor: def read(self): return {'ultrasonic_amplitude': 63} class SickLaserSensor: def read(self): return {'laser_amplitude': 55} class CompositeSensor: """Wrap multiple component sensors, coalesce the results, and return the composite readout. """ component_sensors = [] def __init__(self, component_sensors=None): component_sensors = component_sensors or self.component_sensors self.sensors = [cls() for cls in component_sensors] def read(self): measurements = {} for sensor in self.sensors: measurements.update(sensor.read()) return measurements class MyCompositeSensor(CompositeSensor): component_sensors = [UltrasonicSensor, IRSensor] composite_sensor = MyCompositeSensor() measurement_map = composite_sensor.read() assert measurement_map['ultrasonic_amplitude'] == 63 assert measurement_map['ir_amplitude'] == 12 The architectural problem you're describing with the actuators is solved by using mixins and proxying (via __getattr__) rather than inheritance. (Proxying can be a nice alternative to inheritance because objects to proxy to can be bound/unbound at runtime. Also, you don't have to worry about handling all initialization in a single constructor using this technique.) class MovementActuator: def __init__(self, x=0, y=0): self.x, self.y = (x, y) def move(self, x, y): print 'Moving to', x, y self.x, self.y = (x, y) def get_position(self): return (self.x, self.y) class CommunicationActuator: def communicate(self): return 'Hey you out there!' class CompositeActuator: component_actuators = [] def __init__(self, component_actuators=None): component_actuators = component_actuators \ or self.component_actuators self.actuators = [cls() for cls in component_actuators] def __getattr__(self, attr_name): """Look for value in component sensors.""" for actuator in self.actuators: if hasattr(actuator, attr_name): return getattr(actuator, attr_name) raise AttributeError(attr_name) class MyCompositeActuator(CompositeActuator): component_actuators = [MovementActuator, CommunicationActuator] composite_actuator = MyCompositeActuator() assert composite_actuator.get_position() == (0, 0) assert composite_actuator.communicate() == 'Hey you out there!' And finally, you can throw it all together with a simple node declaration: from sensors import * from actuators import * class AbstractNode: sensors = [] # Set of classes. actuators = [] # Set of classes. def __init__(self): self.composite_sensor = CompositeSensor(self.sensors) self.composite_actuator = CompositeActuator(self.actuators) class MyNode(AbstractNode): sensors = [UltrasonicSensor, SickLaserSensor] actuators = [MovementActuator, CommunicationActuator] def think(self): measurement_map = self.composite_sensor.read() while self.composite_actuator.get_position()[1] >= 0: self.composite_actuator.move(100, -100) my_node = MyNode() my_node.think() That should give you an idea of the alternatives to the rigid type system. Note that you don't have to rely on the type hierarchy at all -- just implement to a (potentially implicit) common interface. LESS OLD: After reading the question more carefully, I see that what you have is a classic example of diamond inheritance, which is the evil that makes people flee towards single inheritance. You probably don't want this to begin with, since class hierarchy means squat in Python. What you want to do is make a SensorInterface (minimum requirements for a sensor) and have a bunch of "mixin" classes that have totally independent functionality that can be invoked through methods of various names. In your sensor framework you shouldn't say things like isinstance(sensor, PositionSensor) -- you should say things like "can this sensor geo-locate?" in the following form: def get_position(sensor): try: return sensor.geolocate() except AttributeError: return None This is the heart of duck-typing philosophy and EAFP (Easier to Ask for Forgiveness than Permission), both of which the Python language embraces. You should probably describe what methods these sensors will actually implement so we can describe how you can use mixin classes for your plugin architecture. OLD: If they write the code in a module that gets put in a plugin package or what have you, you can magically instrument the classes for them when you import their plugin modules. Something along the lines of this snippet (untested): import inspect import types from sensors import Sensor def is_class(obj): return type(obj) in (types.ClassType, types.TypeType) def instrumented_init(self, *args, **kwargs): Sensor.__init__(self, *args, **kwargs) for module in plugin_modules: # Get this from somewhere... classes = inspect.getmembers(module, predicate=is_class) for name, cls in classes: if hasattr(cls, '__init__'): # User specified own init, may be deriving from something else. continue if cls.__bases__ != tuple([Sensor]): continue # Class doesn't singly inherit from sensor. cls.__init__ = instrumented_init You can find the modules within a package with another function.
Integrating MySQL with Python in Windows
I am finding it difficult to use MySQL with Python in my windows system. I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module. Any help ?
Download page for python-mysqldb. The page includes binaries for 32 and 64 bit versions of for Python 2.5, 2.6 and 2.7. There's also discussion on getting rid of the deprecation warning. UPDATE: This is an old answer. Currently, I would recommend using PyMySQL. It's pure python, so it supports all OSes equally, it's almost a drop-in replacement for mysqldb, and it also works with python 3. The best way to install it is using pip. You can install it from here (more instructions here), and then run: pip install pymysql
Python PIL: how to write PNG image to string
I have generated an image using PIL. How can I save it to a string in memory? The Image.save() method requires a file. I'd like to have several such images stored in dictionary.
You can probably use the StringIO class to get a wrapper around strings that behaves like a file. The StringIO object provides the same interface as a file, but saves the contents just in memory: import StringIO output = StringIO.StringIO() image.save(output) contents = output.getvalue() output.close() This might lead to a KeyError if PIL tries to automatically detect the output format. To avoid this problem you can specify the format manually: image.save(output, format="GIF")
Python: How to detect debug interpreter
How can I detect in my python script if its being run by the debug interpreter (ie python_d.exe rather than python.exe)? I need to change the paths to some dlls that I pass to an extension. eg Id like to do something like this at the start of my python script: #get paths to graphics dlls if debug_build: d3d9Path = "bin\\debug\\direct3d9.dll" d3d10Path = "bin\\debug\\direct3d10.dll" openGLPath = "bin\\debug\\openGL2.dll" else: d3d9Path = "bin\\direct3d9.dll" d3d10Path = "bin\\direct3d10.dll" openGLPath = "bin\\openGL2.dll" I thought about adding an "IsDebug()" method to the extension which would return true if it is the debug build (ie was built with "#define DEBUG") and false otherwise. But this seems a bit of a hack for somthing Im sure I can get python to tell me...
Distutils use sys.gettotalrefcount to detect a debug python build: # ... if hasattr(sys, 'gettotalrefcount'): plat_specifier += '-pydebug' this method doesn't rely on an executable name '*_d.exe'. It works for any name. this method is cross-platform. It doesn't depend on '_d.pyd' suffix. See Debugging Builds and Misc/SpecialBuilds.txt
How to get last items of a list in Python?
I need the last 9 numbers of a list and I'm sure there is a way to do it with slicing, but I can't seem to get it. I can get the first 9 like this: num_list[0:9] Any help would be great.
You can use negative integers with the slicing operator for that. Here's an example using the python CLI interpreter: >>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> a[-9:] [4, 5, 6, 7, 8, 9, 10, 11, 12] the important line is a[-9:]
Need a simple "Hello World" example using the Webkit library in Python
Does anyone know of a simple "Hello World" example for using the Webkit library in Python? I have a GTK window, and inside I want to put Webkit. With Python/mozembed (Mozilla/Gecko), this is simple: mozembed = gtkmozembed.MozEmbed() mozembed.load_url('http://google.com/') ..and I have already created my browser, how do I do this with WebKit?
Did you check the Python bindings for the WebKit GTK+ port. In one of the directory there are demos on how to use it, including a browser: python demos/tabbed_browser.py You could check also the slides of a FOSDEM by Alp Toker on WebKit GTK+ (pdf) Developing hybrid Web/GTK+ rich internet applications. import gtk import webkit view = webkit.WebView() sw = gtk.ScrolledWindow() sw.add(view) win = gtk.Window(gtk.WINDOW_TOPLEVEL) win.add(sw) win.show_all() view.open("http://w3.org/") gtk.main() That should give you good hints for starting.
Python xml ElementTree from a string source?
The ElementTree.parse reads from a file, how can I use this if I already have the XML data in a string? Maybe I am missing something here, but there must be a way to use the ElementTree without writing out the string to a file and reading it again. xml.etree.elementtree
You can parse the text as a string, which creates an Element, and create an ElementTree using that Element. import xml.etree.ElementTree as ET tree = ET.ElementTree(ET.fromstring(xmlstring)) I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse and fromstring methods.
How can I know python's path under windows?
I want to know where is the python's installation path. For example: C:\Python25 But however, I have no idea how to do. How can I get the installation path of python? Thanks.
>>> import os >>> import sys >>> os.path.dirname(sys.executable) 'C:\\Python25'
python, regex split and special character
How can I split correctly a string containing a sentence with special chars using whitespaces as separator ? Using regex split method I cannot obtain the desired result. Example code: # -*- coding: utf-8 -*- import re s="La felicità è tutto" # "The happiness is everything" in italian l=re.compile("(\W)").split(s) print " s> "+s print " wordlist> "+str(l) for i in l: print " word> "+i The output is : s> La felicità è tutto wordlist> ['La', ' ', 'felicit', '\xc3', '', '\xa0', '', ' ', '', '\xc3', '', '\xa8', '', ' ', 'tutto'] word> La word> word> felicit word> Ã word> word> ? word> word> word> word> Ã word> word> ? word> word> word> tutto while I'm looking for an output like: s> La felicità è tutto wordlist> ['La', ' ', 'felicità', ' ', 'è', ' ', 'tutto'] word> La word> word> felicità word> word> è word> word> tutto To be noted that s is a string that is returned from another method so I cannot force the encoding like s=u"La felicità è tutto" On official python documentation of Unicode and reg-ex I haven't found a satisfactory explanation. Thanks. Alessandro
Your regex should be (\s) instead of (\W) like this: l = re.compile("(\s)").split(s) The code above will give you the exact output you requested. However the following line makes more sense: l = re.compile("\s").split(s) which splits on whitespace characters and doesn't give you all the spaces as matches. You may need them though so I posted both answers.
Why can't Python's raw string literals end with a single backslash?
Technically, any odd number of backslashes, as described in the docs. >>> r'\' File "<stdin>", line 1 r'\' ^ SyntaxError: EOL while scanning string literal >>> r'\\' '\\\\' >>> r'\\\' File "<stdin>", line 1 r'\\\' ^ SyntaxError: EOL while scanning string literal It seems like the parser could just treat backslashes in raw strings as regular characters (isn't that what raw strings are all about?), but I'm probably missing something obvious. TIA!
The reason is explained in the part of that section which I highlighted in bold: String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation. So raw strings are not 100% raw, there is still some rudimentary backslash-processing.
Trapping MySQL Warnings In Python
I would like to catch and log MySQL warnings in Python. For example, MySQL issues a warning to standard error if you submit 'DROP DATABASE IF EXISTS database_of_armaments' when no such database exists. I would like to catch this and log it, but even in the try/else syntax the warning message still appears. The try/except syntax does catch MySQL errors (eg, submission of a typo like 'DRP DATABASE database_of_armaments'). I have experimented with <<except.MySQLdb.Warning>> -- no luck. I've looked at the warnings module, but don't understand how to incorporate it into the try/else syntax. To be concrete, how do I get the following (or something like it) to work. GIVEN: database 'database_of_armaments' does not exist. try: cursor.execute('DROP DATABASE IF EXISTS database_of_armaments') except: <<WHAT DO I PUT HERE?>> print 'There was a MySQL warning.' <<AND what goes here if I want to get and manipulate information about the warning?>> UPDATE: Thanks for the comments. I had tried these and they didn't work -- but I had been using a DatabaseConnection class that I wrote for a connection, and its runQuery() method to execute. When I created a connection and cursor outside the class, the try/except Exception caught the "Programming Error", and except MySQLdb.ProgrammingError worked as advertised. So now I have to figure out what is wrong with my class coding. Thank you for your help.
Follow these steps. Run it with except Exception, e: print repr(e). See what exception you get. Change the Exception to the exception you actually got. Also, remember that the exception, e, is an object. You can print dir(e), e.__class__.__name__, etc.to see what attributes it has. Also, you can do this interactively at the >>> prompt in Python. You can then manipulate the object directly -- no guessing.
Python - test that succeeds when exception is not raised
I know about unittest Python module. I know about assertRaises() method of TestCase class. I would like to write a test that succeeds when an exception is not raised. Any hints please?
def runTest(self): try: doStuff() except: self.fail("Encountered an unexpected exception.") UPDATE: As liw.fi mentions, the default result is a success, so the example above is something of an antipattern. You should probably only use it if you want to do something special before failing. You should also catch the most specific exceptions possible.
Concurrency: Are Python extensions written in C/C++ affected by the Global Interpreter Lock?
One of Python's strongest points is the ease of writing C and C++ extensions to speed up processor intensive parts of the code. Can these extensions avoid the Global Interpreter Lock or are they also restricted by the GIL? If not, then this "ease of extension" is even more of a killer feature than I previously realized. I suspect the answer is not a simple yes-or-no but I am not sure, so I am asking the question here on StackOverflow.
Yes, calls to C extensions (C routines called from Python) are still subject to the GIL. However, you can manually release the GIL inside your C extension, so long as you are careful to re-assert it before returning control to the Python VM. For information, take a look at the Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros: http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock
Is it possible to create anonymous objects in Python?
I'm debugging some Python that takes, as input, a list of objects, each with some attributes. I'd like to hard-code some test values -- let's say, a list of four objects whose "foo" attribute is set to some number. Is there a more concise way than this? x1.foo = 1 x2.foo = 2 x3.foo = 3 x4.foo = 4 myfunc([x1, x2, x3, x4]) Ideally, I'd just like to be able to say something like: myfunc([<foo=1>, <foo=2>, <foo=3>, <foo=4>]) (Obviously, that is made-up syntax. But is there something similar that really works?) Note: This will never be checked in. It's just some throwaway debug code. So don't worry about readability or maintainability.
I like Tetha's solution, but it's unnecessarily complex. Here's something simpler: >>> class MicroMock(object): ... def __init__(self, **kwargs): ... self.__dict__.update(kwargs) ... >>> def print_foo(x): ... print x.foo ... >>> print_foo(MicroMock(foo=3)) 3
sorting a list of dictionary values by date in python
I have a list and I am appending a dictionary to it as I loop through my data...and I would like to sort by one of the dictionary keys. ex: data = "data from database" list = [] for x in data: dict = {'title':title, 'date': x.created_on} list.append(dict) I want to sort the list in reverse order by value of 'date'
You can do it this way: list.sort(key=lambda item:item['date'], reverse=True)
How to create a Python decorator that can be used either with or without parameters?
I'd like to create a Python decorator that can be used either with parameters: @redirect_output("somewhere.log") def foo(): .... or without them (for instance to redirect the output to stderr by default): @redirect_output def foo(): .... Is that at all possible? Note that I'm not looking for a different solution to the problem of redirecting output, it's just an example of the syntax I'd like to achieve.
Using keyword arguments with default values (as suggested by kquinn) is a good idea, but will require you to include the parenthesis: @redirect_output() def foo(): ... If you would like a version that works without the parenthesis on the decorator you will have to account both scenarios in your decorator code. If you were using Python 3.0 you could use keyword only arguments for this: def redirect_output(fn=None,*,destination=None): destination = sys.stderr if destination is None else destination def wrapper(*args, **kwargs): ... # your code here if fn is None: def decorator(fn): return functools.update_wrapper(wrapper, fn) return decorator else: return functools.update_wrapper(wrapper, fn) In Python 2.x this can be emulated with varargs tricks: def redirected_output(*fn,**options): destination = options.pop('destination', sys.stderr) if options: raise TypeError("unsupported keyword arguments: %s" % ",".join(options.keys())) def wrapper(*args, **kwargs): ... # your code here if fn: return functools.update_wrapper(wrapper, fn[0]) else: def decorator(fn): return functools.update_wrapper(wrapper, fn) return decorator Any of these versions would allow you to write code like this: @redirected_output def foo(): ... @redirected_output(destination="somewhere.log") def bar(): ...
How can I profile a multithread program in Python?
I'm developing an inherently multithreaded module in Python, and I'd like to find out where it's spending its time. cProfile only seems to profile the main thread. Is there any way of profiling all threads involved in the calculation?
Please see yappi (Yet Another Python Profiler).
How can I cluster a graph in Python?
Let G be a graph. So G is a set of nodes and set of links. I need to find a fast way to partition the graph. The graph I am now working has only 120*160 nodes, but I might soon be working on an equivalent problem, in another context (not medicine, but website development), with millions of nodes. So, what I did was to store all the links into a graph matrix: M=numpy.mat(numpy.zeros((len(data.keys()),len(data.keys())))) Now M holds a 1 in position s,t, if node s is connected to node t. I make sure M is symmetrical M[s,t]=M[t,s] and each node links to itself M[s,s]=1. If I remember well if I multiply M with M, the results is a matrix that represents the graph that connects vertexes that are reached on through two steps. So I keep on multplying M with itself, until the number of zeros in the matrix do not decrease any longer. Now I have the list of the connected components. And now I need to cluster this matrix. Up to now I am pretty satisfied with the algorithm. I think it is easy, elegant, and reasonably fast. I am having trouble with this part. Essentially I need to split this graph into its connected components. I can go through all the nodes, and see what are they connected to. But what about sorting the matrix reordering the lines. But I don't know if it is possible to do it. What follows is the code so far: def findzeros(M): nZeros=0 for t in M.flat: if not t: nZeros+=1 return nZeros M=numpy.mat(numpy.zeros((len(data.keys()),len(data.keys())))) for s in data.keys(): MatrixCells[s,s]=1 for t in data.keys(): if t<s: if (scipy.corrcoef(data[t],data[s])[0,1])>threashold: M[s,t]=1 M[t,s]=1 nZeros=findzeros(M) M2=M*M nZeros2=findzeros(M2) while (nZeros-nZeros2): nZeros=nZeros2 M=M2 M2=M*M nZeros2=findzeros(M2) Edit: It has been suggested that I use SVD decomposition. Here is a simple example of the problem on a 5x5 graph. We shall use this since with the 19200x19200 square matrix is not that easy to see the clusters. import numpy import scipy M=numpy.mat(numpy.zeros((5,5))) M[1,3]=1 M[3,1]=1 M[1,1]=1 M[2,2]=1 M[3,3]=1 M[4,4]=1 M[0,0]=1 print M u,s,vh = numpy.linalg.linalg.svd(M) print u print s print vh Essentially there are 4 clusters here: (0),(1,3),(2),(4) But I still don't see how the svn can help in this context.
Why not use a real graph library, like Python-Graph? It has a function to determine connected components (though no example is provided). I'd imagine a dedicated library is going to be faster than whatever ad-hoc graph code you've cooked up. EDIT: NetworkX seems like it might be a better choice than python-graph; its documentation (here for the connected components function) certainly is.
Django Forms, set an initial value to request.user
Is there some way to make the following possible, or should it be done elsewhere? class JobRecordForm(forms.ModelForm): supervisor = forms.ModelChoiceField( queryset = User.objects.filter(groups__name='Supervisors'), widget = forms.RadioSelect, initial = request.user # is there some way to make this possible? ) class Meta: model = JobRecord
If you do this in your view.py instead: form = JobRecordForm( initial={'supervisor':request.user} ) Then you won't trigger the validation. See http://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values
Equivalent for LinkedHashMap in Python
LinkedHashMap is the Java implementation of a Hashtable like data structure (dict in Python) with predictable iteration order. That means that during a traversal over all keys, they are ordered by insertion. This is done by an additional linked list maintaining the insertion order. Is there an equivalent to that in Python?
Although you can do the same thing by maintaining a list to keep track of insertion order, Python 2.7 and Python >=3.1 have an OrderedDict class in the collections module. Before 2.7, you can subclass dict following this recipe.
Python file modes detail
In Python, the following statements do not work: f = open("ftmp", "rw") print >> f, "python" I get the error: Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 9] Bad file descriptor But with the following code it works: g = open("ftmp", "r+") print >> g, "python" It looks like I need to revise the file modes. What are the deep intricacies of the file opening modes?
Better yet, let the documentation do it for you: http://docs.python.org/library/functions.html#open. Your issue in the question is that there is no "rw" mode... you probably want 'r+' as you wrote (or 'a+' if the file does not yet exist).
Why did Python 2.6 add a global next() function?
I noticed that Python2.6 added a next() to it's list of global functions. next(iterator[, default]) Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised. What was the motivation for adding this? What can you do with next(iterator) that you can't do with iterator.next() and an except clause to handle the StopIteration?
It's just for consistency with functions like len(). I believe next(i) calls i.__next__() internally. See http://www.python.org/dev/peps/pep-3114/
python time + timedelta equivalent
I'm trying to do something like this: time() + timedelta(hours=1) however, Python doesn't allow it, apparently for good reason. Does anyone have a simple work around? Related: Python - easy way to add N seconds to a datetime.time?
The solution is in the link that you provided in your question: datetime.combine(date.today(), time()) + timedelta(hours=1) Full example: from datetime import date, datetime, time, timedelta dt = datetime.combine(date.today(), time(23, 55)) + timedelta(minutes=30) print dt.time() Output: 00:25:00
Communicating with a running python daemon
I wrote a small Python application that runs as a daemon. It utilizes threading and queues. I'm looking for general approaches to altering this application so that I can communicate with it while it's running. Mostly I'd like to be able to monitor its health. In a nutshell, I'd like to be able to do something like this: python application.py start # launches the daemon Later, I'd like to be able to come along and do something like: python application.py check_queue_size # return info from the daemonized process To be clear, I don't have any problem implementing the Django-inspired syntax. What I don't have any idea how to do is to send signals to the daemonized process (start), or how to write the daemon to handle and respond to such signals. Like I said above, I'm looking for general approaches. The only one I can see right now is telling the daemon constantly log everything that might be needed to a file, but I hope there's a less messy way to go about it. UPDATE: Wow, a lot of great answers. Thanks so much. I think I'll look at both Pyro and the web.py/Werkzeug approaches, since Twisted is a little more than I want to bite off at this point. The next conceptual challenge, I suppose, is how to go about talking to my worker threads without hanging them up. Thanks again.
Yet another approach: use Pyro (Python remoting objects). Pyro basically allows you to publish Python object instances as services that can be called remotely. I have used Pyro for the exact purpose you describe, and I found it to work very well. By default, a Pyro server daemon accepts connections from everywhere. To limit this, either use a connection validator (see documentation), or supply host='127.0.0.1' to the Daemon constructor to only listen for local connections. Example code taken from the Pyro documentation: Server import Pyro.core class JokeGen(Pyro.core.ObjBase): def __init__(self): Pyro.core.ObjBase.__init__(self) def joke(self, name): return "Sorry "+name+", I don't know any jokes." Pyro.core.initServer() daemon=Pyro.core.Daemon() uri=daemon.connect(JokeGen(),"jokegen") print "The daemon runs on port:",daemon.port print "The object's uri is:",uri daemon.requestLoop() Client import Pyro.core # you have to change the URI below to match your own host/port. jokes = Pyro.core.getProxyForURI("PYROLOC://localhost:7766/jokegen") print jokes.joke("Irmen") Another similar project is RPyC. I have not tried RPyC.
Python: Prevent fileinput from adding newline characters
I am using a Python script to find and replace certain strings in text files of a given directory. I am using the fileinput module to ease the find-and-replace operation, i.e., the file is read, text replaced and written back to the same file. The code looks as follows: import fileinput def fixFile(fileName): # Open file for in-place replace for line in fileinput.FileInput(fileName, inplace=1): line = line.replace("findStr", "replaceStr") print line # Put back line into file The problem is that the written files have: One blank line inserted after every line. Ctrl-M character at the end of every line. How do I prevent these extra appendages from getting inserted into the files?
Your newlines are coming from the print function use: import sys sys.stdout.write ('some stuff') and your line breaks will go away
How would you implement a basic event-loop?
If you have worked with gui toolkits, you know that there is a event-loop/main-loop that should be executed after everything is done, and that will keep the application alive and responsive to different events. For example, for Qt, you would do this in main(): int main() { QApplication app(argc, argv); // init code return app.exec(); } Which in this case, app.exec() is the application's main-loop. The obvious way to implement this kind of loop would be: void exec() { while (1) { process_events(); // create a thread for each new event (possibly?) } } But this caps the CPU to 100% and is practicaly useless. Now, how can I implement such an event loop that is responsive without eating the CPU altogether? Answers are appreciated in Python and/or C++. Thanks. Footnote: For the sake of learning, I will implement my own signals/slots, and I would use those to generate custom events (e.g. go_forward_event(steps)). But if you know how I can use system events manually, I would like to know about that too.
I used to wonder a lot about the same! A GUI main loop looks like this, in pseudo-code: void App::exec() { for(;;) { vector<Waitable> waitables; waitables.push_back(m_networkSocket); waitables.push_back(m_xConnection); waitables.push_back(m_globalTimer); Waitable* whatHappened = System::waitOnAll(waitables); switch(whatHappened) { case &m_networkSocket: readAndDispatchNetworkEvent(); break; case &m_xConnection: readAndDispatchGuiEvent(); break; case &m_globalTimer: readAndDispatchTimerEvent(); break; } } } What is a "Waitable"? Well, it's system dependant. On UNIX it's called a "file descriptor" and "waitOnAll" is the ::select system call. The so-called vector<Waitable> is a ::fd_set on UNIX, and "whatHappened" is actually queried via FD_ISSET. The actual waitable-handles are acquired in various ways, for example m_xConnection can be taken from ::XConnectionNumber(). X11 also provides a high-level, portable API for this -- ::XNextEvent() -- but if you were to use that, you wouldn't be able to wait on several event sources simultaneously. How does the blocking work? "waitOnAll" is a syscall that tells the OS to put your process on a "sleep list". This means you are not given any CPU time until an event occurs on one of the waitables. This, then, means your process is idle, consuming 0% CPU. When an event occurs, your process will briefly react to it and then return to idle state. GUI apps spend almost all their time idling. What happens to all the CPU cycles while you're sleeping? Depends. Sometimes another process will have a use for them. If not, your OS will busy-loop the CPU, or put it into temporary low-power mode, etc. Please ask for further details!
How do I suppress scientific notation in Python?
Here's my code: x = 1.0 y = 100000.0 print x/y My quotient displays as 1.00000e-05 Is there any way to suppress scientific notation and make it display as 0.00001? How to convert the scientific notation into float. Thanks in advance. This feels somewhat ridiculous to ask but I haven't figured out a way to do it yet. I'm going to use the result as a string.
'%f' % (x/y) but you need to manage precision yourself. e.g., '%f' % (1/10**8) will display zeros only. details are in the docs Or for Python 3 the equivalent old formatting or the newer style formatting
Python multiprocessing: sharing a large read-only object between processes?
Do child processes spawned via multiprocessing share objects created earlier in the program? I have the following setup: do_some_processing(filename): for line in file(filename): if line.split(',')[0] in big_lookup_object: # something here if __name__ == '__main__': big_lookup_object = marshal.load('file.bin') pool = Pool(processes=4) print pool.map(do_some_processing, glob.glob('*.data')) I'm loading some big object into memory, then creating a pool of workers that need to make use of that big object. The big object is accessed read-only, I don't need to pass modifications of it between processes. My question is: is the big object loaded into shared memory, as it would be if I spawned a process in unix/c, or does each process load its own copy of the big object? Update: to clarify further - big_lookup_object is a shared lookup object. I don't need to split that up and process it separately. I need to keep a single copy of it. The work that I need to split it is reading lots of other large files and looking up the items in those large files against the lookup object. Further update: database is a fine solution, memcached might be a better solution, and file on disk (shelve or dbm) might be even better. In this question I was particularly interested in an in memory solution. For the final solution I'll be using hadoop, but I wanted to see if I can have a local in-memory version as well.
"Do child processes spawned via multiprocessing share objects created earlier in the program?" No. Processes have independent memory space. Solution 1 To make best use of a large structure with lots of workers, do this. Write each worker as a "filter" -- reads intermediate results from stdin, does work, writes intermediate results on stdout. Connect all the workers as a pipeline: process1 <source | process2 | process3 | ... | processn >result Each process reads, does work and writes. This is remarkably efficient since all processes are running concurrently. The writes and reads pass directly through shared buffers between the processes. Solution 2 In some cases, you have a more complex structure -- often a "fan-out" structure. In this case you have a parent with multiple children. Parent opens source data. Parent forks a number of children. Parent reads source, farms parts of the source out to each concurrently running child. When parent reaches the end, close the pipe. Child gets end of file and finishes normally. The child parts are pleasant to write because each child simply reads sys.sydin. The parent has a little bit of fancy footwork in spawning all the children and retaining the pipes properly, but it's not too bad. Fan-in is the opposite structure. A number of independently running processes need to interleave their inputs into a common process. The collector is not as easy to write, since it has to read from many sources. Reading from many named pipes is often done using the select module to see which pipes have pending input. Solution 3 Shared lookup is the definition of a database. Solution 3A -- load a database. Let the workers process the data in the database. Solution 3B -- create a very simple server using werkzeug (or similar) to provide WSGI applications that respond to HTTP GET so the workers can query the server. Solution 4 Shared filesystem object. Unix OS offers shared memory objects. These are just files that are mapped to memory so that swapping I/O is done instead of more convention buffered reads. You can do this from a Python context in several ways Write a startup program that (1) breaks your original gigantic object into smaller objects, and (2) starts workers, each with a smaller object. The smaller objects could be pickled Python objects to save a tiny bit of file reading time. Write a startup program that (1) reads your original gigantic object and writes a page-structured, byte-coded file using seek operations to assure that individual sections are easy to find with simple seeks. This is what a database engine does -- break the data into pages, make each page easy to locate via a seek. Spawn workers with access this this large page-structured file. Each worker can seek to the relevant parts and do their work there.
Overriding python threading.Thread.run()
Given the documentation at http://docs.python.org/library/threading.html which states for Thread.run(): You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively. I have constructed the following code: class DestinationThread(threading.Thread): def run(self, name, config): print 'In thread' thread = DestinationThread(args = (destination_name, destination_config)) thread.start() But when I execute it, I receive the following error: Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner self.run() TypeError: run() takes exactly 3 arguments (1 given) It seems I am missing something obvious, but the various examples I have seen work with this methodology. Ultimately I am trying to just pass the string and dictionary into the thread, if the Constructor is not the right way, but rather to make a new function to set the values prior to starting the thread, I am open to that. Any suggestions on how to best accomplish this?
You really don't need to subclass Thread. The only reason the API supports this is to make it more comfortable for people coming from Java where that's the only way to do it sanely. The pattern that we recommend you use is to pass a method to the Thread constructor, and just call .start(). def myfunc(arg1, arg2): print 'In thread' print 'args are', arg1, arg2 thread = Thread(target=myfunc, args=(destination_name, destination_config)) thread.start()
Access to errno from Python?
I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno. Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it. Using ctypes, libc.errno doesn't work because errno is a macro in GNU libc. Python 2.6 has some affordances but Debian still uses Python 2.5. Inserting a C module into my pure Python program just to read errno disgusts me. Is there some way to access errno? A Linux-only solution is fine, since the library being wrapped is Linux-only. I also don't have to worry about threads, as I'm only running one thread during the time in which this can fail.
Here is a snippet of code that allows to access errno: from ctypes import * libc = CDLL("libc.so.6") get_errno_loc = libc.__errno_location get_errno_loc.restype = POINTER(c_int) def errcheck(ret, func, args): if ret == -1: e = get_errno_loc()[0] raise OSError(e) return ret copen = libc.open copen.errcheck = errcheck print copen("nosuchfile", 0) The important thing is that you check errno as soon as possible after your function call, otherwise it may already be overwritten.
Security of Python's eval() on untrusted strings?
If I am evaluating a Python string using eval(), and have a class like: class Foo(object): a = 3 def bar(self, x): return x + a What are the security risks if I do not trust the string? In particular: Is eval(string, {"f": Foo()}, {}) unsafe? That is, can you reach os or sys or something unsafe from a Foo instance? Is eval(string, {}, {}) unsafe? That is, can I reach os or sys entirely from builtins like len and list? Is there a way to make builtins not present at all in the eval context? There are some unsafe strings like "[0] * 100000000" I don't care about, because at worst they slow/stop the program. I am primarily concerned about protecting user data external to the program. Obviously, eval(string) without custom dictionaries is unsafe in most cases.
eval() will allow malicious data to compromise your entire system, kill your cat, eat your dog and make love to your wife. There was recently a thread about how to do this kind of thing safely on the python-dev list, and the conclusions were: It's really hard to do this properly. It requires patches to the python interpreter to block many classes of attacks. Don't do it unless you really want to. Start here to read about the challenge: http://tav.espians.com/a-challenge-to-break-python-security.html What situation do you want to use eval() in? Are you wanting a user to be able to execute arbitrary expressions? Or are you wanting to transfer data in some way? Perhaps it's possible to lock down the input in some way.
How do I know if a generator is empty from the start?
Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?
Suggestion: def peek(iterable): try: first = next(iterable) except StopIteration: return None return first, itertools.chain([first], iterable) Usage: res = peek(mysequence) if res is None: # sequence is empty. Do stuff. else: first, mysequence = res # Do something with first, maybe? # Then iterate over the sequence: for element in mysequence: # etc.
Is there a way to substring a string in Python?
Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string? Maybe like myString[2:end]? If leaving the second part means 'till the end', if you leave the first part, does it start from the start?
>>> x = "Hello World!" >>> x[2:] 'llo World!' >>> x[:2] 'He' >>> x[:-2] 'Hello Worl' >>> x[-2:] 'd!' >>> x[2:-2] 'llo Worl' Python calls this concept "slicing" and it works on more than just strings. Take a look here for a comprehensive introduction.
What's the difference between dict() and {}?
So let's say I wanna make a dictionary. We'll call it d. But there are multiple ways to initialize a dictionary in Python! For example, I could do this: d = {'hash': 'bang', 'slash': 'dot'} Or I could do this: d = dict(hash='bang', slash='dot') Or this, curiously: d = dict({'hash': 'bang', 'slash': 'dot'}) Or this: d = dict([['hash', 'bang'], ['slash', 'dot']]) And a whole other multitude of ways with the dict() function. So obviously one of the things dict() provides is flexibility in syntax and initialization. But that's not what I'm asking about. Say I were to make d just an empty dictionary. What goes on behind the scenes of the Python interpreter when I do d = {} versus d = dict()? Is it simply two ways to do the same thing? Does using {} have the additional call of dict()? Does one have (even negligible) more overhead than the other? While the question is really completely unimportant, it's a curiosity I would love to have answered.
>>> def f(): ... return {'a' : 1, 'b' : 2} ... >>> def g(): ... return dict(a=1, b=2) ... >>> g() {'a': 1, 'b': 2} >>> f() {'a': 1, 'b': 2} >>> import dis >>> dis.dis(f) 2 0 BUILD_MAP 0 3 DUP_TOP 4 LOAD_CONST 1 ('a') 7 LOAD_CONST 2 (1) 10 ROT_THREE 11 STORE_SUBSCR 12 DUP_TOP 13 LOAD_CONST 3 ('b') 16 LOAD_CONST 4 (2) 19 ROT_THREE 20 STORE_SUBSCR 21 RETURN_VALUE >>> dis.dis(g) 2 0 LOAD_GLOBAL 0 (dict) 3 LOAD_CONST 1 ('a') 6 LOAD_CONST 2 (1) 9 LOAD_CONST 3 ('b') 12 LOAD_CONST 4 (2) 15 CALL_FUNCTION 512 18 RETURN_VALUE dict() is apparently some C built-in. A really smart or dedicated person (not me) could look at the interpreter source and tell you more. I just wanted to show off dis.dis. :)
Is it possible only to declare a variable without assigning any value in Python?
Is it possible to declare a variable in Python, like so?: var so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why? EDIT: I want to do this for cases like this: value for index in sequence: if value == None and conditionMet: value = index break Duplicate Uninitialised value in python (by same author) Are there any declaration keywords in Python? (by the same author) Related Python: variable scope and function calls Other languages have "variables"
Why not just do this: var = None Python is dynamic, so you don't need to declare things; they exist automatically in the first scope where they're assigned. So, all you need is a regular old assignment statement as above. This is nice, because you'll never end up with an uninitialized variable. But be careful -- this doesn't mean that you won't end up with incorrectly initialized variables. If you init something to None, make sure that's what you really want, and assign something more meaningful if you can.
Redirect command line results to a tkinter GUI
I have created a program that prints results on command line. (It is server and it prints log on command line.) Now, I want to see the same result to GUI . How can I redirect command line results to GUI? Please, suggest a trick to easily transform console application to simple GUI. Note that it should work on Linux and Windows.
You could create a script wrapper that runs your command line program as a sub process, then add the output to something like a text widget. from tkinter import * import subprocess as sub p = sub.Popen('./script',stdout=sub.PIPE,stderr=sub.PIPE) output, errors = p.communicate() root = Tk() text = Text(root) text.pack() text.insert(END, output) root.mainloop() where script is your program. You can obviously print the errors in a different colour, or something like that.
What errors/exceptions do I need to handle with urllib2.Request / urlopen?
I have the following code to do a postback to a remote URL: request = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' }) try: response = urllib2.urlopen(request) except urllib2.HTTPError, e: checksLogger.error('HTTPError = ' + str(e.code)) except urllib2.URLError, e: checksLogger.error('URLError = ' + str(e.reason)) except httplib.HTTPException, e: checksLogger.error('HTTPException') The postBackData is created using a dictionary encoded using urllib.urlencode. checksLogger is a logger using logging. I have had a problem where this code runs when the remote server is down and the code exits (this is on customer servers so I don't know what the exit stack dump / error is at this time). I'm assuming this is because there is an exception and/or error that is not being handled. So are there any other exceptions that might be triggered that I'm not handling above?
Add generic exception handler: request = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' }) try: response = urllib2.urlopen(request) except urllib2.HTTPError, e: checksLogger.error('HTTPError = ' + str(e.code)) except urllib2.URLError, e: checksLogger.error('URLError = ' + str(e.reason)) except httplib.HTTPException, e: checksLogger.error('HTTPException') except Exception: import traceback checksLogger.error('generic exception: ' + traceback.format_exc())
Decorator classes in Python
I want to construct classes for use as decorators with the following principles intact: It should be possible to stack multiple such class decorators on top off 1 function. The resulting function name pointer should be indistinguishable from the same function without a decorator, save maybe for just which type/class it is. Ordering off the decorators should not be relevant unless actually mandated by the decorators. Ie. independent decorators could be applied in any order. This is for a Django project, and the specific case I am working on now the method needs 2 decorators, and to appear as a normal python function: @AccessCheck @AutoTemplate def view(request, item_id) {} @AutoTemplate changes the function so that instead of returning a HttpResponse, it just returns a dictionary for use in the context. A RequestContext is used, and the template name is inferred from the method name and module. @AccessCheck adds additional checks on the user based on the item_id. I am guessing it's just to get the constructor right and copy the appropriate attributes, but which attributes are these? The following decorator won't work as I describe: class NullDecl (object): def __init__ (self, func): self.func = func def __call__ (self, * args): return self.func (*args) As demonstrated by the following code: @NullDecl @NullDecl def decorated(): pass def pure(): pass # results in set(['func_closure', 'func_dict', '__get__', 'func_name', # 'func_defaults', '__name__', 'func_code', 'func_doc', 'func_globals']) print set(dir(pure)) - set(dir(decorated)); Additionally, try and add "print func.name" in the NullDecl constructor, and it will work for the first decorator, but not the second - as name will be missing. Refined eduffy's answer a bit, and it seems to work pretty well: class NullDecl (object): def __init__ (self, func): self.func = func for n in set(dir(func)) - set(dir(self)): setattr(self, n, getattr(func, n)) def __call__ (self, * args): return self.func (*args) def __repr__(self): return self.func
A do-nothing decorator class would look like this: class NullDecl (object): def __init__ (self, func): self.func = func for name in set(dir(func)) - set(dir(self)): setattr(self, name, getattr(func, name)) def __call__ (self, *args): return self.func (*args) And then you can apply it normally: @NullDecl def myFunc (x,y,z): return (x+y)/z
What's a good rate limiting algorithm?
I could use some pseudo-code, or better, Python. I am trying to implement a rate-limiting queue for a Python IRC bot, and it partially works, but if someone triggers less messages than the limit (e.g., rate limit is 5 messages per 8 seconds, and the person triggers only 4), and the next trigger is over the 8 seconds (e.g., 16 seconds later), the bot sends the message, but the queue becomes full and the bot waits 8 seconds, even though it's not needed since the 8 second period has lapsed.
Here the simplest algorithm, if you want just to drop messages when they arrive too quickly (instead of queuing them, which makes sense because the queue might get arbitrarily large): rate = 5.0; // unit: messages per = 8.0; // unit: seconds allowance = rate; // unit: messages last_check = now(); // floating-point, e.g. usec accuracy. Unit: seconds when (message_received): current = now(); time_passed = current - last_check; last_check = current; allowance += time_passed * (rate / per); if (allowance > rate): allowance = rate; // throttle if (allowance < 1.0): discard_message(); else: forward_message(); allowance -= 1.0; There are no datastructures, timers etc. in this solution and it works cleanly :) To see this, 'allowance' grows at speed 5/8 units per seconds at most, i.e. at most five units per eight seconds. Every message that is forwarded deducts one unit, so you can't send more than five messages per every eight seconds. Note that rate should be an integer, i.e. without non-zero decimal part, or the algorithm won't work correctly (actual rate will not be rate/per). E.g. rate=0.5; per=1.0; does not work because allowance will never grow to 1.0. But rate=1.0; per=2.0; works fine.
Full command line as it was typed
I want to get the full command line as it was typed. This: " ".join(sys.argv[:]) doesn't work here (deletes double quotes). Also I prefer not to rejoin something that was parsed and splited. Any ideas? Thank you in advance.
You're too late. By the time that the typed command gets to Python your shell has already worked its magic. For example, quotes get consumed (as you've noticed), variables get interpolated, etc.
How to tell if a connection is dead in python
I want my python application to be able to tell when the socket on the other side has been dropped. Is there a method for this?
It depends on what you mean by "dropped". For TCP sockets, if the other end closes the connection either through close() or the process terminating, you'll find out by reading an end of file, or getting a read error, usually the errno being set to whatever 'connection reset by peer' is by your operating system. For python, you'll read a zero length string, or a socket.error will be thrown when you try to read or write from the socket.
How do I develop against OAuth locally?
I'm building a Python application that needs to communicate with an OAuth service provider. The SP requires me to specify a callback URL. Specifying localhost obviously won't work. I'm unable to set up a public facing server. Any ideas besides paying for server/hosting? Is this even possible?
Two things: The OAuth Service Provider in question is violating the OAuth spec if it's giving you an error if you don't specify a callback URL. callback_url is spec'd to be an OPTIONAL parameter. But, pedantry aside, you probably want to get a callback when the user's done just so you know you can redeem the Request Token for an Access Token. Yahoo's FireEagle developer docs have lots of great information on how to do this. Even in the second case, the callback URL doesn't actually have to be visible from the Internet at all. The OAuth Service Provider will redirect the browser that the user uses to provide his username/password to the callback URL. The two common ways to do this are: Create a dumb web service from within your application that listens on some port (say, http://localhost:1234/) for the completion callback, or Register a protocol handler (you'll have to check with the documentation for your OS specifically on how to do such a thing, but it enables things like <a href="skype:555-1212"> to work). (An example of the flow that I believe you're describing lives here.)
Asynchronous File Upload to Amazon S3 with Django
I am using this file storage engine to store files to Amazon S3 when they are uploaded: http://code.welldev.org/django-storages/wiki/Home It takes quite a long time to upload because the file must first be uploaded from client to web server, and then web server to Amazon S3 before a response is returned to the client. I would like to make the process of sending the file to S3 asynchronous, so the response can be returned to the user much faster. What is the best way to do this with the file storage engine? Thanks for your advice!
I've taken another approach to this problem. My models have 2 file fields, one uses the standard file storage backend and the other one uses the s3 file storage backend. When the user uploads a file it get's stored localy. I have a management command in my application that uploads all the localy stored files to s3 and updates the models. So when a request comes for the file I check to see if the model object uses the s3 storage field, if so I send a redirect to the correct url on s3, if not I send a redirect so that nginx can serve the file from disk. This management command can ofcourse be triggered by any event a cronjob or whatever.
Memory efficiency: One large dictionary or a dictionary of smaller dictionaries?
I'm writing an application in Python (2.6) that requires me to use a dictionary as a data store. I am curious as to whether or not it is more memory efficient to have one large dictionary, or to break that down into many (much) smaller dictionaries, then have an "index" dictionary that contains a reference to all the smaller dictionaries. I know there is a lot of overhead in general with lists and dictionaries. I read somewhere that python internally allocates enough space that the dictionary/list # of items to the power of 2. I'm new enough to python that I'm not sure if there are other unexpected internal complexities/suprises like that, that is not apparent to the average user that I should take into consideration. One of the difficulties is knowing how the power of 2 system counts "items"? Is each key:pair counted as 1 item? That's seems important to know because if you have a 100 item monolithic dictionary then space 100^2 items would be allocated. If you have 100 single item dictionaries (1 key:pair) then each dictionary would only be allocation 1^2 (aka no extra allocation)? Any clearly laid out information would be very helpful!
Three suggestions: Use one dictionary. It's easier, it's more straightforward, and someone else has already optimized this problem for you. Until you've actually measured your code and traced a performance problem to this part of it, you have no reason not to do the simple, straightforward thing. Optimize later. If you are really worried about performance, then abstract the problem make a class to wrap whatever lookup mechanism you end up using and write your code to use this class. You can change the implementation later if you find you need some other data structure for greater performance. Read up on hash tables. Dictionaries are hash tables, and if you are worried about their time or space overhead, you should read up on how they're implemented. This is basic computer science. The short of it is that hash tables are: average case O(1) lookup time O(n) space (Expect about 2n, depending on various parameters) I do not know where you read that they were O(n^2) space, but if they were, then they would not be in widespread, practical use as they are in most languages today. There are two advantages to these nice properties of hash tables: O(1) lookup time implies that you will not pay a cost in lookup time for having a larger dictionary, as lookup time doesn't depend on size. O(n) space implies that you don't gain much of anything from breaking your dictionary up into smaller pieces. Space scales linearly with number of elements, so lots of small dictionaries will not take up significantly less space than one large one or vice versa. This would not be true if they were O(n^2) space, but lucky for you, they're not. Here are some more resources that might help: The Wikipedia article on Hash Tables gives a great listing of the various lookup and allocation schemes used in hashtables. The GNU Scheme documentation has a nice discussion of how much space you can expect hashtables to take up, including a formal discussion of why "the amount of space used by the hash table is proportional to the number of associations in the table". This might interest you. Here are some things you might consider if you find you actually need to optimize your dictionary implementation: Here is the C source code for Python's dictionaries, in case you want ALL the details. There's copious documentation in here: dictobject.h dicobject.c Here is a python implementation of that, in case you don't like reading C. (Thanks to Ben Peterson) The Java Hashtable class docs talk a bit about how load factors work, and how they affect the space your hash takes up. Note there's a tradeoff between your load factor and how frequently you need to rehash. Rehashes can be costly.
Using python map and other functional tools
This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code: foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo, bar): print foo, bar map(maptest, foos, bars) produces: 1.0 1 2.0 2 3.0 3 4.0 None 5.0 None Q. Is there a way to use map or any other functional tools in python to produce the following without loops etc. 1.0 [1,2,3] 2.0 [1,2,3] 3.0 [1,2,3] 4.0 [1,2,3] 5.0 [1,2,3] Just as a side note how would the implementation change if there is a dependency between foo and bar. e.g. foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3,4,5] and print: 1.0 [2,3,4,5] 2.0 [1,3,4,5] 3.0 [1,2,4,5] ... P.S: I know how to do it naively using if, loops and/or generators, but I'd like to learn how to achieve the same using functional tools. Is it just a case of adding an if statement to maptest or apply another filter map to bars internally within maptest?
Are you familiar with other functional languages? i.e. are you trying to learn how python does functional programming, or are you trying to learn about functional programming and using python as the vehicle? Also, do you understand list comprehensions? map(f, sequence) is directly equivalent (*) to: [f(x) for x in sequence] In fact, I think map() was once slated for removal from python 3.0 as being redundant (that didn't happen). map(f, sequence1, sequence2) is mostly equivalent to: [f(x1, x2) for x1, x2 in zip(sequence1, sequence2)] (there is a difference in how it handles the case where the sequences are of different length. As you saw, map() fills in None when one of the sequences runs out, whereas zip() stops when the shortest sequence stops) So, to address your specific question, you're trying to produce the result: foos[0], bars foos[1], bars foos[2], bars # etc. You could do this by writing a function that takes a single argument and prints it, followed by bars: def maptest(x): print x, bars map(maptest, foos) Alternatively, you could create a list that looks like this: [bars, bars, bars, ] # etc. and use your original maptest: def maptest(x, y): print x, y One way to do this would be to explicitely build the list beforehand: barses = [bars] * len(foos) map(maptest, foos, barses) Alternatively, you could pull in the itertools module. itertools contains many clever functions that help you do functional-style lazy-evaluation programming in python. In this case, we want itertools.repeat, which will output its argument indefinitely as you iterate over it. This last fact means that if you do: map(maptest, foos, itertools.repeat(bars)) you will get endless output, since map() keeps going as long as one of the arguments is still producing output. However, itertools.imap is just like map(), but stops as soon as the shortest iterable stops. itertools.imap(maptest, foos, itertools.repeat(bars)) Hope this helps :-) (*) It's a little different in python 3.0. There, map() essentially returns a generator expression.
File dialogs of Tkinter in Python 3?
I want to select a file from a dialog box. Here is code that does all I need, but when I run it: ImportError: No module named 'tkMessageBox' How can I make this example work with Python 3?
The package Tkinter has been renamed to tkinter in Python 3, as well as other modules related to it. Here are the name changes: Tkinter → tkinter tkMessageBox → tkinter.messagebox tkColorChooser → tkinter.colorchooser tkFileDialog → tkinter.filedialog tkCommonDialog → tkinter.commondialog tkSimpleDialog → tkinter.simpledialog tkFont → tkinter.font Tkdnd → tkinter.dnd ScrolledText → tkinter.scrolledtext Tix → tkinter.tix ttk → tkinter.ttk I advise you to learn how to dynamically browse the modules with the dir command. If you are under windows, configure Python to use readline module to get auto-completion and make it much easier to list available classes in a module.
Python's use of __new__ and __init__?
I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern. However, I'm a bit confused as to why __init__ is always called after __new__. I wasn't expecting this. Can anyone tell me why this is happening and how I implement this functionality otherwise? (apart from putting the implementation into the __new__ which feels quite hacky). Here's an example: class A(object): _dict = dict() def __new__(cls): if 'key' in A._dict: print "EXISTS" return A._dict['key'] else: print "NEW" return super(A, cls).__new__(cls) def __init__(self): print "INIT" A._dict['key'] = self print "" a1 = A() a2 = A() a3 = A() Outputs: NEW INIT EXISTS INIT EXISTS INIT Why?
Use __new__ when you need to control the creation of a new instance. Use __init__ when you need to control initialization of a new instance. __new__ is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class. In contrast, __init__ doesn't return anything; it's only responsible for initializing the instance after it's been created. In general, you shouldn't need to override __new__ unless you're subclassing an immutable type like str, int, unicode or tuple. From: http://mail.python.org/pipermail/tutor/2008-April/061426.html You should consider that what you are trying to do is usually done with a Factory and that's the best way to do it. Using __new__ is not a good clean solution so please consider the usage of a factory. Here you have a good factory example.
How do I iterate over a Python dictionary, ordered by values?
I've got a dictionary like: { 'a': 6, 'b': 1, 'c': 2 } I'd like to iterate over it by value, not by key. In other words: (b, 1) (c, 2) (a, 6) What's the most straightforward way?
sorted(dictionary.items(), key=lambda x: x[1]) for these of you that hate lambda :-) import operator sorted(dictionary.items(), key=operator.itemgetter(1)) However operator version requires CPython 2.5+
How can I convert a Python dictionary to a list of tuples?
If I have a dictionary like: { 'a': 1, 'b': 2, 'c': 3 } How can I convert it to this? [ ('a', 1), ('b', 2), ('c', 3) ] And how can I convert it to this? [ (1, 'a'), (2, 'b'), (3, 'c') ]
>>> d = { 'a': 1, 'b': 2, 'c': 3 } >>> d.items() [('a', 1), ('c', 3), ('b', 2)] >>> [(v, k) for k, v in d.iteritems()] [(1, 'a'), (3, 'c'), (2, 'b')] It's not in the order you want, but dicts don't have any specific order anyway. Sort it or organize it as necessary. See: items(), iteritems() In Python 3.x, you would not use iteritems (which no longer exists), but instead use items, which now returns a "view" into the dictionary items. See the What's New document for Python 3.0, and the new documentation on views.
Examples for string find in Python
I am trying to find some examples but no luck. Does anyone know of some examples on the net? I would like to know what it returns when it can't find, and how to specify from start to end, which I guess is going to be 0, -1.
I'm not sure what you're looking for, do you mean find()? >>> x = "Hello World" >>> x.find('World') 6 >>> x.find('Aloha'); -1
OCR for sheet music
Im considering doing a small project as a part of my masters for doing ocr just for sheetmusic instead of text. I think PIL and Python would be fine for simple proof of concept O"notes"R. My question is: Has anyone got any "dont do it with PIL use xyz instead" or something in that alley? EDIT: My delicius links regarding the subject if anyone is interested: http://delicious.com/seet/DIKU-09b4%2Bb1 ========================================================================= EDIT2: Actually, now I know a lot more about OCR for sheet music or OMR as it is called. Within academia the area has been researched since late 60/early 70 and building an OMR system is not a simple task. To get a summary of the problems and the research until early 2000 you could read "The challenge of Optical Music Recognition" which is quite successful in drawing up the lines of the field. Regarding existing software I know of at least these: Sharpeye Photoscore Smartscore X Capella Scan PdfToMusic And my unscientific tests gave me the idea that photoscore was the most robust one. For Opensource software Audiveris is the only complete thing I found and is written in Java. Regarding my original question I am using Gamera. Gamera is an opensource tool for document image analysis which provides tools to do all the basic stuff needed for analysing images for recognition. Gamera has a python interface and the possibility to write c++ "toolkits". For example is it possible to download and use a staffline removal toolkit for gamera.
My project ended with a report and some python software. Find it here: Report Code The gist of it is: It is hard to do good OMR and takes a lot of effort. I didn't have the time to do complete OMR (and it looks like it's not that needed after all). I implemented a tool that can do preprocessing of sheet music before handing it to a OMR tool like Photoscore or the like. The preprocessing includes removal of lyrics and dynamics as this information is not needed for statistical analysis of the music in large music corpora
Tab-completion in Python interpreter in OS X Terminal
Several months ago, I wrote a blog post detailing how to achieve tab-completion in the standard Python interactive interpreter--a feature I once thought only available in IPython. I've found it tremendously handy given that I sometimes have to switch to the standard interpreter due to IPython unicode issues. Recently I've done some work in OS X. To my discontent, the script doesn't seem to work for OS X's Terminal application. I'm hoping some of you with experience in OS X might be able to help me trouble-shoot it so it can work in Terminal, as well. I am reproducing the code below import atexit import os.path try: import readline except ImportError: pass else: import rlcompleter class IrlCompleter(rlcompleter.Completer): """ This class enables a "tab" insertion if there's no text for completion. The default "tab" is four spaces. You can initialize with '\t' as the tab if you wish to use a genuine tab. """ def __init__(self, tab=' '): self.tab = tab rlcompleter.Completer.__init__(self) def complete(self, text, state): if text == '': readline.insert_text(self.tab) return None else: return rlcompleter.Completer.complete(self,text,state) #you could change this line to bind another key instead tab. readline.parse_and_bind('tab: complete') readline.set_completer(IrlCompleter('\t').complete) # Restore our command-line history, and save it when Python exits. history_path = os.path.expanduser('~/.pyhistory') if os.path.isfile(history_path): readline.read_history_file(history_path) atexit.register(lambda x=history_path: readline.write_history_file(x)) Note that I have slightly edited it from the version on my blog post so that the IrlCompleter is initialized with a true tab, which seems to be what is output by the Tab key in Terminal.
This should work under Leopard's python: import rlcompleter import readline readline.parse_and_bind ("bind ^I rl_complete") Whereas this one does not: import readline, rlcompleter readline.parse_and_bind("tab: complete") Save it in ~/.pythonrc.py and execute in .bash_profile export PYTHONSTARTUP=$HOME/.pythonrc.py
Full examples of using pySerial package
Can someone please show me a full python sample code that uses pyserial, i have the package and am wondering how to send the AT commands and read them back!
Blog post Serial RS232 connections in Python import time import serial # configure the serial connections (the parameters differs on the device you are connecting to) ser = serial.Serial( port='/dev/ttyUSB1', baudrate=9600, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_TWO, bytesize=serial.SEVENBITS ) ser.isOpen() print 'Enter your commands below.\r\nInsert "exit" to leave the application.' input=1 while 1 : # get keyboard input input = raw_input(">> ") # Python 3 users # input = input(">> ") if input == 'exit': ser.close() exit() else: # send the character to the device # (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device) ser.write(input + '\r\n') out = '' # let's wait one second before reading output (let's give device time to answer) time.sleep(1) while ser.inWaiting() > 0: out += ser.read(1) if out != '': print ">>" + out
Is there a cross-platform python low-level API to capture or generate keyboard events?
I am trying to write a cross-platform python program that would run in the background, monitor all keyboard events and when it sees some specific shortcuts, it generates one or more keyboard events of its own. For example, this could be handy to have Ctrl-@ mapped to "my.email@address", so that every time some program asks me for my email address I just need to type Ctrl-@. I know such programs already exist, and I am reinventing the wheel... but my goal is just to learn more about low-level keyboard APIs. Moreover, the answer to this question might be useful to other programmers, for example if they want to startup an SSH connection which requires a password, without using pexpect. Thanks for your help. Note: there is a similar question but it is limited to the Windows platform, and does not require python. I am looking for a cross-platform python api. There are also other questions related to keyboard events, but apparently they are not interested in system-wide keyboard events, just application-specific keyboard shortcuts. Edit: I should probably add a disclaimer here: I do not want to write a keylogger. If I needed a keylogger, I could download one off the web a anyway. ;-)
There is no such API. My solution was to write a helper module which would use a different helper depending on the value of os.name. On Windows, use the Win32 extensions. On Linux, things are a bit more complex since real OSes protect their users against keyloggers[*]. So here, you will need a root process which watches one of[] the handles in /dev/input/. Your best bet is probably looking for an entry below /dev/input/by-path/ which contains the strings "kbd" or "keyboard". That should work in most cases. [*]: Jeez, not even my virus/trojan scanner will complain when I start a Python program which hooks into the keyboard events...
condition coverage in python
Is there any tool/library that calculate percent of "condition/decision coverage" of python code. I found only coverage.py but it calculates only percent of "statement coverage".
Coverage.py now includes branch coverage. For the curious: the code is not modified before running. The trace function tracks which lines follow which in the execution, and compare that information with static analysis of the compiled byte code to find path possibilities not executed.
Python SVN bindings for Windows
Where can I find precompiled Python SWIG SVN bindings for Windows?
The (old) Windows binaries page at tigris.org contains an installer for python bindings for SVN. View the source for the SWIG bindings at /trunk/subversion/bindings/swig/python. (May 2010 - The Subversion project is transitioning into its new role as an Apache Software Foundation, many resources are changing address. Updated source link. ) (November 2010 - more Windows binaries) The win32svn project, Subversion for Windows, by alagazam, is a win32 build of subversion. As of November 2010, it contains a 1.6.13 build dated 2010-10-05, including python 2.6 bindings. (January 2011 - keeping up: 2010-12-17, 1.6.15, Python 2.6.6.) (May 2011 - 2011-03-14, 1.6.16, Python 2.6.6) (June 2011 - 2011-06-03, 1.6.17, Python 2.6.6) (October 2011 - 2011-10-15, 1.7.0), Python 2.6.6 and 2.7.2) (December 2011 - 2011-12-12, [1.7.2], Python 2.7.2 and 2.6.6) (February 2012 - 2012-02-18, [1.7.3], Python 2.5.4 , 2.6.6 and 2.7.2 ) (March 2012 - 2012-03-08 1.7.4, Python 2.5.4 , 2.6.6 and 2.7.2) (May 2012 - 2012-05-17 1.7.5, Python 2.5.4 , 2.6.6 and 2.7.3) (August 2012 - 2012-08-15 1.7.6, Python 2.5.4, 2.6.6 and 2.7.3. No Python 3 version) (December 2012 - 2012-12-20 1.7.8, Python 2.5.4, 2.6.6 and 2.7.3.) (November 2013 - 2013-11-25 1.8.5, Python 2.6.6 and 2.7.6) (May 2016 - 2016-05-04 1.8.16, Python 2.6.6 and 2.7.9)
distutils: How to pass a user defined parameter to setup.py?
Please prompt me how to pass a user-defined parameter both from the command line and setup.cfg configuration file to distutils' setup.py script. I want to write a setup.py script, which accepts my package specific parameters. For example: python setup.py install -foo myfoo Thank you, Mher
As Setuptools/Distuils are horribly documented, I had problems finding the answer to this myself. But eventually I stumbled across this example. Also, this similar question was helpful. Basically, a custom command with an option would look like: from distutils.core import setup, Command class InstallCommand(Command): description = "Installs the foo." user_options = [ ('foo=', None, 'Specify the foo to bar.'), ] def initialize_options(self): self.foo = None def finalize_options(self): assert self.foo in (None, 'myFoo', 'myFoo2'), 'Invalid foo!' def run(self): install_all_the_things() setup( ..., cmdclass={ 'install': InstallCommand, } )
Python and MySQL: is there an alternative to MySQLdb?
Is there a module written purely in Python that will allow a script to communicate with a MySQL database? I've already tried MySQLdb without success. It requires too much: GCC, zlib, and openssl. I do not have access to these tools; even if I did, I don't want to waste time getting them to work together. I'm looking for tools that will make my work easier. Can someone point me in the direction of a MySQL Python module written in Python? If not, tips on writing my own code for communicating with MySQL would be appreciated. Thanks, Tony Thanks everyone for your answers. Since I'm working with a small database (a few hundred records, mainly names and addresses) I've decided to use SQLite. I just discovered it. It seems to be perfectly suited for my purposes; it was simple to install (took about two minutes) and works well with Python. I'm stuck with Python 2.4 so I can't use the sqlite3 module, but I'm able to communicate with the database by using Python's 'subprocess.Popen' function and command-line parameters.
You've looked at these? http://wiki.python.org/moin/MySQL
weakref list in python
I'm in need of a list of weak references that deletes items when they die. Currently the only way I have of doing this is to keep flushing the list (removing dead references manually). I'm aware there's a WeakKeyDictionary and a WeakValueDictionary, but I'm really after a WeakList, is there a way of doing this? Here's an example: import weakref class A(object): def __init__(self): pass class B(object): def __init__(self): self._references = [] def addReference(self, obj): self._references.append(weakref.ref(obj)) def flush(self): toRemove = [] for ref in self._references: if ref() is None: toRemove.append(ref) for item in toRemove: self._references.remove(item) b = B() a1 = A() b.addReference(a1) a2 = A() b.addReference(a2) del a1 b.flush() del a2 b.flush()
You could implement it yourself, similarly to how you have done, but with a list subclass that calls flush() before attempting to access an item. Obviously you don't want to do this on every access, but you can optimize this by setting a callback on the weak reference to mark the list dirty when something dies. Then you only need to flush the list when something has died since the last access. Here's a list class implemented using this method. (Note that it's not tested much, and some methods aren't implemented very efficiently (eg. those which just convert to a real list and call the method on that), but it should be a reasonable starting point: import weakref class WeakList(list): def __init__(self, seq=()): list.__init__(self) self._refs = [] self._dirty=False for x in seq: self.append(x) def _mark_dirty(self, wref): self._dirty = True def flush(self): self._refs = [x for x in self._refs if x() is not None] self._dirty=False def __getitem__(self, idx): if self._dirty: self.flush() return self._refs[idx]() def __iter__(self): for ref in self._refs: obj = ref() if obj is not None: yield obj def __repr__(self): return "WeakList(%r)" % list(self) def __len__(self): if self._dirty: self.flush() return len(self._refs) def __setitem__(self, idx, obj): if isinstance(idx, slice): self._refs[idx] = [weakref.ref(obj, self._mark_dirty) for x in obj] else: self._refs[idx] = weakref.ref(obj, self._mark_dirty) def __delitem__(self, idx): del self._refs[idx] def append(self, obj): self._refs.append(weakref.ref(obj, self._mark_dirty)) def count(self, obj): return list(self).count(obj) def extend(self, items): for x in items: self.append(x) def index(self, obj): return list(self).index(obj) def insert(self, idx, obj): self._refs.insert(idx, weakref.ref(obj, self._mark_dirty)) def pop(self, idx): if self._dirty: self.flush() obj=self._refs[idx]() del self._refs[idx] return obj def remove(self, obj): if self._dirty: self.flush() # Ensure all valid. for i, x in enumerate(self): if x == obj: del self[i] def reverse(self): self._refs.reverse() def sort(self, cmp=None, key=None, reverse=False): if self._dirty: self.flush() if key is not None: key = lambda x,key=key: key(x()) else: key = apply self._refs.sort(cmp=cmp, key=key, reverse=reverse) def __add__(self, other): l = WeakList(self) l.extend(other) return l def __iadd__(self, other): self.extend(other) return self def __contains__(self, obj): return obj in list(self) def __mul__(self, n): return WeakList(list(self)*n) def __imul__(self, n): self._refs *= n return self [Edit] Add a more complete list implementation.
How to get the filename without the extension from a path in Python?
How to get the filename without the extension from a path in Python? I found out a method called os.path.basename to get the filename with extension. But even when I import os, I am not able to call it path.basename. Is it possible to call it as directly as basename?
Getting the name of the file without the extension : import os print(os.path.splitext("path_to_file")[0]) As for your import problem, you solve it this way : from os.path import basename # now you can call it directly with basename print(basename("/a/b/c.txt"))
Best way to profile/optimize a website on google's appengine
I'm currently trying to optimize my website, which run on the google's appengine. It's not an easy task, because I'm not using any powerful tool. Does anyone have experience in optimizing python code for this purpose? Have you find a good python profiler?
I have found Gprof2Dot extremely useful. The output of the profiling modules I've tried as pretty unintuitive to interpret. Gprof2Dot turns the cProfile output into a pretty looking graph, with the slowest chain(?) highlighted, and a bit of information on each function (function name, percentage of time spend on this function, and number of calls). An example graph (1429x1896px) I've not done much with the App Engine, but when profiling non-webapp scripts, I tend to profile the script that runs all the unittests, which may not be very accurate to real-world situations One (better?) method would be to have a script that does a fake WSGI request, then profile that. WSGI is really simple protocol, it's basically a function that takes two arguments, one with request info and the second with a callback function (which is used for setting headers, among other things). Perhaps something like the following (which is possible-working pseudo code)... class IndexHandler(webapp.RequestHandler): """Your site""" def get(self): self.response.out.write("hi") if __name__ == '__main__': application = webapp.WSGIApplication([ ('.*', IndexHandler), ], debug=True) # Start fake-request/profiling bit urls = [ "/", "/blog/view/hello", "/admin/post/edit/hello", "/makeanerror404", "/makeanerror500" ] def fake_wsgi_callback(response, headers): """Prints heads to stdout""" print("\n".join(["%s: %s" % (n, v) for n, v in headers])) print("\n") for request_url in urls: html = application({ 'REQUEST_METHOD': 'GET', 'PATH_INFO': request_url}, fake_wsgi_callback ) print html Actually, the App Engine documentation explains a better way of profiling your application: From http://code.google.com/appengine/kb/commontasks.html#profiling: To profile your application's performance, first rename your application's main() function to real_main(). Then, add a new main function to your application, named profile_main() such as the one below: def profile_main(): # This is the main function for profiling # We've renamed our original main() above to real_main() import cProfile, pstats prof = cProfile.Profile() prof = prof.runctx("real_main()", globals(), locals()) print "<pre>" stats = pstats.Stats(prof) stats.sort_stats("time") # Or cumulative stats.print_stats(80) # 80 = how many to print # The rest is optional. # stats.print_callees() # stats.print_callers() print "</pre>" [...] To enable the profiling with your application, set main = profile_main. To run your application as normal, simply set main = real_main.
What are the viable database abstraction layers for Python
I'm starting to get involved in an open source project Gramps which is exploring switching their backend from BSDDB to a relational database. Either SQLite or MySQL we haven't fully decided and may even try to do both in some limited capacity. I'm a professional developer but I'm new to python so I'm not that familiar with the current selection of tools/libraries. I've been tasked with researching DB Abstraction Layers. There is currently a wiki discussion going on to compare them. An object relational mapper might be nice but isn't absolutely necessary. though I know that is usually synonymous with a DB Abstraction Layer. If an ORM is included ad hock queries have to be available without to much wrestling. Right now the list includes: CouchDB I haven't yet looked into this. DB-API this seems to be a standard python api and each db creates their own module that uses it. Even BSDDB seems to have one written but I haven't fully explored it. are the modules interchangeable? SQLAlchemy This seems to be the most popular right now? but I have very limited exposure to the python world. SQLObject I haven't yet looked into this. So what are peoples views and suggestions on database abstraction layers for python?
Look very closely at SQLAlchemy. You can test and develop with SQLite. You can go into production with MySQL -- making essentially no changes to your applications. The DB-API, while widely adhered-to, has enough flexibility that (1) you aren't insulated from SQL variation in the underlying RDBMS and (2) there are still DB driver-specific features that are hard to hide. Another good ORM layer is the ORM that's part of Django. You can (with a little effort) use just the Django ORM without using the rest of the Django web framework. Use an ORM Layer (SQLAlchemy or SQLObject) in preference to DB-API. Why? Your model should be a solid, clear, well-thought-out OO model. The relational mapping should come second after the object model. SQLAlchemy makes this a reasonable approach. A "DB Abstraction Layer" will happen in the normal course of events. Indeed, because of DB-API (as used by SQLAlchemy) you gave two abstraction layers: ORM and DB-API.
Using MultipartPostHandler to POST form-data with Python
Problem: When POSTing data with Python's urllib2, all data is URL encoded and sent as Content-Type: application/x-www-form-urlencoded. When uploading files, the Content-Type should instead be set to multipart/form-data and the contents be MIME encoded. A discussion of this problem is here: http://code.activestate.com/recipes/146306/ To get around this limitation some sharp coders created a library called MultipartPostHandler which creates an OpenerDirector you can use with urllib2 to mostly automatically POST with multipart/form-data. A copy of this library is here: http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html I am new to Python and am unable to get this library to work. I wrote out essentially the following code. When I capture it in a local HTTP proxy, I can see that the data is still URL encoded and not multi-part MIME encoded. Please help me figure out what I am doing wrong or a better way to get this done. Thanks :-) FROM_ADDR = 'my@email.com' try: data = open(file, 'rb').read() except: print "Error: could not open file %s for reading" % file print "Check permissions on the file or folder it resides in" sys.exit(1) # Build the POST request url = "http://somedomain.com/?action=analyze" post_data = {} post_data['analysisType'] = 'file' post_data['executable'] = data post_data['notification'] = 'email' post_data['email'] = FROM_ADDR # MIME encode the POST payload opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler) urllib2.install_opener(opener) request = urllib2.Request(url, post_data) request.set_proxy('127.0.0.1:8080', 'http') # For testing with Burp Proxy # Make the request and capture the response try: response = urllib2.urlopen(request) print response.geturl() except urllib2.URLError, e: print "File upload failed..." EDIT1: Thanks for your response. I'm aware of the ActiveState httplib solution to this (I linked to it above). I'd rather abstract away the problem and use a minimal amount of code to continue using urllib2 how I have been. Any idea why the opener isn't being installed and used?
It seems that the easiest and most compatible way to get around this problem is to use the 'poster' module. # test_client.py from poster.encode import multipart_encode from poster.streaminghttp import register_openers import urllib2 # Register the streaming http handlers with urllib2 register_openers() # Start the multipart/form-data encoding of the file "DSC0001.jpg" # "image1" is the name of the parameter, which is normally set # via the "name" parameter of the HTML <input> tag. # headers contains the necessary Content-Type and Content-Length # datagen is a generator object that yields the encoded parameters datagen, headers = multipart_encode({"image1": open("DSC0001.jpg")}) # Create the Request object request = urllib2.Request("http://localhost:5000/upload_image", datagen, headers) # Actually do the request, and get the response print urllib2.urlopen(request).read() This worked perfect and I didn't have to muck with httplib. The module is available here: http://atlee.ca/software/poster/index.html
Python Class Decorator
In Python 2.5, is there a way to create a decorator that decorates a class? Specifically, I want to use a decorator to add a member to a class and change the constructor to take a value for that member. Looking for something like the following (which has a syntax error on 'class Foo:': def getId(self): return self.__id class addID(original_class): def __init__(self, id, *args, **kws): self.__id = id self.getId = getId original_class.__init__(self, *args, **kws) @addID class Foo: def __init__(self, value1): self.value1 = value1 if __name__ == '__main__': foo1 = Foo(5,1) print foo1.value1, foo1.getId() foo2 = Foo(15,2) print foo2.value1, foo2.getId() Thanks, Rob Edit: Rereading this question, I guess what I'm really after is a way to do something like a C# interface in Python. I need to switch my paradigm I suppose.
Apart from the question whether class decorators are the right solution to your problem: in Python 2.6 and higher, there are class decorators with the @-syntax, so you can write: @addID class Foo: pass in older versions, you can do it another way: class Foo: pass Foo = addID(Foo) Note however that this works the same as for function decorators, and that the decorator should return the new (or modified original) class, which is not what you're doing in the example. The addID decorator would look like this: def addID(original_class): orig_init = original_class.__init__ # make copy of original __init__, so we can call it without recursion def __init__(self, id, *args, **kws): self.__id = id self.getId = getId orig_init(self, *args, **kws) # call the original __init__ original_class.__init__ = __init__ # set the class' __init__ to the new one return original_class You could then use the appropriate syntax for your python version as described above. But I agree with others that inheritance is better suited if you want to override __init__.
Which version of python added the else clause for for loops?
Which was the first version of python to include the else clause for for loops? I find that the python docs usually does a good job of documenting when features were added, but I can't seem to find the info on this feature. (It doesn't help that 'for' and 'else' are particularly difficult terms to google for on a programming website)
It's been present since the beginning. To see that, get the source from alt.sources, specifically the message titled "Python 0.9.1 part 17/21". The date is Feb 21, 1991. This post included the grammar definition, which states: for_stmt: 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] You might be able to find the 0.9.0 sources if you try harder than I did, but as the first public release was 0.9.0 on 20 Feb, that would get you back one day. The 0.9.1 release was a minor patch that did not affect this part of the grammar. (Is that a UTSL reference or what? When was the last time you looked at a shar file? ;) BTW, I reconstructed the original source and tweaked it a bit to compile under gcc-4.0 on my OS X 10.4 box. Details for those interested few, including python-0.9.1.tar.gz. The entire development history is available from version control, even after changing version control systems twice. "hg log -p -r 6:7" from the cpython Mercurial archive shows that the "for/else" was committed on Sun Oct 14 12:07:46 1990 +0000, and the previous commit was Sat Oct 13 19:23:40 1990 +0000. for/else has been part of Python since October 1990.
What is a clean, pythonic way to have multiple constructors in Python?
I can't find a definitive answer for this. AFAIK, you can't have multiple __init__ functions in a Python class. So what is a good way to solve this problem? Suppose I have an class called Cheese with the number_of_holes property. How can I have two ways of creating cheese-objects... one that takes a number of holes like this: parmesan = Cheese(num_holes = 15) and one that takes no arguments and just randomizes the number_of_holes property: gouda = Cheese() I can think of only one way to do this, but that seems kinda clunky: class Cheese(): def __init__(self, num_holes = 0): if (num_holes == 0): # randomize number_of_holes else: number_of_holes = num_holes What do you say? Is there a better way?
Actually None is much better for "magic" values: class Cheese(): def __init__(self, num_holes = None): if num_holes is None: ... Now if you want complete freedom of adding more parameters: class Cheese(): def __init__(self, *args, **kwargs): #args -- tuple of anonymous arguments #kwargs -- dictionary of named arguments self.num_holes = kwargs.get('num_holes',random_holes()) To better explain the concept of *args and **kwargs (you can actually change these names): def f(*args, **kwargs): print 'args: ', args, ' kwargs: ', kwargs >>> f('a') args: ('a',) kwargs: {} >>> f(ar='a') args: () kwargs: {'ar': 'a'} >>> f(1,2,param=3) args: (1, 2) kwargs: {'param': 3} http://docs.python.org/reference/expressions.html#calls
Dynamically change the choices in a wx.ComboBox()
I didn't find a better way to change the different choices in a wx.ComboBox() than swap the old ComboBox with a new one. Is there a better way? Oerjan Pettersen #!/usr/bin/python #20_combobox.py import wx import wx.lib.inspection class MyFrame(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.p1 = wx.Panel(self) lst = ['1','2','3'] self.st = wx.ComboBox(self.p1, -1, choices = lst, style=wx.TE_PROCESS_ENTER) self.st.Bind(wx.EVT_COMBOBOX, self.text_return) def text_return(self, event): lst = ['3','4'] self.st = wx.ComboBox(self.p1, -1, choices = lst, style=wx.TE_PROCESS_ENTER) class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, -1, '20_combobox.py') frame.Show() self.SetTopWindow(frame) return 1 if __name__ == "__main__": app = MyApp(0) # wx.lib.inspection.InspectionTool().Show() app.MainLoop()
wx.ComboBox derives from wx.ItemContainer, which has methods for Appending, Clearing, Inserting and Deleting items, all of these methods are available on wx.ComboBox. One way to do what you want would be to define the text_return() method as follows: def text_return(self, event): self.st.Clear() self.st.Append('3') self.st.Append('4')
Best way to integrate Python and JavaScript?
Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if anyone has done it within a "serious" project or product. I'm guessing it would be possible using Jython and Rhino, for one example, but I'm curious whether or not anyone's ever actually done this, and if there are solutions for other platforms (especially CPython).
How about pyjs? From the above website: pyjs is a Rich Internet Application (RIA) Development Platform for both Web and Desktop. With pyjs you can write your JavaScript-powered web applications entirely in Python.