text
stringlengths
226
34.5k
How to remove two chars from the beginning of a line Question: I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this: #!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here Answer: You were off to a good start. Try this in your loop: for line in lines: line = line[2:] # do something here The [2:] is called "[slice](http://docs.python.org/tutorial/introduction.html#strings)" syntax, it essentially says "give me the part of this sequence which begins at index 2 and continues to the end (since no end point was specified after the colon).
exec() bytecode with arbitrary locals? Question: Suppose I want to execute code, for example value += 5 inside a namespace of my own (so the result is essentially `mydict['value'] += 5`). There's a function `exec()`, but I have to pass a string there: exec('value += 5', mydict) and passing statements as strings seems strange (e.g. it's not colorized that way). Can it be done like: def block(): value += 5 ???(block, mydict) ? The obvious candidate for last line was `exec(block.__code__, mydict)`, but no luck: it raises `UnboundLocalError` about `value`. I believe it basically executes `block()`, not _the code inside block_ , so assignments aren't easy – is that correct? Of course, another possible solution would be to disassembly `block.__code__`... FYI, I got the question because of [this thread](http://mail.python.org/pipermail/python- ideas/2009-August/005552.html). Also, this is why some (me undecided) call for new syntax using mydict: value += 5 * * * Note how this doesn't throw error but doesn't change `mydict` either: def block(value = 0): value += 5 block(**mydict) Answer: You can pass bytecode instead of a string to `exec`, you just need to make the right bytecode for the purpose: >>> bytecode = compile('value += 5', '<string>', 'exec') >>> mydict = {'value': 23} >>> exec(bytecode, mydict) >>> mydict['value'] 28 Specifically, ...: >>> import dis >>> dis.dis(bytecode) 1 0 LOAD_NAME 0 (value) 3 LOAD_CONST 0 (5) 6 INPLACE_ADD 7 STORE_NAME 0 (value) 10 LOAD_CONST 1 (None) 13 RETURN_VALUE the load and store instructions must be of the _NAME persuasion, and this `compile` makes them so, while...: >>> def f(): value += 5 ... >>> dis.dis(f.func_code) 1 0 LOAD_FAST 0 (value) 3 LOAD_CONST 1 (5) 6 INPLACE_ADD 7 STORE_FAST 0 (value) 10 LOAD_CONST 0 (None) 13 RETURN_VALUE ...code in a function is optimized to use the _FAST versions, and those don't work on a dict passed to `exec`. If you started somehow with a bytecode using the _FAST instructions, you could patch it to use the _NAME kind instead, e.g. with [bytecodehacks](http://mail.python.org/pipermail/python-announce- list/2004-July/003280.html) or some similar approach.
wxPython: Items in BoxSizer don't expand horizontally, only vertically Question: I have several buttons in various sizers and they expand in the way that I want them to. However, when I add the parent to a new wx.BoxSizer that is used to add a border around all the elements in the frame, the sizer that has been added functions correctly vertically, but not horizontally. The following code demonstrates the problem: #! /usr/bin/env python import wx import webbrowser class App(wx.App): def OnInit(self): frame = MainFrame() frame.Show() self.SetTopWindow(frame) return True class MainFrame(wx.Frame): title = 'Title' def __init__(self): wx.Frame.__init__(self, None, -1, self.title) panel = wx.Panel(self) #icon = wx.Icon('icon.png', wx.BITMAP_TYPE_PNG) #self.SetIcon(icon) sizer = wx.FlexGridSizer(rows=2, cols=1, vgap=10, hgap=10) button1 = wx.Button(panel, -1, 'BUTTON') sizer.Add(button1, 0, wx.EXPAND) buttonSizer = wx.FlexGridSizer(rows=1, cols=4, vgap=10, hgap=5) buttonDelete = wx.Button(panel, -1, 'Delete') buttonSizer.Add(buttonDelete, 0, 0) buttonEdit = wx.Button(panel, -1, 'Edit') buttonSizer.Add(buttonEdit, 0, 0) buttonNew = wx.Button(panel, -1, 'New') buttonSizer.Add(buttonNew, 0, 0) buttonSizer.AddGrowableCol(0, 0) sizer.Add(buttonSizer, 0, wx.EXPAND|wx.HORIZONTAL) sizer.AddGrowableCol(0, 0) sizer.AddGrowableRow(0, 0) mainSizer = wx.BoxSizer(wx.EXPAND) mainSizer.Add(sizer, 0, wx.EXPAND|wx.ALL, 10) #panel.SetSizerAndFit(sizer) #sizer.SetSizeHints(self) panel.SetSizerAndFit(mainSizer) mainSizer.SetSizeHints(self) if __name__ == '__main__': app = App(False) app.MainLoop() Commenting out lines **57** and **58** and uncommenting lines **55** and **56** removes the extra BoxSizer and shows how I expect everything to function (without the whitespace of course). I am completely stuck with this problem and still have no clue as to how to fix it. Answer: First of all, you're passing some flags incorrectly. BoxSizer takes wx.HORIZONTAL or wx.VERTICAL, not wx.EXPAND. sizer.Add does not take wx.HORIZONTAL. If you have a VERTICAL BoxSizer, wx.EXPAND will make the control fill horizontally, while a proportion of 1 or more (second argument to Add) will make the control fill vertically. It's the opposite for HORIZONTAL BoxSizers. sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(widget1, 0, wx.EXPAND) sizer.Add(widget2, 1) widget1 will expand horizontally. widget2 will expand vertically. If you put a sizer in another sizer, you need to be sure to have its proportion and EXPAND flags set so that its insides will grow how you want them to. I'll leave the rest to you.
models.py with ManyToMany and progmatically adding data via a shell script Question: First post to stackoverflow I did do a search and came up dry. I also own the django book (Forcier,Bissex,Chun) and they don't explain how to do this. In short I can't figure out how to progmatically add a data via a python shell script to the ManyToMay model.. from django.db import models from django.contrib import admin class Client(models.Model): client = models.CharField(max_length=256, primary_key=True) access = models.DateField() description = models.TextField() host = models.CharField(max_length=256) lineEnd = models.CharField(max_length=256) options = models.TextField() owner = models.CharField(max_length=100) root = models.CharField(max_length=256) submitOptions = models.CharField(max_length=256) update = models.DateField() def __unicode__(self): return str(self.client) admin.site.register(Client) class Change(models.Model): """This simply expands out 'p4 describe' """ change = models.IntegerField(primary_key=True) client = models.ManyToManyField(Client) desc = models.TextField() status = models.CharField(max_length=128) def __unicode__(self): return str(self.change) admin.site.register(Change) Here is what I have which works but I don't know how to add the ManyToMany. I can't seem to figure out how to progmatically call it. I know the row in SQL exists. \--- massImport.py --- # Assume the client "clientspec" exists. I know how to create that if neeeded. changes = [ { 'change': 123, 'desc': "foobar", status': "foobar", client': "clientspec", }] for item in changes: entry = Change( change = item['change'], desc = item['desc'], status = item['status'], # client = Client.objects.filter(client=item['client']) ) entry.save() Can anyone show me where the error of my ways is. I would really appreciate it. Thanks!! Answer: Turns out Tiago was very close.. # Assume the client "clientspec" exists. I know how to create that if neeeded. changes = [ { 'change': 123, 'desc': "foobar", status': "foobar", client': "clientspec", }] for item in changes: entry = Change() entry.change = item['change'] entry.desc = item['desc'] entry.status = item['status'] entry.time = datetime.datetime.fromtimestamp(float(item['time'])) entry.client.add(Client.objects.get(client=item['client'])) entry.save() So.. I will give props to Tiago
Can't get Beaker sessions to work (KeyError) Question: I'm a newb to the Python world and am having the dangest time with getting sessions to work in my web frameworks. I've tried getting Beaker sessions to work with the webpy framework and the Juno framework. And in both frameworks I always get a KeyError when I try to start the session. Here is the error message in webpy (its pretty much the exact same thing when I try to use beaker sessions in Juno too)... ERROR <type 'exceptions.KeyError'> at / 'beaker.session' Python /Users/tyler/Dropbox/Code/sites/webpy1/code.py in GET, line 15 Web GET http://localhost:1234/ 15. session = web.ctx.environ['beaker.session'] CODE import web import beaker.session from beaker.middleware import SessionMiddleware urls = ( '/', 'index' ) class index: def GET(self): session = web.ctx.environ['beaker.session'] return "hello" app = web.application(urls, globals()) if __name__ == "__main__": app.run() Answer: You haven't created the session object yet, so you can't find it in the environment (the `KeyError` simply means "`beaker.session` is not in this dictionary"). Note that I don't know either webpy nor beaker very well, so I can't give you deeper advice, but from what I understand from the docs and source this should get you started: if __name__ == "__main__": app.run(SessionMiddleware)
How useful would be a Smalltalk source code browser for other programming languages? Question: I'm working on an IDE for python, ruby and php. Never having used Smallltalk myself (even it was very popular when I was at university) I wonder if the classic Smalltalk Browser which displays only one method is really an improvment or to classical file editing or not. I myself like to have the overview of as much as possible in a class. Now i use a 24" 1280x1920 display in a two column mode which can display **a lot** of lines at ones. I personally have to wonder what is the benefit if you for example also have good code folding editor where a user can fold for example all def's (functions code bodies) with one keystroke. But I see the request to make xxx more smalltalkish from time to time in newsgroups. I know some might want an image based version but the browser was the second most different Smalltalk invention. Answer: The Smalltalk browser has two parts: the top one shows the packages, classes, protocols and methods/messages, the bottom one shows the content of one method. This is very usefull if you design/code your program thinking more on signatures and names, rather than as a web of lines of codes. If you concentrate on signature, this could lead to a more "object oriented" style, where the system is designed as a collaboration of objects sending messages to each other. In this paradigm, the methods names are somehow more important than how they are implemented. If you have a very large screen (I got one myself :-)) you would open several smalltalk browsers allowing you to browse (and code) in several different packages and classes. Moreover, you would probably also have a worspace and a xUnit to test and play with your objects. I suggest you look at the Whisker editor created for Squeak. It proposes a quite nice balance between names and signatures navigation, and lines of code exploration. You would need to try it, as the screenshot does not show the dynamic of it, and how you navigate thru the "boxes" of codes. <http://www.mindspring.com/~dway/smalltalk/whisker.html>
Python re question - sub challenge Question: I want to add a href links to all words prefixed with # or ! or @ If this is the text Check the #bamboo and contact @Fred re #bamboo #garden should be converted to: Check the <a href="/what/bamboo">#bamboo</a> and contact <a href="/who/fred">@Fred</a> re <a href="/what/bamboo">#bamboo</a> <a href="/what/garden">#garden</a> Note that # and @ go to different places. This is as far as I have got, just doing the hashes... matched = re.sub("[#](?P<keyword>\w+)", \ '<a href="/what/(?P=keyword)">(?P=keyword)</a>', \ text) Any re gurus able to point me in the right direction. Do I need to do separate matches for each symbol? Answer: I'd do it with a single match and a function picking the "place". I.e.: import re places = {'#': 'what', '@': 'who', '!': 'why', } def replace(m): all = m.group(0) first, rest = all[0], all[1:] return '<a href="/%s/%s">%s</a>' % ( places[first], rest, all) markedup = re.sub(r'[#!@]\w+', replace, text)
relevent query to how to fetch public key from public key server Question: import urllib response = urllib.urlopen('http://pool.sks-keyservers.net/') print 'RESPONSE:', response print 'URL :', response.geturl() headers = response.info() print 'DATE :', headers['date'] print 'HEADERS :' print '---------' print headers data = response.read() print 'LENGTH :', len(data) print 'DATA :' print '---------' print data This code enable me to see some webpage information and contents. what actually i had query that how to fetch the public key from any public key server using python function. Answer: [This spec](http://tools.ietf.org/html/draft-shaw-openpgp-hkp-00) should help you along, and stop you asking the same question repeatedly :). Basically you need to perform an HTTP GET request to the key server. Most key servers work on TCP port 11371 so you need to ensure that your firewall will let you through. For example, this URL will give you God's public key: [http://pool.sks- keyservers.net:11371/pks/lookup?op=get&search=0x1278A1862492D908&options=mr](http://pool.sks- keyservers.net:11371/pks/lookup?op=get&search=0x1278A1862492D908&options=mr) The response is the key. In python: import urllib f = urllib.urlopen('http://pool.sks-keyservers.net:11371/pks/lookup?op=get&search=0x1278A1862492D908&options=mr') data = f.read() print data -----BEGIN PGP PUBLIC KEY BLOCK----- Version: SKS 1.1.0 mQGiBD/dywoRBADkaddBEedMhFHGH3wKORuOIDFufSDERmlm2ktj3ma+GhfwvnuvvpAj+QYl ANh1K86Mm5k0dGOlhZwIr1zB3cIoNqt7TJ62v8w6mc0BA8UWzWJp0i6dHPa/qeeFFC53B8U1 h3FlPrmQGcVeV+hjOPFU7ANDSDm3tduad7NRxAst7QCg/8o++2BaAlTnbMB+Xfo23uEEc6UE AK0vD4EUPLfU5snfow1zUPXQUDalOcUP6RIhbi6yxKRFAIWI+7QgNPZf/Q2CFIRWsXKmW/ly IDSJgs5ruB+Yj8gmBZlrn5KMmW3EcEoHAhOP+ONZAIOb2LsaAjHjHOuefhlIr1T3gng+kLoD 3Yfy2WTugBizeNybAd2nfZyOJhfWA/4xTfg+Hbcb9n+8sEqgiuyQJEID38Q3FDmwSzRfBMbO JFrf8t/VHPjB7ZSdshl9GM86TXYnWjspzAjjQB8fxLgIim2mC0T46aRNdE0l2ozxRmS95nr7 YuHVA73vcI5tRn6qa9yLXew1YeN3YWxRfIW2AZG7bkRcXOIdl7tO9KiVpbQUR29kIDxHb2RA aGVhdmVuLmNvbT6IWAQQEQIAGAUCP93LCggLAwkIBwIBCgIZAQUbAwAAAAAKCRASeKGGJJLZ CAp7AJ9WqGhOnysRt/b7p+EuC86lhs3iBgCdEVwLgEwcc63OVbBxxFF6vyiNuNG5Ag0EP93L ChAIAPZCV7cIfwgXcqK61qlC8wXo+VMROU+28W65Szgg2gGnVqMU6Y9AVfPQB8bLQ6mUrfdM ZIZJ+AyDvWXpF9Sh01D49Vlf3HZSTz09jdvOmeFXklnN/biudE/F/Ha8g8VHMGHOfMlm/xX5 u/2RXscBqtNbno2gpXI61Brwv0YAWCvl9Ij9WE5J280gtJ3kkQc2azNsOA1FHQ98iLMcfFst jvbzySPAQ/ClWxiNjrtVjLhdONM0/XwXV0OjHRhs3jMhLLUq/zzhsSlAGBGNfISnCnLWhsQD GcgHKXrKlQzZlp+r0ApQmwJG0wg9ZqRdQZ+cfL2JSyIZJrqrol7DVekyCzsAAgIH/j7FzAvF jCmq3vXWnDOymAfJgTNyvYB67y0Xu2HXqGlXe92Gkxcf22w4X63TkZqMy7nXRbGc9WI2sr57 oSTJq3+42WHnVQjd9W10TFIgnH2YkuSC3KckMB5hC1yM9wqaIXNhfxXmq3B4V3UuKLyM3nQi SgWb9+kST3FxcGWXRB0Ec/tIJ0cNeFtu5IrYDNkRbcHep/BuwXEARUIpjlUlG7NPIaY4U03I /GSW7/IrG5/H7EsVWQzxRpcC6DcJjxJv2lIATvraXHwNpllOlPHFb9aABHmTOX7QLrG4FXTP ReH6rjf+w5tqJilTMwYdsZIV13U7+NBwVZHFbUdYMmqhOTiITAQYEQIADAUCP93LCgUbDAAA AAAKCRASeKGGJJLZCMqJAKCzS0hv0EY/GYdUKOOf3XiiZpu3qwCg9kFBm/GO+t073SsHkedu HT0F6po= =NhFO -----END PGP PUBLIC KEY BLOCK-----
Python socket error occured Question: I wrote this code. import socket host = 'localhost' port = 3794 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind((host, port)) while 1: print 'Type message you want to send...' msg = raw_input() if msg == '': s.close() break s.sendall(msg) and next execute this code. Traceback (most recent call last): File "socket.py", line 11, in ? s.bind((host, port)) File "<string>", line 1, in bind socket.error: (99, 'Cannot assign requested address') What's wrong? Do you know solutions? Answer: This means that you already have a socket bound to 3794 port. It may be another application or it means that port didn't got released yet after the previous run of your own script (it happens, if script terminated improperly). Simply try to use another port number - I believe everything will work fine.
Calculating a SHA hash with a string + secret key in python Question: Amazon Product API now requires a signature with every request which I'm trying to generate ushing Python. The step I get hung up on is this one: "Calculate an RFC 2104-compliant HMAC with the SHA256 hash algorithm using the string above with our "dummy" Secret Access Key: 1234567890. For more information about this step, see documentation and code samples for your programming language." Given a string and a secret key (in this case 1234567890) how do I calculate this hash using Python? \----------- UPDATE ------------- The first solution using HMAC.new looks correct however I'm getting a different result than they are. <http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/index.html?rest- signature.html> According to Amazon's example when you hash the secret key 1234567890 and the following string GET webservices.amazon.com /onca/xml AWSAccessKeyId=00000000000000000000&ItemId=0679722769&Operation=I temLookup&ResponseGroup=ItemAttributes%2COffers%2CImages%2CReview s&Service=AWSECommerceService&Timestamp=2009-01-01T12%3A00%3A00Z& Version=2009-01-06 You should get the following signature: `'Nace+U3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg='` I am getting this: `'411a59403c9f58b4a434c9c6a14ef6e363acc1d1bb2c6faf9adc30e20898c83b'` Answer: import hmac import hashlib import base64 dig = hmac.new(b'1234567890', msg=your_bytes_string, digestmod=hashlib.sha256).digest() base64.b64encode(dig).decode() # py3k-mode 'Nace+U3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg='
Is this a bug in Django formset validation? Question: Manual example: <http://docs.djangoproject.com/en/1.0/topics/forms/formsets/#formset- validation> (I'm using Django 1.0.3 to run on Google App Engine) Code: from django import forms from django.forms.formsets import formset_factory class ArticleForm1(forms.Form): title = forms.CharField() pub_date = forms.DateField() class ArticleForm2(forms.Form): title = forms.CharField() class ArticleForm3(forms.Form): title = forms.CharField() pub_date = forms.CharField() ArticleFormSet1 = formset_factory(ArticleForm1) ArticleFormSet2 = formset_factory(ArticleForm2) ArticleFormSet3 = formset_factory(ArticleForm3) data = { 'form-TOTAL_FORMS': u'2', 'form-INITIAL_FORMS': u'0', 'form-0-title': u'', 'form-0-pub_date': u'16 June 1904', 'form-1-title': u'', # <-- this title is missing but required 'form-1-pub_date': u'16 June 1904', # <-- this date is missing but required } formset = ArticleFormSet1(data) print "Should be False: %s" % formset.is_valid() formset = ArticleFormSet2(data) print "Should be False: %s" % formset.is_valid() formset = ArticleFormSet3(data) print "Should be False: %s" % formset.is_valid() Output: $ .../ActiveStatePython2.5/python.exe formset_bug.py Should be False: False Should be False: True Should be False: False ActiveState Python 2.5.4.4, Django 1.0.3 final. It looks as if it's not validating in the case of only one CharField (but 2 CharFields or a CharField and a DateField works). I Googled for such a bug and couldn't find anything. I haven't yet tried Django 1.1, but it's much easier to use 1.0 on GAE for now. Answer: Okay, I understand more about Django now. This is not a bug. From <http://docs.djangoproject.com/en/1.0/topics/forms/formsets/#formset- validation>: "The formset is smart enough to ignore extra forms that were not changed." From <http://stackoverflow.com/questions/927619/django-formset-isvalid- failing-for-extra-forms>: "Formsets pass empty_permitted=True to all "extra" forms, and a form with empty_permitted that hasn't been modified should always pass validation." When I set form-TOTAL_FORMS to u'2', it no longer has any extra, and the validation does what I expect. When there is part of a second field (either as DateField or CharField), the field has some stuff and is no longer extra.
Does a UDP service have to respond from the connected IP address? Question: [Pyzor](http://pyzor.org) uses UDP/IP as the communication protocol. We recently switched the public server to a new machine, and started getting reports of many timeouts. I discovered that I could fix the problem if I changed the IP that was queried from `eth0:1` to `eth0`. I can reproduce this problem with a simple example: This is the server code: #! /usr/bin/env python import SocketServer class RequestHandler(SocketServer.DatagramRequestHandler): def handle(self): print self.packet self.wfile.write("Pong") s = SocketServer.UDPServer(("0.0.0.0", 24440), RequestHandler) s.serve_forever() This is the client code (`188.40.77.206` is `eth0`. `188.40.77.236` is the same server, but is `eth0:1`): >>> import socket >>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) >>> s.sendto('ping', 0, ("188.40.77.206", 24440)) 4 >>> s.recvfrom(1024) ('Pong', ('188.40.77.206', 24440)) >>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) >>> s.sendto('ping', 0, ("188.40.77.236", 24440)) 4 >>> s.recvfrom(1024) [never gets anything] The server gets the "ping" packet in both cases (and therefore sends the "pong" packet in both cases). Oddly, this **does** work from some places (i.e. I'll get a response from both IPs). For example, it works from `188.40.37.137` (same network/datacenter, different server), but also from `89.18.189.160` (different datacenter). In those cases, the `recvfrom` response does have the `eth0` IP, rather than the one that was connected to. Is this just a rule of UDP? Is this a problem/limitation with the [Python](http://python.org) `UDPServer` class? Is it something I'm doing incorrectly? Is there any way that I can have this work apart from simply connecting to the `eth0` IP (or listening on the specific IP rather than `0.0.0.0`)? Answer: I came across this with a TFTP server. My server had two IP addresses facing the same network. Because UDP is connectionless, there can be issues with IP addresses not being set as expected in that situation. The sequence I had was: 1. Client sends the initial packet to the server at a particular IP address 2. Server reads the client's source address from the incoming packet, and sends a response. 1. However, in the response, the server's "source address" is set according to the routing tables, and it gets set to the **other** IP address. 2. It wasn't possible to control the server's "source" IP address because the OS didn't tell us which IP address the request came in through. 3. The client gets a response from the "other" IP address, and rejects it. The solution in my case was to specifically bind the TFTP server to the IP address that I wanted to listen to, rather than binding to all interfaces. I found some text that may be relevant in a [Linux man page for **`tftpd`**](http://man.cx/tftpd%288%29) (TFTP server). Here it is: Unfortunately, on multi-homed systems, it is impossible for tftpd to determine the address on which a packet was received. As a result, tftpd uses two different mechanisms to guess the best source address to use for replies. If the socket that inetd(8) passed to tftpd is bound to a par‐ ticular address, tftpd uses that address for replies. Otherwise, tftpd uses ‘‘UDP connect’’ to let the kernel choose the reply address based on the destination of the replies and the routing tables. This means that most setups will work transparently, while in cases where the reply address must be fixed, the virtual hosting feature of inetd(8) can be used to ensure that replies go out from the correct address. These con‐ siderations are important, because most tftp clients will reject reply packets that appear to come from an unexpected address. See [this answer](http://stackoverflow.com/a/3929208/60075) which shows that on Linux it _is_ possible to read the local address for incoming UDP packets, and set it for outgoing packets. It's possible in C; I'm not sure about Python though.
What is the oldest time that can be represented in python? Question: I have written a function comp(time1, time2) which will return true when time1 is lesser than time2. I have a scenario where time1 should always be lesser than time2. I need time1 to have the least possible value(date). How to find this time and how to form the corresponding object. Answer: If using the [datetime](https://docs.python.org/2/library/datetime.html) module, [date](https://docs.python.org/2/library/datetime.html#date-objects), [time](https://docs.python.org/2/library/datetime.html#time-objects), and [datetime](https://docs.python.org/2/library/datetime.html#datetime-objects) objects all have a `min` and `max` attribute. >>> from datetime import date, time, datetime >>> date.min datetime.date(1, 1, 1) >>> date.max datetime.date(9999, 12, 31) >>> time.min datetime.time(0, 0) >>> time.max datetime.time(23, 59, 59, 999999) >>> datetime.min datetime.datetime(1, 1, 1, 0, 0) >>> datetime.max datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
Python: what kind of literal delimiter is "better" to use? Question: What is the best literal delimiter in Python and why? Single ' or double "? And most important, why? I'm a beginner in Python and I'm trying to stick with just one. I know that in PHP, for example " is preferred, because PHP does not try to search for the 'string' variable. Is the same case in Python? Answer: ' because it's one keystroke less than ". Save your wrists! They're otherwise identical (except you have to escape whichever you choose to use, if they appear inside the string).
gotchas where Numpy differs from straight python? Question: Folks, is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ? > "The horror of that moment I shall never never forget !" > "You will, though," the Queen said, "if you don't make a memorandum of it." For example, NaNs are always trouble, anywhere. If you can explain this without running it, give yourself a point -- from numpy import array, NaN, isnan pynan = float("nan") print pynan is pynan, pynan is NaN, NaN is NaN a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) (I'm not knocking numpy, lots of good work there, just think a FAQ or Wiki of gotchas would be useful.) Edit: I was hoping to collect half a dozen gotchas (surprises for people learning Numpy). Then, if there are common gotchas or, better, common explanations, we could talk about adding them to a community Wiki (where ?) It doesn't look like we have enough so far. Answer: Because `__eq__` does not return a bool, using numpy arrays in any kind of containers prevents equality testing without a container-specific work around. Example: >>> import numpy >>> a = numpy.array(range(3)) >>> b = numpy.array(range(3)) >>> a == b array([ True, True, True], dtype=bool) >>> x = (a, 'banana') >>> y = (b, 'banana') >>> x == y Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() This is a horrible problem. For example, you cannot write unittests for containers which use `TestCase.assertEqual()` and must instead write custom comparison functions. Suppose we write a work-around function `special_eq_for_numpy_and_tuples`. Now we can do this in a unittest: x = (array1, 'deserialized') y = (array2, 'deserialized') self.failUnless( special_eq_for_numpy_and_tuples(x, y) ) Now we must do this for every container type we might use to store numpy arrays. Furthermore, `__eq__` might return a bool rather than an array of bools: >>> a = numpy.array(range(3)) >>> b = numpy.array(range(5)) >>> a == b False Now each of our container-specific equality comparison functions must also handle that special case. Maybe we can patch over this wart with a subclass? >>> class SaneEqualityArray (numpy.ndarray): ... def __eq__(self, other): ... return isinstance(other, SaneEqualityArray) and self.shape == other.shape and (numpy.ndarray.__eq__(self, other)).all() ... >>> a = SaneEqualityArray( (2, 3) ) >>> a.fill(7) >>> b = SaneEqualityArray( (2, 3) ) >>> b.fill(7) >>> a == b True >>> x = (a, 'banana') >>> y = (b, 'banana') >>> x == y True >>> c = SaneEqualityArray( (7, 7) ) >>> c.fill(7) >>> a == c False That seems to do the right thing. The class should also explicitly export elementwise comparison, since that is often useful.
Python/Suds: Type not found: 'xs:complexType' Question: I have the following simple python test script that uses [Suds](https://fedorahosted.org/suds/) to call a SOAP web service (the service is written in ASP.net): from suds.client import Client url = 'http://someURL.asmx?WSDL' client = Client( url ) result = client.service.GetPackageDetails( "MyPackage" ) print result When I run this test script I am getting the following error (used code markup as it doesn't wrap): No handlers could be found for logger "suds.bindings.unmarshaller" Traceback (most recent call last): File "sudsTest.py", line 9, in <module> result = client.service.GetPackageDetails( "t3db" ) File "build/bdist.cygwin-1.5.25-i686/egg/suds/client.py", line 240, in __call__ File "build/bdist.cygwin-1.5.25-i686/egg/suds/client.py", line 379, in call File "build/bdist.cygwin-1.5.25-i686/egg/suds/client.py", line 240, in __call__ File "build/bdist.cygwin-1.5.25-i686/egg/suds/client.py", line 422, in call File "build/bdist.cygwin-1.5.25-i686/egg/suds/client.py", line 480, in invoke File "build/bdist.cygwin-1.5.25-i686/egg/suds/client.py", line 505, in send File "build/bdist.cygwin-1.5.25-i686/egg/suds/client.py", line 537, in succeeded File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/binding.py", line 149, in get_reply File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 303, in process File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 88, in process File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 104, in append File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 181, in append_children File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 104, in append File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 181, in append_children File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 104, in append File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 181, in append_children File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 102, in append File "build/bdist.cygwin-1.5.25-i686/egg/suds/bindings/unmarshaller.py", line 324, in start suds.TypeNotFound: Type not found: 'xs:complexType' Looking at the source for the WSDL file's header (reformatted to fit): <?xml version="1.0" encoding="utf-8" ?> <wsdl:definitions xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://http://someInternalURL/webservices.asmx" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" targetNamespace="http://someURL.asmx" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"> I am guessing based on the last line of output: suds.TypeNotFound: Type not found: 'xs:complexType' That I need to use Sud's [doctor class](https://fedorahosted.org/suds/wiki/Documentation#FIXINGBROKENSCHEMAs) to fix the schema but being a SOAP newbie I don't know what exactly needs fixed in my case. Does anyone here have any experience using Suds to fix/correct schema? Answer: **Ewall** 's resource is a good one. If you try to search in suds trac tickets, you could see that other people have problems [similar to yours](https://fedorahosted.org/suds/ticket/220), but with different object types. It can be a good way to learn from it's examples and how they import their namespaces. > The problem is that your wsdl contains a schema definition that references > the (...) but fails to import the > "http://schemas.xmlsoap.org/soap/encoding/" namespace (and associated > schema) properly. The schema can be patched at runtime using the schema > ImportDoctor as discussed here: > <https://fedorahosted.org/suds/wiki/Documentation#FIXINGBROKENSCHEMAs>. > > **This is a fairly common problem.** > > A commonly referenced schema **(that is not imported)** is the SOAP section > 5 encoding schema. This can now be fixed as follows: (all emphasis were mine). You could try the lines that these documentations provide adding the namespaces presented in your WSDL. This can be a try-and-error aproach. imp = Import('http://schemas.xmlsoap.org/soap/encoding/') # Below is your targetNamespace presented in WSDL. Remember # that you can add more namespaces by appending more imp.filter.add imp.filter.add('http://someURL.asmx') doctor = ImportDoctor(imp) client = Client(url, doctor=doctor) You didn't provide the WSDL you're working with, I suppose you have reasons to not showing to us... so I think you have to try these possibilities by yourself. Good luck!
Why does weakproxy not always preserve equivalence in python? Question: MySQLDb uses weak proxy to prevent circular dependencies between cursors and connections. But you would expect from the documentation on weakref that you could still tests for equivalence. Yet: In [36]: interactive.cursor.connection.thread_id() Out[36]: 4267758 In [37]: interactive.web_logic.conns.primary.thread_id() Out[37]: 4267758 In [38]: interactive.cursor.connection == interactive.web_logic.conns.primary Out[38]: False In [39]: interactive.cursor.connection Out[39]: <weakproxy at 0x3881c60 to Connection at 0x94c010> In [40]: interactive.web_logic.conns.primary Out[40]: <_mysql.connection open to 'xendb01' at 94c010> How do I tell if the connections are the same ? Answer: I've long found `weakref.proxy`'s design and implementation to be somewhat shaky. Witness...: >>> import weakref >>> ob=set(range(23)) >>> rob=weakref.proxy(ob) >>> rob==ob False >>> rob.__eq__(ob) True ...DEFINITELY peculiar! In practice what I use from `weakref` are weak-key or sometimes weak-value dictionaries; but `weakref.ref` is sounder than the proxy wrapper on top of it: >>> wr=weakref.ref(ob) >>> wr()==ob True The need to "call" the ref to get the object (or None if the object has since disappeared) unfortunately makes it non-transparent (so a DB API module couldn't do it while staying compliant to the API). I don't understand why MySqlDb wants weak cursor->connection referencing at all, but if they do I see why they felt they had to use proxies rather than refs. However, one pays a very high price for that transparency! Btw, the "explicit `__eq__`" trick (or an equivalent one with `__cmp__`, depending on the type of the underlying object) may help you, even though it's definitely inelegant!
Running doctests through iPython and pseudo-consoles Question: I've got a fairly basic doctestable file: class Foo(): """ >>> 3+2 5 """ if __name__ in ("__main__", "__console__"): import doctest doctest.testmod(verbose=True) which works as expected when run directly through python. However, in iPython, I get 1 items had no tests: __main__ 0 tests in 1 items. 0 passed and 0 failed. Test passed. Since this is part of a Django project and will need access to all of the appropriate variables and such that manage.py sets up, I can also run it through a modified command, which uses code.InteractiveConsole, one result of which is `__name__` gets set to '`__console__`'. With the code above, I get the same result as with iPython. I tried changing the last line to this: this = __import__(__name__) doctest.testmod(this, verbose=True) and I get an ImportError on `__console__`, which makes sense, I guess. This has no effect on either python or ipython. So, I'd like to be able to run doctests successfully through all three of these methods, especially the InteractiveConsole one, since I expect to be needing Django pony magic fairly soon. Just for clarification, this is what I'm expecting: Trying: 3+2 Expecting: 5 ok 1 items had no tests: __main__ 1 items passed all tests: 1 tests in __main__.Foo 1 tests in 2 items. 1 passed and 0 failed. Test passed. Answer: The root problem is that `ipython` plays weird tricks with `__main__` (through its own `FakeModule` module) so that, by the time `doctest` is introspecting that "alleged module" through its `__dict__`, `Foo` is _NOT_ there -- so doctest doesn't recurse into it. Here's one solution: class Foo(): """ >>> 3+2 5 """ if __name__ in ("__main__", "__console__"): import doctest, inspect, sys m = sys.modules['__main__'] m.__test__ = dict((n,v) for (n,v) in globals().items() if inspect.isclass(v)) doctest.testmod(verbose=True) This DOES produce, as requested: $ ipython dot.py Trying: 3+2 Expecting: 5 ok 1 items had no tests: __main__ 1 items passed all tests: 1 tests in __main__.__test__.Foo 1 tests in 2 items. 1 passed and 0 failed. Test passed. Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12) [[ snip snip ]] In [1]: Just setting global `__test__` doesn't work, again because setting it as a global of what you're thinking of as `__main__` does NOT actually place it in the `__dict__` of the actual object that gets recovered by `m = sys.modules['__main__']`, and the latter is exactly the expression `doctest` is using internally (actually it uses `sys.modules.get`, but the extra precaution is not necessary here since we do know that `__main__` exists in `sys.modules`... it's just NOT the object you expect it to be!-). Also, just setting `m.__test__ = globals()` directly does not work either, for a different reason: `doctest` checks that the values in `__test__` are strings, functions, classes, or modules, and without some selection you cannot guarantee that `globals()` will satisfy that condition (in fact it won't). Here I'm selecting just classes, if you also want functions or whatnot you can use an `or` in the `if` clause in the genexp within the `dict` call. I don't know exactly how you're running a Django shell that's able to execute your script (as I believe `python manage.py shell` doesn't accept arguments, you must be doing something else, and I can't guess exactly what!-), but a similar approach should help (whether your Django shell is using ipython, the default when available, or plain Python): appropriately setting `__test__` in the object you obtain as `sys.modules['__main__']` (or `__console__`, if that's what you're then passing on to doctest.testmod, I guess) should work, as it mimics what doctest will then be doing internally to locate your test strings. And, to conclude, a philosophical reflection on design, architecture, simplicity, transparency, and "black magic"...: All of this effort is basically what's needed to defeat the "black magic" that ipython (and maybe Django, though it may be simply delegating that part to ipython) is doing on your behalf for your "convenience"... any time at which two frameworks (or more;-) are independently doing each its own brand of black magic, interoperability may suddenly require substantial effort and become anything BUT convenient;-). I'm not saying that the same convenience could have been provided (by any one or more of ipython, django and/or doctests) _without_ black magic, introspection, fake modules, and so on; the designers and maintainers of each of those frameworks are superb engineers, and I expect they've done their homework thoroughly, and are performing only the minimum amount of black magic that's indispensable to deliver the amount of user convenience they decided they needed. Nevertheless, even in such a situation, "black magic" suddenly turns from a dream of convenience to a nightmare of debugging as soon as you want to do something even marginally outside what the framework's author had conceived. OK, maybe in this case not quite a nightmare, but I do notice that this question has been open a while and even with the lure of the bounty it didn't get many answers yet -- though you now do have two answers to pick from, mine using the `__test__` special feature of doctest, @codeape's using the peculiar `__IP.magic_run` feature of ironpython. I prefer mine because it does not rely on anything internal or undocumented -- `__test__` IS a documented feature of doctest, while `__IP`, with those two looming leading underscores, scream "deep internals, don't touch" to me;-)... if it breaks at the next point release I wouldn't be at all surprised. Still, matter of taste -- that answer may arguably be considered more "convenient". But, this is exactly my point: convenience may come at an enormous price in terms of giving up simplicity, transparency, and/or avoidance of internal/undocumented/unstable features; so, as a lesson for all of us, the least black magic &c we can get away with (even at the price of giving up an epsilon of convenience here and there), the happier we'll all be in the long run (and the happier we'll make other developers that need to leverage our current efforts in the future).
python variable scope Question: I have started to learn about python and is currently reading through a script written by someone else. I noticed that globals are scattered throughout the script (and I don't like it).. Besides that, I also noticed that when I have code like this def some_function(): foo.some_method() # some other code if __name__ == '__main__' : foo = Some_Object() some_function() even though I don't pass in foo into some_function(), but some_function is still able to manipulate foo (??!). I don't quite like this although it is somewhat similar to Javascript closure (?). I would like to know whether it is possible to stop some_function() from accessing foo if foo is not passed in as a function argument? Or this is the preferred way in python??! (I'm using python 2.5 under ubuntu hardy at the moment) Answer: That script has really serious issues with style and organization -- for example, if somebody imports it they have to somehow divine the fact that they have to set `thescript.foo` to an instance of `Some_Object` before calling `some_function`... yeurgh!-) It's unfortunate that you're having to learn Python from a badly written script, but I'm not sure I understand your question. Variable scope in Python is locals (including arguments), nonlocals (i.e., locals of surrounding functions, for nested functions), globals, builtins. Is what you want to stop access to globals? `some_function.func_globals` is read-only, but you could make a new function with empty globals: import new f=new.function(some_function.func_code, {}) now calling `f()` will given an exception `NameError: global name 'foo' is not defined`. You could set this back in the module with the name `some_function`, or even do it systematically via a decorator, e.g.: def noglobal(f): return new.function(f.func_code, {}) ... @noglobal def some_function(): ... this will guarantee the exception happens whenever `some_function` is called. I'm not clear on what benefit you expect to derive from that, though. Maybe you can clarify...?
Share Python Interpreter in Apache Prefork / WSGI Question: I am attempting to run a Python application within Apache (prefork) with WSGI in such a way that a single Python interpreter will be used. This is necessary since the application uses thread synchronization to prevent race conditions from occurring. Since Apache prefork spawns multiple processes, the code winds up not being shared between the interpreters and thus the thread synchronization is irrelevant (i.e. each thread only sees it own locks which have no bearing on the other processes). Here is the setup: * Apache 2.0 (prefork) * WSGI * Python 2.5 Here is the relevant Apache configuration: WSGIApplicationGroup %{GLOBAL} <VirtualHost _default_:80> WSGIScriptAlias / /var/convergedsecurity/apache/osvm.wsgi Alias /admin_media/ /var/www/html/admin_media/ <Directory /var/www/html/admin_media> Order deny,allow Allow from all </Directory> Alias /media/ /var/www/html/media/ <Directory /var/www/html/media> Order deny,allow Allow from all </Directory> </VirtualHost> Here is what I tried so far (none of which worked): 1. Adding [WSGIApplicationGroup %{GLOBAL}](http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIApplicationGroup) 2. Specifying **WSGIDaemonProcess** and **WSGIProcessGroup** within the virtual host: WSGIDaemonProcess osvm threads=50 WSGIProcessGroup osvm Is there no way to force Apache prefork to use a single Python interpreter with WSGI? The documents seem to imply you can with the WSGIDaemonProcess and WSGIApplicationGroup options but Apache still creates a separate Python interpreter for each process. Answer: You can't have the WSGI application run in embedded mode on UNIX systems, whether it be prefork or worker MPM, as there will indeed be multiple processes. See: <http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading> Creating a daemon process group consisting of single process and delegating WSGI application to that should achieve what you want. You shouldn't even need to use WSGIApplicationGroup if it is only one mounted WSGI application you are talking about. If you want to be absolutely sure though, you can also set it. Thus configuration within VirtualHost would be: WSGIDaemonProcess osvm WSGIProcessGroup osvm WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias / /var/convergedsecurity/apache/osvm.wsgi Although 'processes=1' for WSGIDaemonProcess makes it explicit that one process is created, don't provide the option though and just let it default to one process. Any use of 'processes' option, even if for one process will see 'wsgi.multiprocess' set to True. Rather than use your actual WSGI application, I would suggest you test with the following simple test program. import cStringIO import os def application(environ, start_response): headers = [] headers.append(('Content-Type', 'text/plain')) write = start_response('200 OK', headers) input = environ['wsgi.input'] output = cStringIO.StringIO() print >> output, "PID: %s" % os.getpid() print >> output keys = environ.keys() keys.sort() for key in keys: print >> output, '%s: %s' % (key, repr(environ[key])) print >> output output.write(input.read(int(environ.get('CONTENT_LENGTH', '0')))) return [output.getvalue()] In the output of that, the PID value should always be the same. The wsgi.multiprocess flag should be False. The mod_wsgi.process_group value should be what ever you called the daemon process group. And the mod_wsgi.application_group should be an empty string. If this isn't what you are seeing, ensure you actually restarted Apache after making configuration changes. Also add: LogLevel debug to Apache configuration for VirtualHost. Doing that will cause mod_wsgi to log a lot more messages in Apache error log about process creation and script loading, including details of process group and application group things are happening for. For other information on debugging, see: <http://code.google.com/p/modwsgi/wiki/DebuggingTechniques> If still problems, suggest you go to the mod_wsgi mailing list on Google Groups.
Using Regexp to replace math expression inside Latex File Question: I am trying to replace characters inside a math environment with their boldface versions. Unfortunately, these characters occur inside the rest of the text, as well. My text: text text text text Gtext G G text .... \begin{align} f&=gG \\ G &= tG \end{align} text textG text $G$ text. * * * Every G inside \begin{align} \end{align} and between the dollar signs $G$ shall be replaced with \mathbf{G}. The others shall remain untouched. I appreciate every idea :) Thank you BIG EDIT: So far, I have a working Program (Python), thanks to the advice and some other findings in stackoverflow. But the program replaces f.e **_\quad_** to **_\q"replace"ad_**. if I want to replace all the **_"u"_** s with **_"replace"_**. from tempfile import mkstemp from shutil import move from os import remove, close import shutil def replace(file, outputfile, pattern, subst, boundary1, boundary2): #Create temp file fh, abs_path = mkstemp() newfile="tempfile.tmp" new_file = open(newfile,'w') old_file = open(file) inAlign=False for line in old_file: if boundary1 in line: inAlign = True if inAlign: print line print line.replace(pattern, subst) new_file.write(line.replace(pattern, subst)) else: new_file.write(line) if boundary2 in line: inAlign = False; #close temp file new_file.close() close(fh) old_file.close() shutil.move(newfile,outputfile) replace("texfile.tex","texfile_copy.tex","G", "\\mathbf{G}", "\\begin{align}", "\\end{align}") Hopefully I got the formatting right... Answer: This will be hard-to-impossible with regexes alone. What language are you using? It it's perl, there's a module LaTeX::TOM that will help you out a great deal. However, if you know that your `\begin` and `\end` tags are always on their own line, the following pseudocode would work: foreach (line in file) if line.matches( /\\begin{align}/ ) inAlign = true end if inAlign line.replace( /(G)/\\mathbf{$1}/ ) else line.replace( /\$(G)\$/\$\\mathbf{$1}\$/ ) end if line.matches( /\\end{align}/ ) inAlign = false; end end
Multiprocessing debug techniques Question: I'm having trouble debugging a multi-process application (specifically using a process pool in python's multiprocessing module). I have an apparent deadlock and I do not know what is causing it. The stack trace is not sufficient to describe the issue, as it only displays code in the multiprocessing module. Are there any python tools, or otherwise general techniques used to debug deadlocks? Answer: Yah, debugging deadlocks is fun. You can set the logging level to be higher -- see [the Python documentation](http://docs.python.org/library/multiprocessing.html) for a description of it, but really quickly: import multiprocessing, logging logger = multiprocessing.log_to_stderr() logger.setLevel(multiprocessing.SUBDEBUG) Also, add logging for anything in your code that deals with a resource or whatnot that might be in contention. Finally, shot in the dark: spawning off child processes during an import might cause a problem.
How does this Python code work? Question: I don't know if it is feasable to paste all of the code here but I am looking at the code in [this git repo](http://github.com/cloudkick/libcloud/tree/master). If you look at the example they do: ec2 = EC2('access key id', 'secret key') ...but there is no EC2 class. However, it looks like in libcloud\providers.py there is a dict that maps the EC2 to the EC2NodeDriver found in libcloud\drivers\ec2.py. The correct mapping is calculated by get_driver(provider), but that method doesn't appear to be called anywhere. I am new to python, obviously, but not to programming. I'm not even sure what I should be looking up in the docs to figure this out. Thanks. Answer: `example.py` includes an `import` statement that reads: from libcloud.drivers import EC2, Slicehost, Rackspace This means that the `EC2` class is imported from the `libcloud.drivers` module. However, in this case, `libcloud.drivers` is actually a _package_ (a Python _package_ contains _modules_), which means that `EC2` should be defined in a file `__init__.py` in `libcloud/drivers/`, but it's not. Which means that in this specific case, their example code is actually wrong. (I downloaded the code and got an import error when running `example.py`, and as you can see, the file `libcloud/drivers/__init__.py` does not contain any definitions at all, least of all an `EC2` definition.)
Cubic root of the negative number on python Question: Can someone help me to find a solution on how to calculate a cubic root of the negative number using python? >>> math.pow(-3, float(1)/3) nan it does not work. Cubic root of the negative number is negative number. Any solutions? Answer: A simple use of [De Moivre's formula](http://en.wikipedia.org/wiki/De%5FMoivre%27s%5Fformula), is sufficient to show that the cube root of a value, regardless of sign, is a multi-valued function. That means, for any input value, there will be three solutions. Most of the solutions presented to far only return the principle root. A solution that returns all valid roots, and explicitly tests for non- complex special cases, is shown below. import numpy import math def cuberoot( z ): z = complex(z) x = z.real y = z.imag mag = abs(z) arg = math.atan2(y,x) return [ mag**(1./3) * numpy.exp( 1j*(arg+2*n*math.pi)/3 ) for n in range(1,4) ] **Edit:** As requested, in cases where it is inappropriate to have dependency on numpy, the following code does the same thing. def cuberoot( z ): z = complex(z) x = z.real y = z.imag mag = abs(z) arg = math.atan2(y,x) resMag = mag**(1./3) resArg = [ (arg+2*math.pi*n)/3. for n in range(1,4) ] return [ resMag*(math.cos(a) + math.sin(a)*1j) for a in resArg ]
How can I impersonate the current user with IronPython? Question: I am trying to manage an IIS7 installation remotely using the Microsoft.Web.Administration library. I'm doing this in IronPython: import Microsoft.Web.Administration from Microsoft.Web.Administration import ServerManager manager = ServerManager.OpenRemote("RemoteServerName") for site in manager.Sites: print "Site: %(site)s" % { 'site' : site.Name } On the last line as it attempts to communicate with the remote server I get the following error: > Retrieving the COM class factory for remote component with CLSID > {2B72133B-3F5B-4602-8952-803546CE3344} from machine devdealernetsvr failed > due to the following error: 80070005. My research into the error lead me to believe that I do not have the proper credentials against the remote machine and so I would like to impersonate a user that does. I was hard pressed to find a way to do this with IronPython. Any help is much appreciated. Answer: (this doesn't necessarily answer the question but it does fix the problem) It turned out my application worked fine. My setup was the problem. :( To fix my issue I needed to: 1. Log into the remote server. 2. In IIS enable remote management (it's just a check box) 3. In the Services snap-in, start the remote management service and set it to automatic Thanks Anthony!
Python generating Python Question: I have a group of objects which I am creating a class for that I want to store each object as its own text file. I would really like to store it as a Python class definition which subclasses the main class I am creating. So, I did some poking around and found a Python Code Generator on effbot.org. I did some experimenting with it and here's what I came up with: # # a Python code generator backend # # fredrik lundh, march 1998 # # fredrik@pythonware.com # http://www.pythonware.com # # Code taken from http://effbot.org/zone/python-code-generator.htm import sys, string class CodeGeneratorBackend: def begin(self, tab="\t"): self.code = [] self.tab = tab self.level = 0 def end(self): return string.join(self.code, "") def write(self, string): self.code.append(self.tab * self.level + string) def indent(self): self.level = self.level + 1 def dedent(self): if self.level == 0: raise SyntaxError, "internal error in code generator" self.level = self.level - 1 class Point(): """Defines a Point. Has x and y.""" def __init__(self, x, y): self.x = x self.y = y def dump_self(self, filename): self.c = CodeGeneratorBackend() self.c.begin(tab=" ") self.c.write("class {0}{1}Point()\n".format(self.x,self.y)) self.c.indent() self.c.write('"""Defines a Point. Has x and y"""\n') self.c.write('def __init__(self, x={0}, y={1}):\n'.format(self.x, self.y)) self.c.indent() self.c.write('self.x = {0}\n'.format(self.x)) self.c.write('self.y = {0}\n'.format(self.y)) self.c.dedent() self.c.dedent() f = open(filename,'w') f.write(self.c.end()) f.close() if __name__ == "__main__": p = Point(3,4) p.dump_self('demo.py') That feels really ugly, is there a cleaner/better/more pythonic way to do this? Please note, this is not the class I actually intend to do this with, this is a small class I can easily mock up in not too many lines. Also, the subclasses don't need to have the generating function in them, if I need that again, I can just call the code generator from the superclass. Answer: We use Jinja2 to fill in a template. It's much simpler. The template looks a lot like Python code with a few `{{something}}` replacements in it.
How to count possibilities in python lists Question: Given a list like this: num = [1, 2, 3, 4, 5] There are 10 three-element combinations: [123, 124, 125, 134, 135, 145, 234, 235, 245, 345] How can I generate this list? Answer: Use [itertools.combinations](http://docs.python.org/library/itertools.html#itertools.combinations): import itertools num = [1, 2, 3, 4, 5] combinations = [] for combination in itertools.combinations(num, 3): combinations.append(int("".join(str(i) for i in combination))) # => [123, 124, 125, 134, 135, 145, 234, 235, 245, 345] print len(combinations) # => 10 **Edit** You can skip int(), join(), and str() if you are only interested in the number of combinations. itertools.combinations() gives you tuples that may be good enough.
File open: Is this bad Python style? Question: To read contents of a file: data = open(filename, "r").read() The open file immediately stops being referenced anywhere, so the file object will eventually close... and it shouldn't affect other programs using it, since the file is only open for reading, not writing. EDIT: This has actually bitten me in a project I wrote - it prompted me to ask [this](http://stackoverflow.com/questions/2023608/check-what-files-are-open- in-python/2023791#2023791) question. File objects are cleaned up only when you run out of memory, not when you run out of file handles. So if you do this too often, you could end up running out of file descriptors and causing your IO attempts at opening files to throw exceptions. Answer: Just for the record: This is only slightly longer, and closes the file immediately: from __future__ import with_statement with open(filename, "r") as f: data = f.read()
How to extract a string between 2 other strings in python? Question: Like if I have a string like `str1 = "IWantToMasterPython"` If I want to extract `"Py"` from the above string. I write: extractedString = foo("Master","thon") I want to do all this because i am trying to extract lyrics from an html page. The lyrics are written like `<div class = "lyricbox"> ....lyrics goes here....</div>`. Any suggestions on how can I implement. Answer: The solution is to use a regexp: import re r = re.compile('Master(.*?)thon') m = r.search(str1) if m: lyrics = m.group(1)
Code organization in Python: Where is a good place to put obscure methods? Question: I have a class called `Path` for which there are defined about 10 methods, in a dedicated module `Path.py`. Recently I had a need to write 5 more methods for `Path`, however these new methods are quite obscure and technical and 90% of the time they are irrelevant. Where would be a good place to put them so their context is clear? Of course I can just put them with the class definition, but I don't like that because I like to keep the important things separate from the obscure things. Currently I have these methods as functions that are defined in a separate module, just to keep things separate, but it would be better to have them as bound methods. (Currently they take the `Path` instance as an explicit parameter.) Does anyone have a suggestion? Answer: If the method is relevant to the Path - no matter how obscure - I think it should reside within the class itself. If you have multiple places where you have path-related functionality, it leads to problems. For example, if you want to check if some functionality already exists, how will a new programmer know to check the other, less obvious places? I think a good practice might be to order functions by importance. As you may have heard, some suggest putting public members of classes first, and private/protected ones after. You could consider putting the common methods in your class higher than the obscure ones.
Serving file download with python Question: Hey gang, I'm trying to convert a legacy php script over to python and not having much luck. The intent of the script is to serve up a file while concealing it's origin. Here's what's working in php: <?php $filepath = "foo.mp3"; $filesize = filesize($filepath); header("Pragma: no-cache"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); // force download dialog //header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header('Content-Disposition: attachment;filename="'.$filepath.'"'); header("Content-Transfer-Encoding: binary"); #header('Content-Type: audio/mpeg3'); header('Content-Length: '.$filesize); @readfile($filepath); exit(0); ?> When I do the equivilent in Python, I get a download that is zero bytes. Here's what I'm trying: #!/usr/bin/env python # encoding: utf-8 import sys import os import cgitb; cgitb.enable() filepath = "foo.mp3" filesize = os.path.getsize(filepath) print "Prama: no-cache" print "Expires: 0" print "Cache-Control: must-revalidate, post-check=0, pre-check=0" print "Content-Type: application/octet-stream" print "Content-Type: application/download" print 'Content-Disposition: attachment;filename="'+filepath+'"' print "Content-Transfer-Encoding: binary" print 'Content-Length: '+str(filesize) print #required blank line open(filepath,"rb").read() Can anyone please help me? Answer: Well, maybe it's just me missing something, but... You are actually not writing the contents of the file to stdout. You are just reading it into memory, so it will never show up on the other side of the TCP connection... Try: sys.stdout.write(open(filepath,"rb").read()) sys.stdout.flush() Depending on the file size, it might be better to read the file in chunks, like so: chunk_size = 4096 handle = open(filepath, "rb") while True: buffer = handle.read(chunk_size) if buffer: sys.stdout.write(buffer) else: break Another thing to be aware of: writing binary data to stdout may cause Python to choke due to encoding issues. This depends on the Python version you are using.
PIL: Image resizing : Algorithm similar to firefox's Question: I'm getting about the same _bad looking_ resizing from all the 4 algorithms of PIL >>> data = utils.fetch("http://wavestock.com/images/beta-icon.gif") >>> image = Image.open(StringIO.StringIO(data)); image.save("/home/ptarjan/www/tmp/metaward/original.png") >>> >>> image = Image.open(StringIO.StringIO(data)); image.resize((36,36), Image.ANTIALIAS).save("/home/ptarjan/www/tmp/metaward/antialias.png") >>> image = Image.open(StringIO.StringIO(data)); image.resize((36,36), Image.BILINEAR).save("/home/ptarjan/www/tmp/metaward/bilinear.png") >>> image = Image.open(StringIO.StringIO(data)); image.resize((36,36), Image.BICUBIC).save("/home/ptarjan/www/tmp/metaward/bicubic.png") >>> image = Image.open(StringIO.StringIO(data)); image.resize((36,36), Image.NEAREST).save("/home/ptarjan/www/tmp/metaward/nearest.png") >>> >>> image = Image.open(StringIO.StringIO(data)); image.thumbnail((36,36), Image.ANTIALIAS); image.save("/home/ptarjan/www/tmp/metaward/antialias-thumb.png") >>> image = Image.open(StringIO.StringIO(data)); image.thumbnail((36,36), Image.BILINEAR); image.save("/home/ptarjan/www/tmp/metaward/bilinear-thumb.png") >>> image = Image.open(StringIO.StringIO(data)); image.thumbnail((36,36), Image.BICUBIC); image.save("/home/ptarjan/www/tmp/metaward/bicubic-thumb.png") >>> image = Image.open(StringIO.StringIO(data)); image.thumbnail((36,36), Image.NEAREST); image.save("/home/ptarjan/www/tmp/metaward/nearest-thumb.png") >>> >>> image = Image.open(StringIO.StringIO(data)); image.convert("RGB").resize((36,36), Image.ANTIALIAS).save("/home/ptarjan/www/tmp/metaward/antialias-rgb.png") >>> image = Image.open(StringIO.StringIO(data)); image.convert("RGB").resize((36,36), Image.BILINEAR).save("/home/ptarjan/www/tmp/metaward/bilinear-rgb.png") >>> image = Image.open(StringIO.StringIO(data)); image.convert("RGB").resize((36,36), Image.BICUBIC).save("/home/ptarjan/www/tmp/metaward/bicubic-rgb.png") >>> image = Image.open(StringIO.StringIO(data)); image.convert("RGB").resize((36,36), Image.NEAREST).save("/home/ptarjan/www/tmp/metaward/nearest-rgb.png") But the results look much worse that just resizing in firefox. <http://paulisageek.com/tmp/metaward/images.html> How can I get a similar effect to the firefox result using PIL (or another python image library)? **EDIT** : Hover your mouse to see what each image is ![](http://paulisageek.com/tmp/metaward/original.png) ![](http://paulisageek.com/tmp/metaward/antialias.png) ![](http://paulisageek.com/tmp/metaward/bicubic.png) ![](http://paulisageek.com/tmp/metaward/bilinear.png) ![](http://paulisageek.com/tmp/metaward/nearest.png) ![](http://paulisageek.com/tmp/metaward/antialias-thumb.png) ![](http://paulisageek.com/tmp/metaward/bicubic-thumb.png) ![](http://paulisageek.com/tmp/metaward/bilinear-thumb.png) ![](http://paulisageek.com/tmp/metaward/nearest-thumb.png) ![](http://paulisageek.com/tmp/metaward/antialias-rgb.png) ![](http://paulisageek.com/tmp/metaward/bicubic-rgb.png) ![](http://paulisageek.com/tmp/metaward/bilinear-rgb.png) ![](http://paulisageek.com/tmp/metaward/nearest-rgb.png) It looks like the RGB and then ANTIALIS looks the best. Any other recommendations? For reference, this is the one that looked the best : >>> image = Image.open(StringIO.StringIO(data)); >>> image.convert("RGB").resize((36,36), Image.ANTIALIAS) Answer: I resized the "original" with Python and found the same results as you did. I also resized the "original" with GIMP and I got the same (if not inferior) quality. This made me suspect that Firefox cheats. Possibly it converts to RGB ("original" mode is indexed color). Thus the following code: import Image im=Image.open("beta-icon.gif") im = im.convert("RGB") im=im.resize((36,36), Image.ANTIALIAS) im.save("q5.png") The result is almost as good as that of Firefox.
Python: Automatically initialize instance variables? Question: I have a python class that looks like this: class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): followed by: self.PID=PID self.PPID=PPID self.cmd=cmd ... Is there any way to autoinitialize these instance variables, like C++'s initialization list? It would spare lots of redundant code. Answer: **Edit: extended the solution to honor default arguments also** Here is the complete solution: from functools import wraps import inspect def initializer(func): """ Automatically assigns the parameters. >>> class process: ... @initializer ... def __init__(self, cmd, reachable=False, user='root'): ... pass >>> p = process('halt', True) >>> p.cmd, p.reachable, p.user ('halt', True, 'root') """ names, varargs, keywords, defaults = inspect.getargspec(func) @wraps(func) def wrapper(self, *args, **kargs): for name, arg in list(zip(names[1:], args)) + list(kargs.items()): setattr(self, name, arg) for name, default in zip(reversed(names), reversed(defaults)): if not hasattr(self, name): setattr(self, name, default) func(self, *args, **kargs) return wrapper * * * **Edit: Adam asked me to extend the solution to support keyword arguments** from functools import wraps import inspect def initializer(fun): names, varargs, keywords, defaults = inspect.getargspec(fun) @wraps(fun) def wrapper(self, *args, **kargs): for name, arg in zip(names[1:], args) + kargs.items(): setattr(self, name, arg) fun(self, *args, **kargs) return wrapper * * * You can use a decorator: from functools import wraps import inspect def initializer(fun): names, varargs, keywords, defaults = inspect.getargspec(fun) @wraps(fun) def wrapper(self, *args): for name, arg in zip(names[1:], args): setattr(self, name, arg) fun(self, *args) return wrapper class process: @initializer def __init__(self, PID, PPID, cmd, FDs, reachable, user): pass Output: >>> c = process(1, 2, 3, 4, 5, 6) >>> c.PID 1 >>> dir(c) ['FDs', 'PID', 'PPID', '__doc__', '__init__', '__module__', 'cmd', 'reachable', 'user'
Application Structure for GUI & Functions Question: I'm starting a basic application using Python and PyQt and could use some experienced insight. Here's the structure I was thinking. This is understandably subjective, but is there a better way? myApp/GUI/__init__.py mainWindow.py subWindow1.py subWindow2.py myApp/Logic/__init__.py setOfMethods1.py setOfMethods2.py mainWindow imports subWindows mainWindow imports Logic module Answer: ## MVC It looks like you have been reading about model-view-controller. Separating the UI from the back end is a good idea. It will make runnings tests and debugging just the logic side easier, and the internal structure will be more modular. I'm not certain it makes as much sense to split the UI into the currently anticipated windows, though. I might just let the UI part grow and factor for common code.
apt like column output - python library Question: Debian's apt tool outputs results in uniform width columns. For instance, try running "aptitude search svn" .. and all names appear in the first column of the same width. Now if you resize the terminal, the column width is adjusted accordingly. Is there a Python library that enables one to do this? Note that the library has to be aware of the terminal width and take a table as input - which could be, for instance, `[('rapidsvn', 'A GUI client for subversion'), ...]` .. and you may also specify a max-width for the first column (or any column). Also note how the string in the second column below is trimmed if exceeds the terminal width .. thus not introducing the undesired second line. $ aptitude search svn [...] p python-svn-dbg - A(nother) Python interface to Subversion (d v python2.5-svn - v python2.6-svn - p rapidsvn - A GUI client for subversion p statsvn - SVN repository statistics p svn-arch-mirror - one-way mirroring from Subversion to Arch r p svn-autoreleasedeb - Automatically release/upload debian package p svn-buildpackage - helper programs to maintain Debian packages p svn-load - An enhanced import facility for Subversion p svn-workbench - A Workbench for Subversion p svnmailer - extensible Subversion commit notification t p websvn - interface for subversion repositories writt $ **EDIT** : (in response to Alex's answer below) ... the output will be similar to 'aptitude search' in that 1) only the last column (which is the only column with the longest string in a row) is to be trimmed, 2) there are typically 2-4 columns only, but the last column ("description") is expected to take at least half the terminal width. 3) all rows contain equal number of columns, 4) all entries are strings only Answer: **Update** : The `colprint` routine is now available in the [applib](http://code.activestate.com/pypm/applib/) Python library [hosted in GitHub](https://github.com/ActiveState/applib/blob/master/applib/textui.py#L213). Here's the complete program for those of you interested: # This function was written by Alex Martelli # http://stackoverflow.com/questions/1396820/ def colprint(table, totwidth=None): """Print the table in terminal taking care of wrapping/alignment - `table`: A table of strings. Elements must not be `None` - `totwidth`: If None, console width is used """ if not table: return if totwidth is None: totwidth = find_console_width() totwidth -= 1 # for not printing an extra empty line on windows numcols = max(len(row) for row in table) # ensure all rows have >= numcols columns, maybe empty padded = [row+numcols*('',) for row in table] # compute col widths, including separating space (except for last one) widths = [ 1 + max(len(x) for x in column) for column in zip(*padded)] widths[-1] -= 1 # drop or truncate columns from the right in order to fit while sum(widths) > totwidth: mustlose = sum(widths) - totwidth if widths[-1] <= mustlose: del widths[-1] else: widths[-1] -= mustlose break # and finally, the output phase! for row in padded: print(''.join([u'%*s' % (-w, i[:w]) for w, i in zip(widths, row)])) def find_console_width(): if sys.platform.startswith('win'): return _find_windows_console_width() else: return _find_unix_console_width() def _find_unix_console_width(): """Return the width of the Unix terminal If `stdout` is not a real terminal, return the default value (80) """ import termios, fcntl, struct, sys # fcntl.ioctl will fail if stdout is not a tty if not sys.stdout.isatty(): return 80 s = struct.pack("HHHH", 0, 0, 0, 0) fd_stdout = sys.stdout.fileno() size = fcntl.ioctl(fd_stdout, termios.TIOCGWINSZ, s) height, width = struct.unpack("HHHH", size)[:2] return width def _find_windows_console_width(): """Return the width of the Windows console If the width cannot be determined, return the default value (80) """ # http://code.activestate.com/recipes/440694/ from ctypes import windll, create_string_buffer STDIN, STDOUT, STDERR = -10, -11, -12 h = windll.kernel32.GetStdHandle(STDERR) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if res: import struct (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) sizex = right - left + 1 sizey = bottom - top + 1 else: sizex, sizey = 80, 25 return sizex
Downloading file using IE from python Question: I'm trying to download file with Python using IE: from win32com.client import DispatchWithEvents class EventHandler(object): def OnDownloadBegin(self): pass ie = DispatchWithEvents("InternetExplorer.Application", EventHandler) ie.Visible = 0 ie.Navigate('http://website/file.xml') After this, I'm getting a window asking the user where to save the file. How can I save this file automatically from python? I need to **use some browser** , not urllib or mechanize, because **before downloading file I need to interact with some ajax functionality**. Answer: This works for me as long as the IE dialogs are in the foreground and the downloaded file does not already exist in the "Save As" directory: import time import threading import win32ui, win32gui, win32com, pythoncom, win32con from win32com.client import Dispatch class IeThread(threading.Thread): def run(self): pythoncom.CoInitialize() ie = Dispatch("InternetExplorer.Application") ie.Visible = 0 ie.Navigate('http://website/file.xml') def PushButton(handle, label): if win32gui.GetWindowText(handle) == label: win32gui.SendMessage(handle, win32con.BM_CLICK, None, None) return True IeThread().start() time.sleep(3) # wait until IE is started wnd = win32ui.GetForegroundWindow() if wnd.GetWindowText() == "File Download - Security Warning": win32gui.EnumChildWindows(wnd.GetSafeHwnd(), PushButton, "&Save"); time.sleep(1) wnd = win32ui.GetForegroundWindow() if wnd.GetWindowText() == "Save As": win32gui.EnumChildWindows(wnd.GetSafeHwnd(), PushButton, "&Save");
Python: copy.deepcopy produces an error Question: I have been using this copy method for quite a while, in lots of classes that needed it. class population (list): def __init__ (self): pass def copy(self): return copy.deepcopy(self) It has suddenly started producing this error: File "C:\Python26\lib\copy.py", line 338, in _reconstruct state = deepcopy(state, memo) File "C:\Python26\lib\copy.py", line 162, in deepcopy y = copier(x, memo) File "C:\Python26\lib\copy.py", line 255, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "C:\Python26\lib\copy.py", line 189, in deepcopy y = _reconstruct(x, rv, 1, memo) File "C:\Python26\lib\copy.py", line 323, in _reconstruct y = callable(*args) File "C:\Python26\lib\copy_reg.py", line 93, in __newobj__ return cls.__new__(cls, *args) TypeError: object.__new__(generator) is not safe, use generator.__new__() >>> the lines which include the references to lines 338, 162, 255, 189 were repeated quite a few times before the 'line 338' that I copied here. Answer: Are you cloning a generator? [Generators can't be cloned.](https://mail.python.org/pipermail/python-list/2009-March/539759.html) Copying answer by Gabriel Genellina here: * * * There is no way of "cloning" a generator: py> g = (i for i in [1,2,3]) py> type(g)() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot create 'generator' instances py> g.gi_code = code Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: readonly attribute py> import copy py> copy.copy(g) Traceback (most recent call last): ... TypeError: object.__new__(generator) is not safe, use generator.__new__() py> type(g).__new__ <built-in method __new__ of type object at 0x1E1CA560> You can do that with a generator function because it acts as a "generator factory", building a new generator when called. Even using the Python C API, to create a generator one needs a frame object -- and there is no way to create a frame object "on the fly" that I know of :( py> import ctypes py> PyGen_New = ctypes.pythonapi.PyGen_New py> PyGen_New.argtypes = [ctypes.py_object] py> PyGen_New.restype = ctypes.py_object py> g = (i for i in [1,2,3]) py> g2 = PyGen_New(g.gi_frame) py> g2.gi_code is g.gi_code True py> g2.gi_frame is g.gi_frame True py> g.next() 1 py> g2.next() 2 g and g2 share the same execution frame, so they're not independent. There is no easy way to create a new frame in Python: py> type(g.gi_frame)() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot create 'frame' instances One could try using PyFrame_New -- but that's way too magic for my taste...
Python decorate a class to change parent object type Question: Suppose you have two classes X & Y. You want to decorate those classes by adding attributes to the class to produce new classes X1 and Y1. For example: class X1(X): new_attribute = 'something' class Y1(Y): new_attribute = 'something' *new_attribute* will always be the same for both X1 and Y1. X & Y are not related in any meaningful way, except that multiple inheritance is not possible. There are a set of other attributes as well, but this is degenerate to illustrate. I feel like I'm overcomplicating this, but I had thought to use a decorator, somewhat likeso: def _xywrap(cls): class _xy(cls): new_attribute = 'something' return _xy @_xywrap(X) class X1(): pass @_xywrap(Y) class Y1(): pass It feels like I'm missing a fairly common pattern, and I'd be much obliged for thoughts, input and feedback. Thank you for reading. Brian **EDIT:** Example: Here is a relevant extract that may illuminate. The common classes are as follows: from google.appengine.ext import db # I'm including PermittedUserProperty because it may have pertinent side-effects # (albeit unlikely), which is documented here: [How can you limit access to a # GAE instance to the current user][1]. class _AccessBase: users_permitted = PermittedUserProperty() owner = db.ReferenceProperty(User) class AccessModel(db.Model, _AccessBase): pass class AccessExpando(db.Expando, _AccessBase): pass # the order of _AccessBase/db.* doesn't seem to resolve the issue class AccessPolyModel(_AccessBase, polymodel.PolyModel): pass Here's a sub-document: class Thing(AccessExpando): it = db.StringProperty() Sometimes Thing will have the following properties: Thing { it: ... } And other times: Thing { it: ..., users_permitted:..., owner:... } I've been unable to figure out why Thing would sometimes have its _AccessParent properties, and other times not. Answer: Use 3-arguments [type](http://docs.python.org/library/functions.html?#type): def makeSomeNicelyDecoratedSubclass(someclass): return type('MyNiceName', (someclass,), {'new_attribute':'something'}) This is indeed, as you surmised, a reasonably popular idiom. **Edit** : in the general case if someclass has a custom metaclass you may need to extract and use it (with a 1-argument `type`) in lieu of `type` itself, to preserve it (this may be the case for your Django and App Engine models): def makeSomeNicelyDecoratedSubclass(someclass): mcl = type(someclass) return mcl('MyNiceName', (someclass,), {'new_attribute':'something'}) This also works where the simpler version above does (since in simple cases w/no custom metaclasses `type(someclass) is type`).
Showing an image from console in Python Question: What is the easiest way to show a `.jpg` or `.gif` image from Python console? I've got a Python console program that is checking a data set which contains links to images stored locally. How should I write the script so that it would display images pop-up graphical windows? Answer: Using the awesome [Pillow](https://pypi.python.org/pypi/Pillow/2.7.0) library: >>> from PIL import Image >>> img = Image.open('test.png') >>> img.show() This will open the image in your default image viewer.
To Ruby or not to Ruby Question: I know that this is a difficult question to answer, but I thought I would try anwyays.... I am just starting at a new company where they have a minimal existing code base. It probably has a month of man effort invested at this point. It is currently written in Ruby. It is also currently using Ruby on Rails -- but mostly just for the sake of testing out the Ruby code. The ultimate goal of the code is actually to drive a backend to a site that will be written in php (could be a backend to Drupal, Echo, etc...). I have no experience with Ruby, so I would tend to want to go with a language I know better (like Python), but am not willing to rule Ruby out for no reason. If you are not going to use Ruby for a Rails project, is it still worth it? Will I be better off going with Python or some other language? How do the libraries stack up? Thanks!!! Answer: My advice would depend on your own goals, which might look like this... you might want to ask yourself (or score each of these from 1-10) if you prefer to: 1. learn a new language you might use in future? = Ruby 2. deepen your Python skills by using it for everything (say [Django](http://www.djangoproject.com/) or [Web.Py](http://webpy.org/)) = Python 3. move the [Ruby testing away from Rails](http://ruby-toolbox.com/categories/testing%5Fframeworks.html) = Ruby Other questions you could ask yourself to help the decision might be: 1. is speed important? Do some tests in the various languages. (If Ruby, then use [Ruby 1.9](http://rads.stackoverflow.com/amzn/click/0596516177) and get [the other Ruby book](http://rads.stackoverflow.com/amzn/click/0672328844)). 2. is integration important? If so, why use a PHP front end? 3. is your connection to the language community important? If so, choose on 'community feel'. 4. is there a lot of backend text processing? (Perl?) 5. do you want to use an ORM or write SQL? = look at Ruby and Python [lightweight frameworks](http://www.linux-mag.com/id/7324). I don't think the libraries will be an issue, since (I'm pretty sure that) libraries for popular languages cover all common tasks. If you can score all the above from 1-10 it may help isolate a preferred direction... Then, as I see it, the issue breaks down into 3 things: 1. what language do you most like to code in (work should be enjoyable)? 2. can the front end and back end be generated in a single language? 3. do you want to use a framework or a ready-made CMS for the front end? It's worth looking at the origins of languages: [PHP was originally announced](http://groups.google.ch/group/comp.infosystems.www.authoring.cgi/msg/cc7d43454d64d133?oe=UTF-8&output=gplain) as an extension of [SSI](http://vr-zone.com/manual/en/howto/ssi.html), Ruby tries to take the best of Perl, Smalltalk and Lisp but has elements of a C/Java-like syntax, Perl is intimately connected to Unix and everywhere, although usually invisible to end users (despite some [very good Perl web frameworks](http://mark.stosberg.com/blog/2008/12/titanium-a-new-release-and- more.html)). You already know about Python. As for frameworks and CMSs, a trawl through the distinctions/limitations/features might also help. It is too easy to install a PHP CMS (fine for a site with a well-defined purpose) but then find yourself hampered in acres of impenetrable code when you want do do something it can't do out of the box. A framework in the backend language will enable you to hook the back and front ends together more easily.
How to extract and then refer to variables defined in a python module? Question: I'm trying to build a simple environment check script for my firm's test environment. My goal is to be able to ping each of the hosts defined for a given test environment instance. The hosts are defined in a file like this: #!/usr/bin/env python host_ip = '192.168.100.10' router_ip = '192.168.100.254' fs_ip = '192.168.200.10' How can I obtain all of these values in a way that is iterable (i.e. I need to loop through and ping each ip address)? I've looked at local() and vars(), but trying do something like this: for key, value in vars(): print key, value generates this error: ValueError: too many values to unpack I have been able to extract the names of all variables by checking `dir(local_variables)` for values that don't contain a '__' string, but then I have a list of strings, and I can't figure out how to get from the string to the value of the same-named variable. Answer: First off, I strongly recommend not doing it that way. Instead, do: hosts = { "host_ip": '192.168.100.10', "router_ip": '192.168.100.254', "fs_ip": '192.168.200.10', } Then you can simply import the module and reference it normally--this gives an ordinary, standard way to access this data from any Python code: import config for host, ip in config.hosts.iteritems(): ... If you do access variables directly, you're going to get a bunch of stuff you don't want: the builtins (`__builtins__`, `__package__`, etc); anything that was imported while setting up the other variables, etc. You'll also want to make sure that the context you're running in is different from the one whose variables you're iterating over, or you'll be creating new variables in locals() (or vars(), or globals()) while you're iterating over it, and you'll get `"RuntimeError: dictionary changed size during iteration"`.
Just installed QtOpenGL but cannot import it (from Python) Question: I just installed it with apt-get on debian linux with apt-get install libqt4-opengl the rest of PyQt4 is available, but I cant get to this new module. from PyQt4 import QtOpenGL raises ImportError. any idea what to do? Answer: Did you forget to install the Python bindings? apt-get install python-qt4-gl
Accessing a Python variable in a list Question: I think this is probably something really simple, but I'd appreciate a hint: I am using a python list to hold some some database insert statements: list = [ "table_to_insert_to" ],["column1","column2"],[getValue.value1],["value2"]] The problem is one of the values isn't evaluated until runtime-- so before the page even gets run, it breaks when it tries to import the function. How do you handle this? Answer: You've just pointed out one (out of a zillion) problems with global variables: not using global variables is the best solution to this problem and many others. If you still mistakenly believe you must use a global variable, put a placeholder (e.g. `None`) in the place where the value you don't yet know will go, and assign the right value there when it's finally known.
How to install MySQLdb package? (ImportError: No module named setuptools) Question: I am trying to install MySQLdb package. I found the source code [here](https://sourceforge.net/projects/mysql-python/files/). I did the following: gunzip MySQL-python-1.2.3c1.tar.gz tar xvf MySQL-python-1.2.3c1.tar cd MySQL-python-1.2.3c1 python setup.py build As the result I got the following: Traceback (most recent call last): File "setup.py", line 5, in ? from setuptools import setup, Extension ImportError: No module named setuptools Does anybody knows how to solve this problem? By the way, if I am able to do the described step, I will need to do the following: sudo python setup.py install And I have no system-administrator-rights. Do I still have a chance to install MySQLdb? Thank you. Answer: After trying many suggestions, simply using `sudo apt-get install python- mysqldb` worked for me. More info: [Getting "Error loading MySQLdb module: No module named MySQLdb" \- have tried previously posted solutions](http://stackoverflow.com/questions/2952187/getting-error-loading- mysqldb-module-no-module-named-mysqldb-have-tried-pre)
How to set ignorecase flag for part of regular expression in Python? Question: Is it possible to implement in Python something like this simple one: #!/usr/bin/perl my $a = 'Use HELLO1 code'; if($a =~ /(?i:use)\s+([A-Z0-9]+)\s+(?i:code)/){ print "$1\n"; } Letters of token in the middle of string are always capital. Letters of the rest of words can have any case (USE, use, Use, CODE, code, Code and so on) Answer: As far as I could find, the python regular expression engine does not support partial ignore-case. Here is a solution using a case-insensitive regular expression, which then tests if the token is uppercase afterward. #! /usr/bin/env python import re token_re = re.compile(r'use\s+([a-z0-9]+)\s+code', re.IGNORECASE) def find_token(s): m = token_re.search(s) if m is not None: token = m.group(1) if token.isupper(): return token if __name__ == '__main__': for s in ['Use HELLO1 code', 'USE hello1 CODE', 'this does not match', ]: print s, '->', print find_token(s) Here is the program's output: Use HELLO1 code -> HELLO1 USE hello1 CODE -> None this does not match -> None
Python Eval: What's wrong with this code? Question: I'm trying to write a very simple Python utility for personal use that counts the number of lines in a text file for which a predicate specified at the command line is true. Here's the code: import sys pred = sys.argv[2] if sys.argv[1] == "stdin" : handle = sys.stdin else : handle = open(sys.argv[1]) result = 0 for line in handle : eval('result += 1 if ' + pred + ' else 0') print result When I run it using `python count.py myFile.txt "int(line) == 0"`, I get the following error: File "c:/pycode/count.py", line 10, in <module> eval('toAdd = 1 if ' + pred + ' else 0') File "<string>", line 1 toAdd = 1 if int(line) == 0 else 0 This looks like perfectly valid Python code to me (though I've never used Python's eval before, so I don't know what its quirks, if any, are). Please tell me how I can fix this to make it work. Answer: Try using exec instead of eval. The difference between the 2 is explained [here](http://www.ibiblio.org/g2swap/byteofpython/read/exec-statement.html)
Can Python encode a string to match ASP.NET membership provider's EncodePassword Question: I'm working on a Python script to create hashed strings from an existing system similar to that of ASP.NET's MembershipProvider. Using Python, is there a way to take a hexadecimal string and convert it back to a binary and then do a base64 encoding, somehow treating the original string as Unicode. Let's try some code. I'm looking to re-encode a hashed password so that the hashes would be equal in Python and ASP.NET/C#: import base64 import sha import binascii def EncodePassword(password): # strings are currently stored as hex hex_hashed_password = sha.sha(password).hexdigest() # attempt to convert hex to base64 bin_hashed_password = binascii.unhexlify(hex_hashed_password) return base64.standard_b64encode(bin_hashed_password) print EncodePassword("password") # W6ph5Mm5Pz8GgiULbPgzG37mj9g= The ASP.NET MembershipProvider users this method to encode: static string EncodePassword(string pass) { byte[] bytes = Encoding.Unicode.GetBytes(pass); //bytes = Encoding.ASCII.GetBytes(pass); byte[] inArray = null; HashAlgorithm algorithm = HashAlgorithm.Create("SHA1"); inArray = algorithm.ComputeHash(bytes); return Convert.ToBase64String(inArray); } string s = EncodePassword("password"); // 6Pl/upEE0epQR5SObftn+s2fW3M= That doesn't match. But, when I run it with the password encoded with ASCII encoding, it matches, so the Unicode part of the .NET method is what's the difference. > W6ph5Mm5Pz8GgiULbPgzG37mj9g= Is there a way in the python script to get an output to match the default .NET version? Answer: This is the trick: > Encoding.Unicode “Unicode” encoding is confusing Microsoft-speak for UTF-16LE (specifically, without any BOM). Encode the string to that before hashing and you get the right answer: >>> import hashlib >>> p= u'password' >>> hashlib.sha1(p.encode('utf-16le')).digest().encode('base64') '6Pl/upEE0epQR5SObftn+s2fW3M=\n'
Python serializable objects json Question: class gpagelet: """ Holds 1) the pagelet xpath, which is a string 2) the list of pagelet shingles, list """ def __init__(self, parent): if not isinstance( parent, gwebpage): raise Exception("Parent must be an instance of gwebpage") self.parent = parent # This must be a gwebpage instance self.xpath = None # String self.visibleShingles = [] # list of tuples self.invisibleShingles = [] # list of tuples self.urls = [] # list of string class gwebpage: """ Holds all the datastructure after the results have been parsed holds: 1) lists of gpagelets 2) loc, string, location of the file that represents it """ def __init__(self, url): self.url = url # Str self.netloc = False # Str self.gpagelets = [] # gpagelets instance self.page_key = "" # str Is there a way for me to make my class json serializable? The thing that I am worried is the recursive reference. Answer: Write your own encoder and decoder, which can be very simple like `return __dict__` e.g. here is a encoder to dump totally recursive tree structure, you can enhance it or use as it is for your own purpose import json class Tree(object): def __init__(self, name, childTrees=None): self.name = name if childTrees is None: childTrees = [] self.childTrees = childTrees class MyEncoder(json.JSONEncoder): def default(self, obj): if not isinstance(obj, Tree): return super(MyEncoder, self).default(obj) return obj.__dict__ c1 = Tree("c1") c2 = Tree("c2") t = Tree("t",[c1,c2]) print json.dumps(t, cls=MyEncoder) it prints {"childTrees": [{"childTrees": [], "name": "c1"}, {"childTrees": [], "name": "c2"}], "name": "t"} you can similarly write a decoder but there you will somehow need to identify is it is your object or not, so may be you can put a type too if needed.
How can I protect myself from a zip bomb? Question: I just read about [zip bombs](http://en.wikipedia.org/wiki/Zip%5Fbomb), i.e. zip files that contain very large amount of highly compressible data (00000000000000000...). When opened they fill the server's disk. How can I detect a zip file is a zip bomb **before** unzipping it? **UPDATE** Can you tell me how is this done in Python or Java? Answer: Try this in Python: import zipfile z = zipfile.ZipFile('c:/a_zip_file') print 'total files size=', sum(e.file_size for e in z.infolist()) z.close()
How do I get this program to start over in python? Question: I believe the word is "recurse" instead of 'start over.' I've created this program to hone my multiplication skills in the morning. I can get it to give me a multiplication problem, but how do I get it to ask me another one? from random import randint print 'Good Morning Pete!' X = randint(0, 10) Y = randint(0, 10) A = X * Y Z = int(raw_input('%i * %i = ? ' % (X, Y))) count = 0 if Z == A: count += 1 print 'Good Job!' else: print 'Sorry!' if count == '10': print 'Time to kill \'em' how do I get it to spit out a new problem for me to solve? I'm a beginner. Thanks all! Answer: Pete, you wouldn't need _recursion_ in this case, but merely a _loop_. I suggest you put the bulk of the logic of this program (the part that asks the multiplcation problem and check your answer), into a function. Say One Problem(). This function could return 0 if you answered wrong, 1 if you answered correctly and -1 if you entered some key indicating that you want to stop. (BTW, this function is introduced to help you structure the program, make it more readeable but it is not needed for introducing a loop. you could well keep all this stuff inside the loop. Also, you should know that there are other loop constructs in python, for exampe while loops.) Then you'd just need in your main section something like that : GoodReplyCtr = 0 for i in range(0, 10): # or 100 or 1000 if you feel ambitious... cc = OneProblem() if cc < 0: break GoodReplyCtr += cc print(GoodReplyCtr) The concept of recursion (again not needed here), is when a function calls itself. This is a common practice when navigating graphs (like say the directory structure on you drive C:), or with some mathematical problems. We typically do not need to cover recursion early in the learning of computer languages concepts, but once you have a good mastery of things, you may find it quite useful (and challenging at time ;-) ) Keep at it! Math and python are cool. **Edit** : One last trick: You may find that you need to work on some multiplication tables more than other. Rather than using randint you can use the random's module random.choice() method to favor some numbers or to eliminate others. for example import random X = random.choice((2, 3, 4, 6, 7, 8, 9, 7, 9)) # see, no 0, 1,or 5 but more chance to get 7 or 9
multiline checkbox in wxpython Question: I'm working with wxpython (2.8) with python 2.5. is it possible to force a wx.CheckBox to display its label on multiple lines? I'd like to be able to do the same as wx.StaticText.Wrap(width) See the attached example: the wx.CheckBox is 200 px wide, but it's label does not fit in this space. Any help is really appreciated! Thanks a lot Mauro #example starts here import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Hello World", size= (300,200)) self.panel = wx.Panel(self, -1) myVSizer = wx.BoxSizer(wx.VERTICAL) #instantiating a checkbox 200 px wide. but the label is too long cb = wx.CheckBox(self.panel, -1, label="This is a very very long label for 200 pixel wide cb!", size =wx.Size(200, -1)) myVSizer.Add( cb, 1) self.panel.SetSizer(myVSizer) myVSizer.Layout() app = wx.App(redirect=True) top = MyFrame() top.Show() app.MainLoop() Answer: what about something like this? Flex! (I've made it a radio button to show that it still behaves like one) import wx import textwrap class MultilineRadioButton(wx.RadioButton): def __init__(self, parent, id=-1, label=wx.EmptyString, wrap=10, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, validator=wx.DefaultValidator, name=wx.RadioButtonNameStr): wx.RadioButton.__init__(self,parent,id,'',pos,size,style,validator,name) self._label = label self._wrap = wrap lines = self._label.split('\n') self._wrappedLabel = [] for line in lines: self._wrappedLabel.extend(textwrap.wrap(line,self._wrap)) self._textHOffset = 20 dc = wx.ClientDC(self) font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) dc.SetFont(font) maxWidth = 0 totalHeight = 0 lineHeight = 0 for line in self._wrappedLabel: width, height = dc.GetTextExtent(line) maxWidth = max(maxWidth,width) lineHeight = height totalHeight += lineHeight self._textHeight = totalHeight self.SetInitialSize(wx.Size(self._textHOffset + maxWidth,totalHeight)) self.Bind(wx.EVT_PAINT, self.OnPaint) def OnPaint(self, event): dc = wx.PaintDC(self) self.Draw(dc) self.RefreshRect(wx.Rect(0,0,self._textHOffset,self.GetSize().height)) event.Skip() def Draw(self, dc): dc.Clear() font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) dc.SetFont(font) height = self.GetSize().height if height > self._textHeight: offset = height / 2 - self._textHeight / 2 else: offset = 0 for line in self._wrappedLabel: width, height = dc.GetTextExtent(line) dc.DrawText(line,self._textHOffset,offset) offset += height class HFrame(wx.Frame): def __init__(self,pos=wx.DefaultPosition): wx.Frame.__init__(self,None,title="Hello World",size=wx.Size(600,400),pos=pos) self.panel = wx.Panel(self,-1) sizer = wx.BoxSizer(wx.HORIZONTAL) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) self.panel.SetSizer(sizer) sizer.Layout() class VFrame(wx.Frame): def __init__(self,pos=wx.DefaultPosition): wx.Frame.__init__(self,None,title="Hello World",size=wx.Size(600,400),pos=pos) self.panel = wx.Panel(self,-1) sizer = wx.BoxSizer(wx.VERTICAL) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10) sizer.Add(cb,1) self.panel.SetSizer(sizer) sizer.Layout() app = wx.App(redirect=False) htop = HFrame(pos=wx.Point(0,50)) htop.Show() vtop = VFrame(pos=wx.Point(650,50)) vtop.Show() app.MainLoop()
Python CreateFile Cannot Find PhysicalMemory Question: I am trying to access the Physical Memory of a Windows 2000 system (trying to do this without a memory dumping tool). My understanding is that I need to do this using the CreateFile function to create a handle. I have used an older version of [win32dd](http://www.msuiche.net/2008/06/14/capture-memory-under- win2k3-or-vista-with-win32dd/) to help me through this. Other documentation on the web points me to using either "\Device\PhysicalMemory" or "\\\\.\PhysicalMemory". Unfortunately, I get the same error for each. Traceback (most recent call last): File "testHandles.py", line 101, in (module) File "testHandles.py", line 72, in createFileHandle pywintypes.error: (3, 'CreateFile', 'The system cannot find the path specified.') Actually, the error number returned is different for each run \\\\.\PhysicalMemory == 3 and \Device\PhysicalMemory == 2. Review of pywin32, win32file, createfile, pyhandle, and pywintypes did not produce information as to the different return values. Here is my code. I am using py2exe to get this working on Windows 2000 (and yes it compiles successfully). I realize that I might also have a problem with DeviceIoControl but right now I am concentrating on CreateFile. # testHandles.py import ctypes import socket import struct import sys import win32file import pywintypes def createFileHandle(): outLoc = pywintypes.Unicode("C:\\Documents and Settings\\Administrator\\My Documents\\pymemdump_dotPM.dd") handleLoc = pywintypes.Unicode("\\\\.\\PhysicalMemory") #handleLoc = pywintypes.Unicode("\\Device\\PhysicalMemory") placeHolder = 0 BytesReturned = 0 # Device = CreateFile(L"\\\\.\\win32dd", GENERIC_ALL, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); # CreateFile(fileName, desiredAccess , shareMode , attributes , creationDisposition , flagsAndAttributes , hTemplateFile ) #hMemHandle = win32file.CreateFile(handleLoc, GENERIC_ALL, SHARE_READ, None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, None) hMemHandle = win32file.CreateFile(handleLoc, win32file.GENERIC_READ, win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None) print "hMemHandle: %s" % hMemHandle if (hMemHandle == NO_ERROR): print "Could not build hMemHandle" sys.exit() # We send destination path to the driver. #if (!DeviceIoControl(hMemHandle, 0x19880922, outLoc, (ULONG)(wcslen(outLoc) + 1) * sizeof(TCHAR), NULL, 0, &BytesReturned, NULL)) if (ctypes.windll.Kernel32.DeviceIoControl(hMemHandle, 0x19880922, outLoc, 5, NULL, 0, BytesReturned, NULL)): print "Error: DeviceIoControl(), Cannot send IOCTL.\n" else: print "[win32dd] Physical memory dumped. You can now check %s.\n" % outLoc # Dump memory createFileHandle() Thank you, Cutaway Answer: I don't believe it's possible to access the physical memory object from user mode land in Windows. As your [win32dd link](http://www.msuiche.net/2008/06/14/capture-memory-under-win2k3-or-vista- with-win32dd/) suggests, you will need to do it from kernel mode.
Why can't I import the 'math' library when embedding python in c? Question: I'm using the example in python's 2.6 docs to begin a foray into embedding some python in C. The [example C-code](http://docs.python.org/extending/embedding.html#pure-embedding) does not allow me to execute the following 1 line script: import math Using line: ./tmp.exe tmp foo bar it complains Traceback (most recent call last): File "/home/rbroger1/scripts/tmp.py", line 1, in <module> import math ImportError: [...]/python/2.6.2/lib/python2.6/lib-dynload/math.so: undefined symbol: PyInt_FromLong When I do `nm` on my generated binary (tmp.exe) it shows 0000000000420d30 T PyInt_FromLong The function seems to be defined, so why can't the shared object find the function? Answer: I'm using Python 2.6, and I successfully compiled and ran that same example code that you listed, without changing anything in the source. $ gcc python.c -I/usr/include/python2.6/ /usr/lib/libpython2.6.so $ ./a.out random randint 1 100 Result of call: 39 $ ./a.out random randint 1 100 Result of call: 57 I specifically chose the `random` module because it does have `from math import log,...` so it is certainly importing the `math` module as well. Your issue is probably due to how you're linking; see [this forum post](http://objectmix.com/python/311970-weird-embedding-problem.html) for a similar issue someone else had. I can't find the links again, but it seems like there are some common issues when trying to link against Python's static library then importing modules that require a dynamic library.
Eclipse+PyDev+GAE memcache error Question: I've started using Eclipe+PyDev as an environment for developing my first app for Google App Engine. Eclipse is configured according to [this tutorial](http://code.google.com/appengine/articles/eclipse.html). Everything was working until I start to use memcache. PyDev reports the errors and I don't know how to fix it: ![alt text](http://www.freeimagehosting.net/uploads/fc176c0957.png) Error: Undefined variable from import: get How to fix this? Sure, it is only PyDev checker problem. Code is correct and run on GAE. UPDATE: 1. I'm using PyDev 1.5.0 but experienced the same with 1.4.8. 2. My PYTHONPATH includes (set in Project Properties/PyDev - PYTHONPATH): * `C:\Program Files\Google\google_appengine` * `C:\Program Files\Google\google_appengine\lib\django` * `C:\Program Files\Google\google_appengine\lib\webob` * `C:\Program Files\Google\google_appengine\lib\yaml\lib` UPDATE 2: I took a look at `C:\Program Files\Google\google_appengine\google\appengine\api\memcache\__init__.py` and found `get()` is not declared as `memcache` module function. They use the following trick to do that (I didn't hear about such possibility): _CLIENT = None def setup_client(client_obj): """Sets the Client object instance to use for all module-level methods. Use this method if you want to have customer persistent_id() or persistent_load() functions associated with your client. Args: client_obj: Instance of the memcache.Client object. """ global _CLIENT var_dict = globals() _CLIENT = client_obj var_dict['set_servers'] = _CLIENT.set_servers var_dict['disconnect_all'] = _CLIENT.disconnect_all var_dict['forget_dead_hosts'] = _CLIENT.forget_dead_hosts var_dict['debuglog'] = _CLIENT.debuglog var_dict['get'] = _CLIENT.get var_dict['get_multi'] = _CLIENT.get_multi var_dict['set'] = _CLIENT.set var_dict['set_multi'] = _CLIENT.set_multi var_dict['add'] = _CLIENT.add var_dict['add_multi'] = _CLIENT.add_multi var_dict['replace'] = _CLIENT.replace var_dict['replace_multi'] = _CLIENT.replace_multi var_dict['delete'] = _CLIENT.delete var_dict['delete_multi'] = _CLIENT.delete_multi var_dict['incr'] = _CLIENT.incr var_dict['decr'] = _CLIENT.decr var_dict['flush_all'] = _CLIENT.flush_all var_dict['get_stats'] = _CLIENT.get_stats setup_client(Client()) Hmm... Any idea how to force PyDev to recognize that? Answer: There is a cleaner solution: Try adding GAE's memcache to your forced builtins. In your PyDev->Interpreter-Python->ForcedBuiltins window, add the "google.appengine.api.memcache" entry and apply. Double-click on the memcache errors to check them back, they disappear! Please make sure that system pythonpath includes google APE install directory.
Why is the WindowsError while deleting the temporary file? Question: 1. I have created a temporary file. 2. Added some data to the file created. 3. Saved it and then trying to delete it. But I am getting `WindowsError`. I have closed the file after editing it. How do I check which other process is accessing the file. C:\Documents and Settings\Administrator>python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import tempfile >>> __, filename = tempfile.mkstemp() >>> print filename c:\docume~1\admini~1\locals~1\temp\tmpm5clkb >>> fptr = open(filename, "wb") >>> fptr.write("Hello World!") >>> fptr.close() >>> import os >>> os.remove(filename) Traceback (most recent call last): File "<stdin>", line 1, in <module> WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'c:\\docume~1\\admini~1\\locals~1\\temp\\tmpm5clkb' Answer: From the [documentation](http://docs.python.org/library/tempfile.html#tempfile.mkstemp): > mkstemp() returns a tuple containing an OS-level handle to an open file (as > would be returned by os.open()) and the absolute pathname of that file, in > that order. New in version 2.3. So, `mkstemp` returns both the OS file handle to _and_ the filename of the temporary file. When you re-open the temp file, the original returned file handle is still open (no-one stops you from opening twice or more the same file in your program). If you want to operate on that OS file handle as a python file object, you can: >>> __, filename = tempfile.mkstemp() >>> fptr= os.fdopen(__) and then continue with your normal code.
Twisted network client with multiprocessing workers? Question: So, I've got an application that uses Twisted + Stomper as a STOMP client which farms out work to a multiprocessing.Pool of workers. This appears to work ok when I just use a python script to fire this up, which (simplified) looks something like this: # stompclient.py logging.config.fileConfig(config_path) logger = logging.getLogger(__name__) # Add observer to make Twisted log via python twisted.python.log.PythonLoggingObserver().start() # initialize the process pool. (child processes get forked off immediately) pool = multiprocessing.Pool(processes=processes) StompClientFactory.username = username StompClientFactory.password = password StompClientFactory.destination = destination reactor.connectTCP(host, port, StompClientFactory()) reactor.run() As this gets packaged for deployment, I thought I would take advantage of the twistd script and run this from a tac file. Here's my very-similar-looking tac file: # stompclient.tac logging.config.fileConfig(config_path) logger = logging.getLogger(__name__) # Add observer to make Twisted log via python twisted.python.log.PythonLoggingObserver().start() # initialize the process pool. (child processes get forked off immediately) pool = multiprocessing.Pool(processes=processes) StompClientFactory.username = username StompClientFactory.password = password StompClientFactory.destination = destination application = service.Application('myapp') service = internet.TCPClient(host, port, StompClientFactory()) service.setServiceParent(application) For the sake of illustration, I have collapsed or changed a few details; hopefully they were not the essence of the problem. For example, my app has a plugin system, the pool is initialized by a separate method, and then work is delegated to the pool using pool.apply_async() passing one of my plugin's process() methods. So, if I run the script (stompclient.py), everything works as expected. It also appears to work OK if I run twist in non-daemon mode (-n): twistd -noy stompclient.tac however, it does _not_ work when I run in daemon mode: twistd -oy stompclient.tac The application appears to start up OK, but when it attempts to fork off work, it just hangs. By "hangs", I mean that it appears that the child process is never asked to do anything and the parent (that called pool.apply_async()) just sits there waiting for the response to return. I'm sure that I'm doing something stupid with Twisted + multiprocessing, but I'm really hoping that someone can explain to my the flaw in my approach. Thanks in advance! Answer: Since the difference between your working invocation and your non-working invocation is only the "-n" option, it seems most likely that the problem is caused by the daemonization process (which "-n" prevents from happening). On POSIX, one of the steps involved in daemonization is forking and having the parent exit. Among of things, this has the consequence of having your code run in a different process than the one in which the .tac file was evaluated. This also re-arranges the child/parent relationship of processes which were started in the .tac file - as your pool of multiprocessing processes were. The multiprocessing pool's processes start off with a parent of the twistd process you start. However, when that process exits as part of daemonization, their parent becomes the system init process. This may cause some problems, although probably not the hanging problem you described. There are probably other similarly low-level implementation details which normally allow the multiprocessing module to work but which are disrupted by the daemonization process. Fortunately, avoiding this strange interaction should be straightforward. Twisted's service APIs allow you to run code after daemonization has completed. If you use these APIs, then you can delay the initialization of the multiprocessing module's process pool until after daemonization and hopefully avoid the problem. Here's an example of what that might look like: from twisted.application.service import Service class MultiprocessingService(Service): def startService(self): self.pool = multiprocessing.Pool(processes=processes) MultiprocessingService().setServiceParent(application) Now, separately, you may also run into problems relating to clean up of the multiprocessing module's child processes, or possibly issues with processes created with Twisted's process creation API, reactor.spawnProcess. This is because part of dealing with child processes correctly generally involves handling the SIGCHLD signal. Twisted and multiprocessing aren't going to be cooperating in this regard, though, so one of them is going to get notified of all children exiting and the other will never be notified. If you don't use Twisted's API for creating child processes at all, then this may be okay for you - but you might want to check to make sure any signal handler the multiprocessing module tries to install actually "wins" and doesn't get replaced by Twisted's own handler.
tail -f in python with no time.sleep Question: I need to emulate "tail -f" in python, but I don't want to use time.sleep in the reading loop. I want something more elegant like some kind of blocking read, or select.select with timeout, but python 2.6 "select" documentation specifically says: "it cannot be used on regular files to determine whether a file has grown since it was last read." Any other way? In a few days if no solution is given I will read tail's C source code to try to figure it out. I hope they don't use sleep, hehe Thanks. MarioR Answer: (update) Either use FS monitors tools * For [linux](http://pyinotify.sourceforge.net/) * For [Windows](http://timgolden.me.uk/python/win32%5Fhow%5Fdo%5Fi/watch%5Fdirectory%5Ffor%5Fchanges.html) * For [Mac](http://pypi.python.org/pypi/pyobjc-framework-FSEvents/2.2b2) Or a single sleep usage (which I would you consider as much more elegant). import time def follow(thefile): thefile.seek(0,2) # Go to the end of the file while True: line = thefile.readline() if not line: time.sleep(0.1) # Sleep briefly continue yield line logfile = open("access-log") loglines = follow(logfile) for line in loglines: print line
Why I cannot build a chain of methods? (method1.method2.method3) Question: If I have the following code: import sqlite sqlite.connect('tmp.db').cursor().close() I get the following error message: Traceback (most recent call last): File "searchengine2.py", line 13, in ? sqlite.connect('tmp.db').cursor().close() File "/usr/lib64/python2.4/site-packages/sqlite/main.py", line 280, in close if self.con and self.con.closed: ReferenceError: weakly-referenced object no longer exists However, if I modify the code in the following way: import sqlite x1 = sqlite.connect('tmp.db') x2 = x1.cursor() x3 = x2.close() everything is fine. Why? Answer: Apparently the `cursor` keeps a weak reference to the connection (`self.con`). Because you chain the functions, the connection you've instantiated is out of scope as soon as you instantiate the cursor -- nothing holds a _strong_ reference to the connection anymore, and the connection is eligible for garbage collection. Therefore, by the time you try to `close` the cursor (which in turn tries to `close` the connection), the connection is already out of scope and may have been garbage collected -- if it was, then the connection is already closed. There's no way to get around this without modifying the cursor's source to make it hold a strong reference to the connection, and there's no easy way to tell how many problems that might introduce if you do it that way. (Good) designers don't arbitrarily make weak references without a good reason. (Hopefully you understand weak references from [your last question](http://stackoverflow.com/questions/1482141/what-does-it-mean-weakly- referenced-object-no-longer-exists).)
`xrange(2**100)` -> OverflowError: long int too large to convert to int Question: `xrange` function doesn't work for large integers: >>> N = 10**100 >>> xrange(N) Traceback (most recent call last): ... OverflowError: long int too large to convert to int >>> xrange(N, N+10) Traceback (most recent call last): ... OverflowError: long int too large to convert to int Python 3.x: >>> N = 10**100 >>> r = range(N) >>> r = range(N, N+10) >>> len(r) 10 Is there a backport of py3k builtin `range()` function for Python 2.x? ### Edit I'm looking for a complete implementation of "lazy" `range()`, not just a partial implementation of some of its functionality. Answer: I believe there is no backport (Py 3's completely removed the int/long distinction, after all, but in 2.* it's here to stay;-) but it's not hard to hack your own, e.g....: import operator def wowrange(start, stop, step=1): if step == 0: raise ValueError('step must be != 0') elif step < 0: proceed = operator.gt else: proceed = operator.lt while proceed(start, stop): yield start start += step **Edit** it appears the OP doesn't just want looping (the normal purpose of xrange, and range in Py3), but also `len` and the `in` operator (the latter does work on the above generator, but slowly -- optimizations are possible). For such richness a class is better...: import operator class wowrange(object): def __init__(self, start, stop=None, step=1): if step == 0: raise ValueError('step must be != 0') if stop is None: start, stop = 0, start if step < 0: self.proceed = operator.gt self.l = (stop-start+step+1)//step else: self.proceed = operator.lt self.l = (stop-start+step-1)//step self.lo = min(start, stop) self.start, self.stop, self.step = start, stop, step def __iter__(self): start = self.start while self.proceed(start, self.stop): yield start start += self.step def __len__(self): return self.l def __contains__(self, x): if x == self.stop: return False if self.proceed(x, self.start): return False if self.proceed(self.stop, x): return False return (x-self.lo) % self.step == 0 I wouldn't be surprised if there's an off-by-one or similar glitch lurking here, but, I hope this helps! **Edit** again: I see indexing is ALSO required. Is it just too hard to write your own `__getitem__`? I guess it is, so here it, too, is, served on a silver plate...: def __getitem__(self, i): if i < 0: i += self.l if i < 0: raise IndexError elif if i >= self.l: raise IndexError return self.start + i * self.step I don't know if 3.0 `range` supports slicing (`xrange` in recent `2.*` releases doesn't -- it used to, but that was removed because the complication was ridiculous and prone to bugs), but I guess I do have to draw a line in the sand somewhere, so I'm not going to add it;-).
Python Script to find instances of a set of strings in a set of files Question: I have a file which I use to centralize all strings used in my application. Lets call it Strings.txt; TITLE="Title" T_AND_C="Accept my terms and conditions please" START_BUTTON="Start" BACK_BUTTON="Back" ... This helps me with I18n, the issue is that my application is now a lot larger and has evolved. As such a lot of these strings are probably not used anymore. I want to eliminate the ones that have gone and tidy up the file. I want to write a python script, using regular expressions I can get all of the string aliases but how can I search all files in a Java package hierarchy for an instance of a string? If there is a reason I use use perl or bash then let me know as I can but I'd prefer to stick to one scripting language. Please ask for clarification if this doesn't make sense, hopefully this is straightforward, I just haven't used python much. Thanks in advance, Gav Answer: Assuming the files are of reasonable size (as source files will be) so you can easily read them in memory, and that you're looking for the parts in quotes right of the = signs: import collections files_by_str = collections.defaultdict(list) thestrings = [] with open('Strings.txt') as f: for line in f: text = line.split('=', 1)[1] text = text.strip().replace('"', '') thestrings.append(text) import os for root, dirs, files in os.walk('/top/dir/of/interest'): for name in files: path = os.path.join(root, name) with open(path) as f: data = f.read() for text in thestrings: if text in data: files_by_str[text].append(path) break This gives you a dict with the texts (those that are present in 1+ files, only), as keys, and lists of the paths to the files containing them as values. If you care only about a yes/no answer to the question "is this text present somewhere", and don't care where, you can save some memory by keeping only a set instead of the defaultdict; but I think that often knowing what files contained each text will be useful, so I suggest this more complete version.
Combining Dictionaries Of Lists In Python Question: I have a very large collection of (p, q) tuples that I would like to convert into a dictionary of lists where the first item in each tuple is a key that indexes a list that contains q. Example: Original List: (1, 2), (1, 3), (2, 3) Resultant Dictionary: {1:[2, 3], 2:[3]} Furthermore, I would like to efficiently combine these dictionaries. Example: Original Dictionaries: {1:[2, 3], 2:[3]}, {1:[4], 3:[1]} Resultant Dictionary: {1:[2, 3, 4], 2:[3], 3:[1]} These operations reside within an inner loop, so I would prefer that they be as fast as possible. Thanks in advance Answer: If the list of tuples is sorted, `itertools.groupby`, as suggested by @gnibbler, is not a bad alternative to `defaultdict`, but it needs to be used differently than he suggested: import itertools import operator def lot_to_dict(lot): key = operator.itemgetter(0) # if lot's not sorted, you also need...: # lot = sorted(lot, key=key) # NOT in-place lot.sort to avoid changing it! grob = itertools.groupby(lot, key) return dict((k, [v[1] for v in itr]) for k, itr in grob) For "merging" dicts of lists into a new d.o.l...: def merge_dols(dol1, dol2): keys = set(dol1).union(dol2) no = [] return dict((k, dol1.get(k, no) + dol2.get(k, no)) for k in keys) I'm giving `[]` a nickname `no` to avoid uselessly constructing a lot of empty lists, given that performance is important. If the sets of the dols' keys overlap only modestly, faster would be: def merge_dols(dol1, dol2): result = dict(dol1, **dol2) result.update((k, dol1[k] + dol2[k]) for k in set(dol1).intersection(dol2)) return result since this uses list-catenation only for overlapping keys -- so, if those are few, it will be faster.
Web Service client in Python using ZSI - "Classless struct didn't get dictionary" Question: I am trying to write a sample client in Python using ZSI for a simple Web Service. The Web Service WSDL is following: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.example.org/test/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="test" targetNamespace="http://www.example.org/test/"> <wsdl:message name="NewOperationRequest"> <wsdl:part name="NewOperationRequest" type="xsd:string"/> </wsdl:message> <wsdl:message name="NewOperationResponse"> <wsdl:part name="NewOperationResponse" type="xsd:string"/> </wsdl:message> <wsdl:portType name="test"> <wsdl:operation name="NewOperation"> <wsdl:input message="tns:NewOperationRequest"/> <wsdl:output message="tns:NewOperationResponse"/> </wsdl:operation> </wsdl:portType> <wsdl:binding name="testSOAP" type="tns:test"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <wsdl:operation name="NewOperation"> <soap:operation soapAction="http://www.example.org/test/NewOperation"/> <wsdl:input> <soap:body namespace="http://www.example.org/test/" use="literal"/> </wsdl:input> <wsdl:output> <soap:body namespace="http://www.example.org/test/" use="literal"/> </wsdl:output> </wsdl:operation> </wsdl:binding> <wsdl:service name="test"> <wsdl:port binding="tns:testSOAP" name="testSOAP"> <soap:address location="http://localhost/test"/> </wsdl:port> </wsdl:service> </wsdl:definitions> Every time I run following code: from ZSI.ServiceProxy import ServiceProxy service = ServiceProxy('test.wsdl') service.NewOperation('test') I receive: (...) /var/lib/python-support/python2.5/ZSI/TCcompound.pyc in cb(self, elt, sw, pyobj, name, **kw) 345 f = lambda attr: pyobj.get(attr) 346 if TypeCode.typechecks and type(d) != types.DictType: --> 347 raise TypeError("Classless struct didn't get dictionary") 348 349 indx, lenofwhat = 0, len(self.ofwhat) TypeError: Classless struct didn't get dictionary I have searched Google for this error and I found couple posts describing similar problem but with no answer. Do you know was is wrong here? Is there an error in the WSDL, do I miss something in the code or there is a bug in ZSI? Thank you in advance for you help :-) Answer: Finally, I have found the solution. I should run like this: from ZSI.ServiceProxy import ServiceProxy service = ServiceProxy('test.wsdl') service.NewOperation(NewOperationRequest='test') The reason of the problem was that the name of the parameter was missing (sic!) - silly error ;-)
Parsing out data using BeautifulSoup in Python Question: I am attempting to use BeautifulSoup to parse through a DOM tree and extract the names of authors. Below is a snippet of HTML to show the structure of the code I'm going to scrape. <html> <body> <div class="list-authors"> <span class="descriptor">Authors:</span> <a href="/find/astro-ph/1/au:+Lin_D/0/1/0/all/0/1">Dacheng Lin</a>, <a href="/find/astro-ph/1/au:+Remillard_R/0/1/0/all/0/1">Ronald A. Remillard</a>, <a href="/find/astro-ph/1/au:+Homan_J/0/1/0/all/0/1">Jeroen Homan</a> </div> <div class="list-authors"> <span class="descriptor">Authors:</span> <a href="/find/astro-ph/1/au:+Kosovichev_A/0/1/0/all/0/1">A.G. Kosovichev</a> </div> <!--There are many other div tags with this structure--> </body> </html> My point of confusion is that when I do soup.find, it finds the first occurrence of the div tag that I'm searching for. After that, I search for all 'a' link tags. At this stage, how do I extract the authors names from each of the link tags and print them out? Is there a way to do it using BeautifulSoup or do I need to use Regex? How do I continue iterating over every other other div tag and extract the authors names? import re import urllib2,sys from BeautifulSoup import BeautifulSoup, NavigableString html = urllib2.urlopen(address).read() soup = BeautifulSoup(html) try: authordiv = soup.find('div', attrs={'class': 'list-authors'}) links=tds.findAll('a') for link in links: print ''.join(link[0].contents) #Iterate through entire page and print authors except IOError: print 'IO error' Answer: just use findAll for the divs link you do for the links for authordiv in soup.findAll('div', attrs={'class': 'list-authors'}):
How to pick certain elements of x-tuple returned by a function? Question: I am a newbie to Python. Consider the function `str.partition()` which returns a 3-tuple. If I am interested in only elements 0 and 2 of this tuple, what is the best way to pick only certain elements out of such a tuple? I can currently do either: # Introduces "part1" variable, which is useless (part0, part1, part2) = str.partition(' ') Or: # Multiple calls and statements, again redundancy part0 = str.partition(' ')[0] part2 = str.partition(' ')[2] I would like to be able to do _something_ like this, but cannot: (part0, , part2) = str.partition(' ') # Or: (part0, part2) = str.partition(' ')[0, 2] Answer: Underscore is often used as a name for stuff you do not need, so something like this would work: part0, _, part2 = str.partition(' ') In this particular case, you could do this, but it isn't a pretty solution: part0, part2 = str.partition(' ')[::2] A more esoteric solution: from operator import itemgetter part0, part2 = itemgetter(0, 2)(str.partition(' '))
How to use export with Python on Linux Question: I need to make an export like this in Python : # export MY_DATA="my_export" I've tried to do : # -*- python-mode -*- # -*- coding: utf-8 -*- import os os.system('export MY_DATA="my_export"') But when I list export, "MY_DATA" not appear : # export How I can do an export with Python without saving "my_export" into a file ? Answer: `export` is a command that you give directly to the shell (e.g. `bash`), to tell it to add or modify one of its environment variables. You can't change your shell's environment from a child process (such as Python), it's just not possible. Here's what's happening with you try `os.system('export MY_DATA="my_export"')`... /bin/bash process, command `python yourscript.py` forks python subprocess |_ /usr/bin/python process, command `os.system()` forks /bin/sh subprocess |_ /bin/sh process, command `export ...` changes local environment When the bottom-most `/bin/sh` subprocess finishes running your `export ...` command, then it's discarded, along with the environment that you have just changed.
how to run both python 2.6 and 3.0 on the same windows XP box? Question: What kind of setup do people use to run both python 2.6 and python 3.0 on the same windows machine? Answer: No problem, each version is installed in its own directory. On my Windows box, I have `C:\Python26\` and `C:\Python31\`. The _Start Menu_ items are also distinct. Just use the standard installers from the Python Programming Language [Official Website](http://www.python.org/download/), or the ready-to- install distributions from [ActiveState](http://www.activestate.com/activepython/). A direct way to select the wanted version is to name it explicitly on the command line. C:\> C:\Python25\python ver.py 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] C:\> C:\Python31\python ver.py 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] Where `ver.py` is: import sys print (sys.version)
map string position to line number in regex output Question: I'm working on a "grep-like" utility in Python for searching Oracle source code files. Coding standards have changed over time, so trying to find something like "all deletes from table a.foo" could span multiple lines, or not, depending on the age of that piece of code: s = """-- multiline DDL statement DELETE a.foo f WHERE f.bar = 'XYZ'; DELETE a.foo f WHERE f.bar = 'ABC'; DELETE a.foo WHERE bar = 'PDQ'; """ import re p = re.compile( r'\bDELETE\b.+?a\.foo', re.MULTILINE | re.DOTALL ) for m in re.finditer( p, s ): print s[ m.start() : m.end() ] This outputs: DELETE a.foo DELETE a.foo DELETE a.foo What I want: [2] DELETE [3] a.foo [7] DELETE a.foo [10] DELETE a.foo Is there a quick/simple/builtin way to map string indices to line numbers? Answer: lineno = s.count("\n",0,m.start())+1
How to print a list in Python "nicely" Question: In PHP, I can do this: echo '<pre>' print_r($array); echo '</pre>' In Python, I currently just do this: print the_list However, this will cause a big jumbo of data. Is there any way to print it nicely into a readable tree? (with indents)? Answer: from pprint import pprint pprint(the_list)
Does anyone know a way to scramble the elements in a list? Question: thelist = ['a','b','c','d'] How I can to scramble them in Python? Answer: >>> import random >>> thelist = ['a', 'b', 'c', 'd'] >>> random.shuffle(thelist) >>> thelist ['d', 'a', 'c', 'b'] Your result will (hopefully!) vary.
How do I change my float into a two decimal number with a comma as a decimal point separator in python? Question: I have a float: 1.2333333 How do I change it into a two decimal number with a comma as a decimal point separator, eg 1,23? Answer: The [locale module](http://docs.python.org/library/locale.html) can help you with reading and writing numbers in the locale's format. >>> import locale >>> locale.setlocale(locale.LC_ALL, "") 'sv_SE.UTF-8' >>> locale.format("%f", 2.2) '2,200000' >>> locale.format("%g", 2.2) '2,2' >>> locale.atof("3,1415926") 3.1415926000000001
How to read lines from a file into a multidimensional array (or an array of lists) in python Question: I have a file with a format similar to this: a,3,4,2,1 3,2,1,a,2 I want to read the file and create an array of lists in a way that: array[0] = ['a','3','4','2','1'] array[1] = ['3','2','1','a','2'] How can I do that? So far I am stuck with: f = open('./urls-eu.csv', 'r') for line in f: arr = line.split(',') print arr I am really new to python. Answer: Batteries included: >>> import csv >>> array = list( csv.reader( open( r'./urls-eu.csv' ) ) ) >>> array[0] ['a', '3', '4', '2', '1'] >>> array[1] ['3', '2', '1', 'a', '2']
Why Does List Argument in Python Behave Like ByRef? Question: This may be for most languages in general, but I'm not sure. I'm a beginner at Python and have always worked on copies of lists in C# and VB. But in Python whenever I pass a list as an argument and enumerate through using a "for i in range," and then change the value of the list argument, the input values actually changes the original list. I thought Python was supposed to pass arguments by value by default so that once the function is finished I still have the original values from before I called the function. What am I missing? Thanks! Answer: Python does pass arguments by value but the value you are receiving is a copy of the reference (incidentally this is the exact same way that C#, VB.NET, and Java behave as well). This is the important thing to remember: > _Objects are not passed by reference - object references are passed by > value_. Since you have a copy of the reference, any operation on what that reference points to will be just as if you were holding the original reference itself.
(strongly vs weakly) typed AND (statically vs dynamically) typed languages and Moore's law Question: I do not know how many faces this problem. If I do programming in weakly/dynamically typed language like python,php,javascript for few days I lose touch with strongly typed languages like c++,Java,.net. I recently heard languages like python and ruby which people loved programming in. It is very easy programming in weakly/dynamically typed languages, but there is a danger of losing touch with languages like c++,Java. Processors now becoming very powerful and according to [Moore's law](http://en.wikipedia.org/wiki/Moore%27s%5Flaw) it will increase speed with time exponentially. So efficiency may not be issue as similar thing happened when we shifted from embedded to high level languages like c++,java. * So is the world shifting toward weakly/dynamically typed languages? * Will the weakly/dynamically typed languages replace strongly typed languages in future? * Are there any fields in which strongly typed language is a must use and cannot be replaced current time as well as near future? Answer: First, Moore's law is only an empirical observation. Sooner or later, the laws of physics will mean that it is no longer possible to keep increase uniprocessor speed. Moore's law is not a useful predictor of the future in the medium to long term, and possibly not even in the short term. Second, strongly and weakly typed languages are EQUALLY affected by Moores law. Third, Moore's law is about uniprocessors. We're well into a world where increases in raw computing power are coming through multi-processing, but there aren't the software tools (e.g. languages) around yet that help the average Joe programmer to write programs that take advantage of multi- processing. However, functional languages offer more promise in this area than procedural ones. Fourth, I think you are really comparing statically typed versus dynamically typed languages. (The terms "strongly typed" and "weakly typed" have become so confused due to conflicting definitions that they are no longer meaningful.) I guess your argument is that Moore's law means that efficiency matters less, so we can "get away with" using less efficient computation paradigms; e.g. dynamically typed languages. (And if we are talking about interactive tasks, the computer only needs to keep up with the user's speed of asking for things and mentally processing the answers.) The flip side of that argument is that people are wanting their computers to do more compute intensive things; e.g. each generation of computer games requires more power to do the graphics. Online business wants to do more things (e.g. serve more web requests) faster with hardware that is cheaper to run. In short, there are lots of situations where efficiency does matter, and this will always be the case. So what you find is that in places where speeds is important, we tend to use efficient computing techniques, and where it is unimportant we use techniques that minimize software development and maintenance costs. * * * **UPDATE** On rereading my answer, I missed something. If we taken it as read that Moores law is breaking down, and that future increases in computing "power" will come in the form of more cores, etcetera, then there will be an increasing role for functional languages. Anyone who has tried to exploit parallelism in an imperative or OO language will recognize that it is a tricky problem, fraught with pitfalls. By contrast, in a pure functional language, parallelism is much simpler. Since the state of data structures doesn't change, you don't need to worry about threads synchronizing over the use of the data structures. Furthermore, it is simpler for the compiler or runtime system of the language to spot that a particular part of your program could be done in parallel ... and just do it. Or at a higher level, the FP language IDE (or whatever) could find / suggest opportunities for large scale transformations to aid parallel execution. IMO, this is what is behind the (slow) rise in popularity of functional languages ...
Python 3.1.1 with --enable-shared : will not build any extensions Question: Summary: Building Python 3.1 on RHEL 5.3 64 bit with `--enable-shared` fails to compile all extensions. Building "normal" works fine without any problems. **Please note** that this question may seem to blur the line between programming and system administration. However, I believe that because it has to deal directly with getting language support in place, and it very much has to do with supporting the process of programming, that I would cross-post it here. Also at: <http://serverfault.com/questions/73196/python-3-1-1-with- enable-shared-will-not-build-any-extensions>. Thank you! **Problem:** Building Python 3.1 on RHEL 5.3 64 bit with `--enable-shared` fails to compile all extensions. Building "normal" works fine without any problems. I can build python 3.1 just fine, but when built as a shared library, it emits many warnings (see below), and refuses to build any of the `c` based modules. Despite this failure, I can still build mod_wsgi 3.0c5 against it, and run it under apache. Needless to say, the functionality of Python is greatly reduced... Interesting to note that Python 3.2a0 (from svn) compiles fine with --enable- shared, and mod_wsgi compiles fine against it. But when starting apache, I get: `Cannot load /etc/httpd/modules/mod_wsgi.so into server: /etc/httpd/modules/mod_wsgi.so: undefined symbol: PyCObject_FromVoidPtr` The project that this is for is a long-term project, so I'm okay with alpha quality software if needed. Here are some more details on the problem. **Host:** * Dell PowerEdge * Intel Xenon * RHEL 5.3 64bit * Nothing "special" **Build:** * Python 3.1.1 source distribution * Works fine with `./configure` * Does not work fine with `./configure --enable-shared` (`export CFLAGS="-fPIC"` has been done) **make output** * * * `gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict- prototypes -I. -IInclude -I./Include -fPIC -DPy_BUILD_CORE -c ./Modules/_weakref.c -o Modules/_weakref.o` * * * `building 'bz2' extension gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -I./Include -I/usr/local/include -IInclude -I/home/build/RPMBUILD/BUILD/Python-3.1.1 -c /home/build/RPMBUILD/BUILD/Python-3.1.1/Modules/bz2module.c -o build/temp.linux-x86_64-3.1/home/build/RPMBUILD/BUILD/Python-3.1.1/Modules/bz2module.o gcc -pthread -shared -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes build/temp.linux-x86_64-3.1/home/build/RPMBUILD/BUILD/Python-3.1.1/Modules/bz2module.o -L/usr/local/lib -L. -lbz2 -lpython3.1 -o build/lib.linux-x86_64-3.1/bz2.so /usr/bin/ld: /usr/local/lib/libpython3.1.a(abstract.o): relocation R_X86_64_32 against 'a local symbol' can not be used when making a shared object; recompile with -fPIC` * * * Failed to build these modules: _bisect _codecs_cn _codecs_hk _codecs_iso2022 _codecs_jp _codecs_kr _codecs_tw _collections _csv _ctypes _ctypes_test _curses _curses_panel _dbm _elementtree _gdbm _hashlib _heapq _json _lsprof _multibytecodec _multiprocessing _pickle _random _socket _sqlite3 _ssl _struct _testcapi array atexit audioop binascii bz2 cmath crypt datetime fcntl grp itertools math mmap nis operator ossaudiodev parser pyexpat readline resource select spwd syslog termios time unicodedata zlib Answer: Something is wrong with your build environment. It is picking up a libpython3.1.a from `/usr/local/lib`; this confuses the error messages. It tries linking with that library, which fails - however, it shouldn't have tried that in the first place, since it should have used the libpython that it just built. I recommend taking the Python 3.1 installation in `/usr/local` out of the way. You don't show in your output whether a libpython3.1.so.1.0 was created in the build tree; it would be important to find out whether it exists, how it was linked, and what symbols it has exported.
Python for C++ or Java Programmer Question: I have a background in C++ and Java and Objective C programming, but i am finding it hard to learn python, basically where its "Main Function" or from where the program start executing. So is there any tutorial/book which can teach python to people who have background in C++ or Java. Basically something which can show if how you were doing this in C++ and how this is done in Python. OK i think i did not put the question heading or question right, basically i was confused about the "Main" Function, otherwise other things are quite obvious from python official documentation except this concept. Thanks to all Answer: When you run a script through the Python interpreter (or import that script from another script), **it actually executes all the code from beginning to end** \-- in _that_ sense, **there is no "entry point" to a Python script**. So to work around this, Python automatically creates a `__name__` variable and fills it with the value `"__main__"` when you are running a script by itself (as opposed to something else importing that script). That's why you'll see many scripts like: def foo(): print "Hello!" if __name__ == "__main__": foo() where all the function/class definitions are at the top, and there is a similar if-statement as the last thing in the script. You are guaranteed that Python will start executing the script from top-to-bottom, so it will read all of your definitions there. If you wanted, you could intermingle actual functional code inside all the function definitions. If this script was named `bar.py`, you could do `python bar.py` at the command line and you would see the script print out `"Hello!"`. On the other hand, if you did `import bar` from another Python script, nothing would print out until you did `bar.foo()`, because `__name__` was no longer `"__main__"` and the if-statement failed, thus `foo` was never executed.
Why doesn't memcache work in my Django? Question: from django.core.cache import cache def testcache(): cache.set('test','I am putting this message in',3333) print cache.get('test') It just prints "**None** " This is in "ps aux": dovr 2241 0.0 0.8 57824 2144 ? Ssl 04:20 0:00 memcached -d -u root -m 3900 -p 11211 dovr 2247 0.0 3.7 83696 9800 pts/2 S+ 04:20 0:00 python manage.py runserver 0.0.0.0:8000 And this is in my settings.py: CACHE_BACKEND = 'memcached://MYIPADRESS:11211/' By the way, it worked before, but not anymore! I don't know why. So weird. Answer: You can insure that you can reach memcached from your code by logging value returned from `set()` method. Probably memcached listens on 127.0.0.1 while you are trying to connect to external interface.
Python sqlite3 version Question: Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.4.1' Questions: * Why is the version of the sqlite**3** module **'2.4.1'** * Whats the reason behind bundling such an old sqlite with Python? The sqlite releaselog says **2002 Mar 13 (2.4.1)**. Answer: Python 2.5.1 >>> import sqlite3 >>> sqlite3.version '2.3.2' >>> sqlite3.sqlite_version '3.3.4' version - pysqlite version sqlite_version - sqlite version
python: interact with the session in cgi scripts Question: Can python cgi scripts write and read data to the session? If so how? Is there a high-level API or must I roll my own classes? Answer: There's no "_session_ " on `cgi`. You must roll your own session handling code if you're using raw `cgi`. Basically, sessions work by creating a unique cookie number and sending it on a response header to the client, and then checking for this cookie on every connection. Store the session data somewhere on the server (memory, database, disk) and use the cookie number as a key to retrieve it on every request made by the client. However `cgi` is not how you develop applications for the web in python. Use [`wsgi`](http://wsgi.org/). Use a web framework. Here's a quick example using [cherrypy](http://cherrypy.org/). `cherrypy.tools.sessions` is a cherrypy tool that handles cookie setting/retrieving and association with data automatically: import cherrypy class HelloSessionWorld(object): @cherrypy.tools.sessions() def index(self): if 'data' in cherrypy.session: return "You have a cookie! It says: %r" % cherrypy.session['data'] else: return "You don't have a cookie. <a href='getcookie'>Get one</a>." index.exposed = True @cherrypy.tools.sessions() def getcookie(self): cherrypy.session['data'] = 'Hello World' return "Done. Please <a href='..'>return</a> to see it" getcookie.exposed = True application = cherrypy.tree.mount(HelloSessionWorld(), '/') if __name__ == '__main__': cherrypy.quickstart(application) Note that this code is a `wsgi` application, in the sense that you can publish it to any `wsgi`-enabled web server (apache has [`mod_wsgi`](http://code.google.com/p/modwsgi)). Also, cherrypy has its own `wsgi` server, so you can just run the code with python and it will start serving on [`http://localhost:8080/`](http://localhost:8080/)
How can I build the Boost.Python example on Ubuntu 9.10? Question: I am using Ubuntu 9.10 beta, whose repositories contain boost 1.38. I would like to build the hello-world example. I followed the instructions here (<http://www.boost.org/doc/libs/1%5F40%5F0/libs/python/doc/tutorial/doc/html/python/hello.html>), found the example project, and issued the "bjam" command. I have installed bjam and boost-build. I get the following output: Jamroot:18: in modules.load rule python-extension unknown in module Jamfile</usr/share/doc/libboost1.38-doc/examples/libs/python/example>. /usr/share/boost-build/build/project.jam:312: in load-jamfile /usr/share/boost-build/build/project.jam:68: in load /usr/share/boost-build/build/project.jam:170: in project.find /usr/share/boost-build/build-system.jam:248: in load /usr/share/boost-build/kernel/modules.jam:261: in import /usr/share/boost-build/kernel/bootstrap.jam:132: in boost-build /usr/share/doc/libboost1.38-doc/examples/libs/python/example/boost-build.jam:7: in module scope I do not know enough about Boost (this is an exploratory exercise for myself) to understand why the python-extension macro in the included Jamroot is not valid. I am running this example from the install directory, so I have not altered the Jamroot's use-project setting. As a side question, if I were to just willy-nilly start a project in an arbitrary directory, how would I write my jamroot? Answer: The problem comes from using Ubuntu package instead of boost compiled from source. You have to edit you Jamroot to say it to use global libboost-python, instead of looking for lib in relative boost source tree. Summarily you should have these lines at the beginning of your Jamroot: using python ; lib libboost_python : : <name>boost_python ; project : requirements <library>libboost_python ; It was reported as a bug on Debian and corrected at least on lenny with libboost-python1.40 ...mostly. The example in libboost_python still refers to boost_python-mt instead of boost_python, but /usr/lib/libboost_python.so exists but not /usr/lib/libboost_python-mt.so. Hopefully Ubuntu will soon have the same fix and the next user won't stumble on this... I know the answer to your question because I **did** had the exact same problem not long ago.
In Python, how do I transform a string into a file? Question: There is a read-only library function that takes a file as an argument. But I have a string. How do I convert a string to a file, that if you read the file it will return this string? I don't want to write to disk. Answer: The `StringIO` module: >>> import StringIO >>> f = StringIO.StringIO("foo") >>> f.read() 'foo' The `cStringIO` module has the same interface, and is faster, but can't deal with Unicode strings that have non-ASCII characters. [StringIO documentation](http://docs.python.org/library/stringio.html)
How do I request data securely via Google OAuth? Question: Until recently users of my site were able to import data from Google, via OAuth. However, recently they have received the warning below, in a yellow box, when authorising (although the import still works). I've also noticed this same warning on Facebook's GMail authenticator! What's changed / am I missing? > This website is registered with Google to make authorization requests, but > has not been configured to send requests securely. > > If you grant access but you did not initiate this request at www.foo.com, it > may be possible for other users of www.foo.com to access your data. We > recommend you deny access unless you are certain that you initiated this > request directly with www.foo.com. (The site is written in Zope/Python, but the step/documentation I'm missing is more important) Answer: Did you try Googling the error message? Doing so took me to [this page](http://code.google.com/apis/accounts/docs/RegistrationForWebAppsAuto.html), which states: > Registered with enhanced security: Registered applications **with a security > certificate on file** can use secure tokens. The Access Request page removes > cautions, displaying this message: " Google is not affiliated with , and we > recommend that you grant access only if you trust the site." See their docs, step 4, "Upload a security certificate" for more details.
syntax error on `If` line Question: My code: #!/usr/bin/env python def Runaaall(aaa): Objects9(1.0, 2.0) def Objects9(aaa1, aaa2): If aaa2 != 0: print aaa1 / aaa2 The error I receive: $ python test2.py File "test2.py", line 7 If aaa2 != 0: print aaa1 / aaa2 ^ SyntaxError: invalid syntax I'm at a loss to why this error is happening. Answer: `if` must be written in lower case. Furthermore, * Write function names in lower case (see [PEP 8](http://www.python.org/dev/peps/pep-0008/), the Python style guide). * Write the body of an `if`-clause on a separate line. * Though in this case you'll probably not run into trouble, be careful with [comparing floats for equality](http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm). * Since you've just started learning Python, you may want to get acquainted with writing parentheses around the arguments to `print`, since from Python 3 onwards, [print is a function](http://docs.python.org/dev/3.0/whatsnew/3.0.html), not a keyword. To enforce this syntax in Python 2.6, you can put this at the top of your file: from __future__ import print_function Demonstration: >>> print 'test' test >>> from __future__ import print_function >>> print 'test' File "<stdin>", line 1 print 'test' ^ SyntaxError: invalid syntax >>> print('test') test For more on `__future__` imports, see the [documentation](http://docs.python.org/3.1/library/%5F%5Ffuture%5F%5F.html).
Has anyone found that UIWebView fails for some URLS? Question: I have been working on an iPhone App for a couple of weeks now and one of the earlier features I added was a _UIWebView_ that loaded context sensitive Wikipedia page topics. This was pretty trivial to implement and has been working fine for some time. Today, I found that functionality had unexpectedly stopped working. I had been fiddling around at the perimeter of that piece of code and initially assumed that I had broken something. I checked all the obvious places, my urls, was the _UIWebView_ still hooked up in the XIB etc. I didn't find any issues. Investigating further, I stuck some error handling on my _UIWebViewDelegate_ *didFailLoadWithError* and found I was getting a -999 error: > **NSURLErrorCancelled** > > Returned when an asynchronous load is canceled. > > A Web Kit framework delegate will receive this error when it performs a > cancel operation on a loading resource. Note that an NSURLConnection or > NSURLDownload delegate will not receive this error if the download is > canceled. So this sounds like making a new request (or cancelling) before the original one has finished. I check my code for anything like this and come up empty. So I went into my usual downward spiral of paranoia and assumed that Wikipedia was blocking requests based on UAgent or something and went on something of wild goose chase attempting to spoof my way back to a happy place. These attempts were not successful and eventually sanity prevailed. I created a simple python script to mimic the HTTP request I was making from my APP in the simulator, to see what Wikipedia was sending back: string = "GET /wiki/Franklin_D._Roosevelt HTTP/1.1\r\nHost: en.wikipedia.org\r\nUser-Agent: test\r\nReferer: http://en.wikipedia.org/wiki/Franklin_D._Roosevelt\r\nAccept: */*\r\nAccept-Language: en-us\r\n_Accept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\n\r\n" import socket s = socket.socket() s.connect(("en.wikipedia.org",80)) s.send(string) x = s.recv (1000) while (x): print x x = s.recv (1000) So I run this guy and discover that Wikipedia is very kindly returning my data promptly and completely. So what is going on? Chinks started to appear in my every present, paranoid armour "It's always my fault" and I decide to check out if other iPhone apps can view these URLs. I post a [tweet](http://twitter.com/redbluething/status/4906373854) with an ironically amusing (I am easily amused) URL and check out if Tweetie can view the URL. It can't. A friend tries it out in Twitterific. Same problem. Works fine in Safari and the Wikipedia App, but it seems like iPhone apps using a bog standard _UIWebView_ are having problems with Wikipedia pages. Just to be completely certain there are no other variables, I created a [simple test app](http://www.cannonade.net/pics/UIWebViewTest.zip) with just a UIWebView that loads up <http://en.wikipedia.com>, it fails with the same error (added that code at the end). So what do you guys think? Is this just a _UIWebView_ bug? Any Apple gronks out there know what is going on here? Have I missed something completely obvious and I am once again sitting on the train to work without my pants on? Looking forward to hearing what you think. Keep in mind, this was working fine yesterday. **Debrief** (or maybe Post Mortem is more appropriate): Thanks [Duncan](http://stackoverflow.com/users/75656/duncanwilcox) for the solution and a pretty clear description of what is going on here. Looks like the reason I originally saw the error, when I wasn't implementing the _didFailLoadWithError_ delegate method at all, was that the default behavior for that method is apparently to clear the _UIWebView_ and consequently kill the request. When I added my implementation to find out what was going on, I stuck in some code to write the error to the view and, as Duncan points out, this is what got me. Seems like a pretty horrible solution to ignore -999 error codes in the callback, but I am fine with duct tape. I tried quite a few apps to test if this was a UIWebView problem (Tweetie, Twitteriffic etc ...) and they all had the issue. It looks like this might be a pretty common oversight for developers. Maybe Apple can clean this up in the next version. Other interesting point is that when I switched my URLs to use <http://en.m.wikipedia.com> instead of <http://en.wikipedia.com>, the problem went away. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; _webView = (UIWebView*)self.view; _webView.delegate = self; // load the url // FAIL //NSURL * newUrl = [[[NSURL alloc] initWithString:@"http://en.wikipedia.com"] autorelease]; // OK NSURL * newUrl = [[[NSURL alloc] initWithString:@"http://www.stackoverflow.com"] autorelease]; NSURLRequest * newUrlRequest = [NSURLRequest requestWithURL:newUrl]; [_webView loadRequest:newUrlRequest]; } // delegate stuff - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)req navigationType:(UIWebViewNavigationType)navigationType { return YES; } - (void)webViewDidStartLoad:(UIWebView *)wv { // starting the load, show the activity indicator in the status bar [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; } - (void)webViewDidFinishLoad:(UIWebView *)webView { // finished loading, hide the activity indicator in the status bar [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; } - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { NSURLErrorDomain // load error, hide the activity indicator in the status bar [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; [_webView loadHTMLString:[[[NSString alloc] initWithFormat:@"Failed to load page %@", [error localizedDescription]] autorelease] baseURL:nil]; } Answer: Looks like there's an answer here: <http://stackoverflow.com/questions/1024748/how-do-i-fix-nsurlerrordomain- error-999-in-iphone-3-0-os> which in turn refers to: <http://www.iphonedevsdk.com/forum/iphone-sdk-development/6280-uiwebview- didfailloadwitherror-how-get-errors-code-list.html> Looks like you need a hack like this in the webView:didFailLoadWithError: delegate: if ([error code] != NSURLErrorCancelled) { //show error alert, etc. } In essence what's happening is the delegate is getting a "cancelled" (-999) failure, that might be originated in javascript or perhaps even in a UIWebView bug. With your code the webview doesn't show anything at all because you're using the very same UIWebView to display the error. If you had just NSLog'd the error you would have seen a failure, but then the page would have loaded just fine, giving you a hint that the failure is bogus.
Running Tests From a Module Question: I am attempting to run some unit tests in python from what I believe is a module. I have a directory structure like TestSuite.py UnitTests |__init__.py |TestConvertStringToNumber.py In testsuite.py I have import unittest import UnitTests class TestSuite: def __init__(self): pass print "Starting testting" suite = unittest.TestLoader().loadTestsFromModule(UnitTests) unittest.TextTestRunner(verbosity=1).run(suite) Which looks to kick off the testing okay but it doesn't pick up any of the test in TestConvertNumberToString.py. In that class I have a set of functions which start with 'test'. What should I be doing such that running python TestSuite.py actually kicks off all of my tests in UnitTests? Answer: Here is some code which will run all the unit tests in a directory: #!/usr/bin/env python import unittest import sys import os unit_dir = sys.argv[1] if len(sys.argv) > 1 else '.' os.chdir(unit_dir) suite = unittest.TestSuite() for filename in os.listdir('.'): if filename.endswith('.py') and filename.startswith('test_'): modname = filename[:-2] module = __import__(modname) suite.addTest(unittest.TestLoader().loadTestsFromModule(module)) unittest.TextTestRunner(verbosity=2).run(suite) If you call it testsuite.py, then you would run it like this: testsuite.py UnitTests
Apache2 + RewriteMap + Python -- when returning 'NULL', apache hangs Question: [SOLVED: See solution below.] I'm having a problem writing a `RewriteMap` program (using Python). I have a `RewriteMap` directive pointing to a Python script which determines if the requested URL needs to be redirected elsewhere. When the script outputs a string terminated by a linebreak, Apache redirects accordingly. However, when the script outputs `NULL` (with no linebreak), Apache hangs and subsequent HTTP requests are effectively ignored. The error log shows no errors. The rewrite log only shows a `pass through` followed by a `redirect` when successful, then only `pass through` when `NULL` is returned by the script. Subsequent requests also only show `pass through`. Additionally, replacing `stdout` with `os.fdopen(sys.stdout.fileno(), 'w', 0)` to set buffer length to zero did not help. Any help would be greatly appreciated. Thank you in advance. ### /etc/apache2/httpd.conf [...] RewriteLock /tmp/apache_rewrite.lock ### /etc/apache2/sites-available/default <VirtualHost *:80> [...] RewriteEngine on RewriteLogLevel 1 RewriteLog /var/www/logs/rewrite.log RewriteMap remap prg:/var/www/remap.py [...] </VirtualHost> ### /var/www/webroot/.htaccess RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteRule (.*_.*) /${remap:$1} [R=301] ### /var/www/remap.py #!/usr/bin/python import sys def getRedirect(str): new_url = None # if url needs to be redirected, put this value in new_url # otherwise new_url remains None return new_url while True: request = sys.stdin.readline().strip() response = getRedirect(request) if response: sys.stdout.write(response + '\n') else: sys.stdout.write('NULL') sys.stdout.flush() Answer: You have to return a single newline, not 'NULL'. Apache waits for a newline to know when the URL to be rewrite to ends. If your script sends no newline, Apache waits forever. So just change `return ('NULL')` to `return ('NULL\n')`, this will then redirect to /. If you don't want this to happen, have the program to return the URL you want when there's no match in the map. If you want not to redirect when there's no match I would: RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond (${remap:$1}) !NULL RewriteRule (.*_.*) /%1 [R=301] Use a match in the RewriteCond (this would work with _NULL_ as well, of course). But given your problem, this looks like the proper solution.
How do I make these relative imports work in Python 3? Question: I have a directory structure that looks like this: project/ __init__.py foo/ __init.py__ first.py second.py third.py plum.py In `project/foo/__init__.py` I import classes from `first.py`, `second.py` and `third.py` and put them in `__all__`. There's a class in `first.py` named `WonderfulThing` which I'd like to use in `second.py`, and want to import by importing `*` from `foo`. (It's outside of the scope of this question why I'd like to do so, assume I have a good reason.) In `second.py` I've tried `from .foo import *`, `from foo import *` and `from . import *` and in none of these cases is `WonderfulThing` imported. I also tried `from ..foo import *`, which raises an error "Attempted relative import beyond toplevel package". I've read the docs and the PEP, and I can't work out how to make this work. Any assistance would be appreciated. **Clarification/Edit:** It seems like I may have been misunderstanding the way `__all__` works in packages. I was using it the same as in modules, from .first import WonderfulThing __all__ = [ "WonderfulThing" ] but looking at the docs again it seems to suggest that `__all__` may only be used in packages to specify the names of modules to be imported by default; there doesn't seem to be any way to include anything that's not a module. Is this correct? **Edit:** A non-wildcard import failed (`cannot import name WonderfulThing`). Trying `from . import foo` failed, but `import foo` works. Unfortunately, `dir(foo)` shows nothing. Answer: Edit: I did misunderstand the question: No `__all__` is not restricted to just modules. One question is why you want to do a relative import. There is nothing wrong with doing `from project.foo import *`, here. Secondly, the `__all__` restriction on foo won't prevent you from doing `from project.foo.first import WonderfulThing`, or just `from .first import WonderfulThing`, which still will be the best way. And if you really want to import a a lot of things, it's probably best to do `from project import foo`, and then use the things with `foo.WonderfulThing` instead for doing an `import *` and then using `WonderfulThing` directly. However to answer your direct question, to import from the `__init__` file in second.py you do this: from . import WonderfulThing or from . import *
edit text file using Python Question: I need to update a text file whenever my IP address changes, and then run a few commands from the shell afterwards. 1. Create variable LASTKNOWN = "212.171.135.53" This is the ip address we have while writing this script. 2. Get the current IP address. It will change on a daily basis. 3. Create variable CURRENT for the new IP. 4. Compare (as strings) CURRENT to LASTKNOWN 5. If they are the same, exit() 6. If they differ, A. "Copy" the old config file (/etc/ipf.conf) containing LASTKNOWN IP address into /tmp B. Replace LASTKNOWN with CURRENT in the /tmp/ipf.conf file. C. Using subprocess "mv /tmp/ipf.conf /etc/ipf.conf" D. Using subprocess execute, "ipf -Fa -f /etc/ipf.conf" E. Using subprocess execute, "ipnat -CF -f /etc/ipnat.conf" 7. exit() I know how to do steps 1 through 6. I fall down on the "file editing" part, A -> C. I can't tell what module to use or whether I should be editing the file in place. There are so many ways to do this, I can't decide on the best approach. I guess I want the most conservative one. I know how to use subprocess, so you don't need to comment on that. I don't want to replace entire lines; just a specific dotted quad. Thanks! Answer: Another way to simply edit files in place is to use the [`fileinput`](http://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CC8QFjAA&url=http%3A%2F%2Fdocs.python.org%2Flibrary%2Ffileinput.html&ei=TGeZUPCRHOfP0QXQhIHAAw&usg=AFQjCNEmKT3Z55eqWRpCJIDCDyy1ACOGhg) module: import fileinput, sys for line in fileinput.input(["test.txt"], inplace=True): line = line.replace("car", "truck") # sys.stdout is redirected to the file sys.stdout.write(line)
Python binary data reading Question: A urllib2 request receives binary response as below: 00 00 00 01 00 04 41 4D 54 44 00 00 00 00 02 41 97 33 33 41 99 5C 29 41 90 3D 71 41 91 D7 0A 47 0F C6 14 00 00 01 16 6A E0 68 80 41 93 B4 05 41 97 1E B8 41 90 7A E1 41 96 8F 57 46 E6 2E 80 00 00 01 16 7A 53 7C 80 FF FF Its structure is: DATA, TYPE, DESCRIPTION 00 00 00 01, 4 bytes, Symbol Count =1 00 04, 2 bytes, Symbol Length = 4 41 4D 54 44, 6 bytes, Symbol = AMTD 00, 1 byte, Error code = 0 (OK) 00 00 00 02, 4 bytes, Bar Count = 2 FIRST BAR 41 97 33 33, 4 bytes, Close = 18.90 41 99 5C 29, 4 bytes, High = 19.17 41 90 3D 71, 4 bytes, Low = 18.03 41 91 D7 0A, 4 bytes, Open = 18.23 47 0F C6 14, 4 bytes, Volume = 3,680,608 00 00 01 16 6A E0 68 80, 8 bytes, Timestamp = November 23,2007 SECOND BAR 41 93 B4 05, 4 bytes, Close = 18.4629 41 97 1E B8, 4 bytes, High = 18.89 41 90 7A E1, 4 bytes, Low = 18.06 41 96 8F 57, 4 bytes, Open = 18.82 46 E6 2E 80, 4 bytes, Volume = 2,946,325 00 00 01 16 7A 53 7C 80, 8 bytes, Timestamp = November 26,2007 TERMINATOR FF FF, 2 bytes, How to read binary data like this? Thanks in advance. ### Update: I tried struct module on first 6 bytes with following code: struct.unpack('ih', response.read(6)) (16777216, 1024) But it should output (1, 4). I take a look at the manual but have no clue what was wrong. Answer: So here's my best shot at interpreting the data you're giving...: import datetime import struct class Printable(object): specials = () def __str__(self): resultlines = [] for pair in self.__dict__.items(): if pair[0] in self.specials: continue resultlines.append('%10s %s' % pair) return '\n'.join(resultlines) head_fmt = '>IH6sBH' head_struct = struct.Struct(head_fmt) class Header(Printable): specials = ('bars',) def __init__(self, symbol_count, symbol_length, symbol, error_code, bar_count): self.__dict__.update(locals()) self.bars = [] del self.self bar_fmt = '>5fQ' bar_struct = struct.Struct(bar_fmt) class Bar(Printable): specials = ('header',) def __init__(self, header, close, high, low, open, volume, timestamp): self.__dict__.update(locals()) self.header.bars.append(self) del self.self self.timestamp /= 1000.0 self.timestamp = datetime.date.fromtimestamp(self.timestamp) def showdata(data): terminator = '\xff' * 2 assert data[-2:] == terminator head_data = head_struct.unpack(data[:head_struct.size]) try: assert head_data[4] * bar_struct.size + head_struct.size == \ len(data) - len(terminator) except AssertionError: print 'data length is %d' % len(data) print 'head struct size is %d' % head_struct.size print 'bar struct size is %d' % bar_struct.size print 'number of bars is %d' % head_data[4] print 'head data:', head_data print 'terminator:', terminator print 'so, something is wrong, since', print head_data[4] * bar_struct.size + head_struct.size, '!=', print len(data) - len(terminator) raise head = Header(*head_data) for i in range(head.bar_count): bar_substr = data[head_struct.size + i * bar_struct.size: head_struct.size + (i+1) * bar_struct.size] bar_data = bar_struct.unpack(bar_substr) Bar(head, *bar_data) assert len(head.bars) == head.bar_count print head for i, x in enumerate(head.bars): print 'Bar #%s' % i print x datas = ''' 00 00 00 01 00 04 41 4D 54 44 00 00 00 00 02 41 97 33 33 41 99 5C 29 41 90 3D 71 41 91 D7 0A 47 0F C6 14 00 00 01 16 6A E0 68 80 41 93 B4 05 41 97 1E B8 41 90 7A E1 41 96 8F 57 46 E6 2E 80 00 00 01 16 7A 53 7C 80 FF FF ''' data = ''.join(chr(int(x, 16)) for x in datas.split()) showdata(data) this emits: symbol_count 1 bar_count 2 symbol AMTD error_code 0 symbol_length 4 Bar #0 volume 36806.078125 timestamp 2007-11-22 high 19.1700000763 low 18.0300006866 close 18.8999996185 open 18.2299995422 Bar #1 volume 29463.25 timestamp 2007-11-25 high 18.8899993896 low 18.0599994659 close 18.4629001617 open 18.8199901581 ...which seems to be pretty close to what you want, net of some output formatting details. Hope this helps!-)
How can I get an accurate UTC time with Python? Question: I wrote a desktop application and was using `datetime.datetime.utcnow()` for timestamping, however I've recently noticed that some people using the application get wildly different results than I do when we run the program at the same time. Is there any way to get the UTC time locally without using urllib to fetch it from a website? Answer: Python depends on the underlying operating system to provide an accurate time- of-day clock. If it isn't doing that, you don't have much choice other than to bypass the o/s. There's a pure-Python implementation of an NTP client [here](http://pypi.python.org/pypi/ntplib/). A very simple-minded approach: >>> import ntplib,datetime >>> x = ntplib.NTPClient() >>> datetime.datetime.utcfromtimestamp(x.request('europe.pool.ntp.org').tx_time) datetime.datetime(2009, 10, 21, 7, 1, 54, 716657) However, it would not be very nice to be continually hitting on other NTP servers out there. A good net citizen would use the ntp client library to keep track of the offset between the o/s system clock and that obtained from the server and only periodically poll to adjust the time.
Python problem executing popen in cron Question: I use `popen` to execute commands in a Python script, and I call it via cron. Cron calls out this script but the behavior isn't the same if I call it by hand. ### Source: from subprocess import Popen, PIPE pp = Popen('/usr/bin/which iptables', shell=True, stdout=PIPE) data = '' for ln in pp.stdout: data = data+ln if data == '': print 'ko' else: print 'ok : '+data ### By hand: # python /home/user/test.py > : /sbin/iptables ### By cron (in /tmp/err_cron): * * * * * /usr/bin/python /home/user/test.py >> /tmp/err_cron ko ko ko Why does cron not run this script normally? Answer: Normally when processes are run from cron, the `PATH` is set to a very restrictive value (the man page for my crontab says `/usr/bin:/bin`). You may need to add: PATH=/usr/bin:/bin:/sbin to the top of your crontab file.
Interacting with SVN from appengine Question: I've got a couple of projects where it would be useful to be able to interact with an SVN server from appengine. * Pull specific files from the svn (fairly easy, since there is a web interface which I can grab the data off automatically, but how do I authenticate) * Commit changes to the svn (this is the really hard/important part) * Possibly run an SVN server (from an appengine app, I'm guessing this isn't possible) I would prefer a python solution, but I can survive with java if I must Answer: you can try using [SVNKit](http://svnkit.com/) with the java runtime
How can I grab the color of a pixel on my desktop? (Linux) Question: I want to grab the color of a pixel with known coordinates on my Linux desktop. Until now, I've used `"import -window SomeWindow -crop 1x1+X+Y /tmp/grab.jpg"` then extracting the pixel value using Python and [PIL](http://en.wikipedia.org/wiki/Python%5FImaging%5FLibrary). This does the job, but since import grabs the whole window before cropping, it's very slow :( Are there any clever way to grab the color of only one pixel? I know both relative (window) and absolute coordinates. A Python or shell script would be preferable, but if you know some clever C/[X11](http://en.wikipedia.org/wiki/X%5FWindow%5FSystem) functions, also please let me know :) Answer: This does the trick, but requires python-gtk: import gtk.gdk import sys def PixelAt(x, y): w = gtk.gdk.get_default_root_window() sz = w.get_size() pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1]) pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1]) pixel_array = pb.get_pixels_array() return pixel_array[y][x] print PixelAt(int(sys.argv[1]), int(sys.argv[2])) On Ubuntu 9.10, this also requires python-numpy or it segfaults the python interpreter on the `get_pixels_array` line. Ubuntu 10.04 it still has this requirement, or it causes an ImportError regarding numpy.core.multiarray.
Load different modules without changing the logic file Question: Suppose I've got 2 different modules which have the uniform(same) interfaces. The files list like this: root/ logic.py sns_api/ __init__.py facebook/ pyfacebook.py __init__.py myspace/ pymyspace.py __init__.py And pyfacebook.py and pymyspace.py have the same interfaces, which means: # in pyfacebook.py class Facebook: def __init__(self, a, b): # do the init def method1(self, a, b, ...): # do the logic # in pymyspace.py class Myspace: def __init__(self, a, b): # do the init def method1(self, a, b, ...): # do the logic Now I have a question. I want to do the logic in logic.py without duplicating the codes, so I'm wondering how can I just set a flag to show which module I use and python will load the right codes automatically, which means: # in logic.py PLATFORM = "facebook" # import the right modules in, complete the logic with the current platform # create the right instance and invoke the right methods Then I change PLATFORM = 'myspace', the logic will work automatically. So how can I do this? I'm wondering whether using the dynamic importing will work, or eval raw python codes, but seems not a good solution. Or if I can make a uniform wrapper in sns_api/__init__.py Anyone can help? Answer: With just two i'd do if platform == 'facebook': from pyfacebook import FaceBook as Platform elif platform == 'myspace': from pymyspace import Myspace as Platform else: raise RuntimeError, "not a valid platform" and use `Platform` in the rest of the code. It's done like this in the library, see the `os` module. You can do really dynamic imports using `name = `[`__import__`](http://docs.python.org/library/functions.html#%5F%5Fimport%5F%5F)`('module')`, but you probably don't need this.
How import Pydev project into interactive console? Question: Newbie question (I'm just getting started with Python and Pydev): I've created a project "Playground" with (standard?) src/root sub-folder. In there I've created example.py. How do I import my "example" module into Pydev's interactive console? ">>> import example" gives: "ImportError: No module named example" Answer: You need to set your PYTHONPATH accordingly (Google search is your friend) or use *.pth in your installation _site-packages_ directory pointing to your project path. Don't forget to set your interpreter details with Pydev (Window->Preferences->Pydev->interpreter).
Storing Images on App Engine using Django Question: I'm trying to upload and save a resized image in a db.BlobProperty field on Google App Engine using Django. the relevant part of my view that process the request looks like this: image = images.resize(request.POST.get('image'), 100, 100) recipe.large_image = db.Blob(image) recipe.put() Which seems like it would be the logical django equivalent of the example in the docs: from google.appengine.api import images class Guestbook(webapp.RequestHandler): def post(self): greeting = Greeting() if users.get_current_user(): greeting.author = users.get_current_user() greeting.content = self.request.get("content") avatar = images.resize(self.request.get("img"), 32, 32) greeting.avatar = db.Blob(avatar) greeting.put() self.redirect('/') (source: <http://code.google.com/appengine/docs/python/images/usingimages.html#Transform>) But, I keep getting an error that says: NotImageError / Empty image data. and refers to this line: image = images.resize(request.POST.get('image'), 100, 100) I'm having trouble getting to the image data. Seems like it's not being uploaded but I can't figure out why. My form has the enctype="multipart/form- data" and all that. I think something's wrong with how I'm referring to the image data. "request.POST.get('image')" but I can't figure out how else to reference it. Any ideas? Thanks in advance. Answer: After some guidance from "hcalves" I figured out the problem. First of all, the default version of Django that comes bundled with App Engine is version 0.96 and how the framework handles uploaded files has changed since then. However in order to maintain compatibility with older apps you have to explicitly tell App Engine to use Django 1.1 like this: from google.appengine.dist import use_library use_library('django', '1.1') You can read more about that [in the app engine docs](http://code.google.com/appengine/docs/python/tools/libraries.html). Ok, so here's the solution: from google.appengine.api import images image = request.FILES['large_image'].read() recipe.large_image = db.Blob(images.resize(image, 480)) recipe.put() Then, to serve the dynamic images back again from the datastore, build a handler for images like this: from django.http import HttpResponse, HttpResponseRedirect def recipe_image(request,key_name): recipe = Recipe.get_by_key_name(key_name) if recipe.large_image: image = recipe.large_image else: return HttpResponseRedirect("/static/image_not_found.png") #build your response response = HttpResponse(image) # set the content type to png because that's what the Google images api # stores modified images as by default response['Content-Type'] = 'image/png' # set some reasonable cache headers unless you want the image pulled on every request response['Cache-Control'] = 'max-age=7200' return response
dynamically adding functions to a Python module Question: Our framework requires wrapping certain functions in some ugly boilerplate code: def prefix_myname_suffix(obj): def actual(): print 'hello world' obj.register(actual) return obj I figured this might be simplified with a decorator: @register def myname(): print 'hello world' However, that turned out to be rather tricky, mainly because the framework looks for a certain pattern of function names at module level. I've tried the following within the decorator, to no avail: current_module = __import__(__name__) new_name = prefix + func.__name__ + suffix # method A current_module[new_name] = func # method B func.__name__ = new_name current_module += func Any help would be appreciated! Answer: use either current_module.new_name = func or setattr(current_module, new_name, func)
Python - RegExp - Modify text files Question: Newbie to Python.... help requested with the following task :-) I have tree of various files, some of them are C source code. I would like to modify these C files with python script. The C code has 4 defines - #define ZR_LOG0(Id, Class, Seveity, Format) #define ZR_LOG1(Id, Class, Seveity, Format, Attr0) #define ZR_LOG2(Id, Class, Seveity, Format, Attr0, Attr1) #define ZR_LOG3(Id, Class, Seveity, Format, Attr0, Attr1, Attr2) there are various ZR_LOGn lines spread throughout the C source code. Example: ZR_LOG1 (1, LOG_CLASS_3, LOG_INFO, "hello world %d", 76); White spaces (spaces, tabs) may appear anywhere in the line (between the fields). The python script task is as follow: 1. Replace any 'Id' field (which is an integer type that we don't care about its original value) with sequential counter. (The first 'LOG'... line we'll encounter the 'Id' field will get the value 0, the next one 1, and so on) 2. In a separate output file, for each ZR_LOG line, we'll create an index line in the format _{ NewId, Format },_ For the example above will get: { 0, "hello world %d" }, Appreciate your help with it.... * * * I have started with the following code, you may either look at it or ignore it altogether. ''' Created on Oct 25, 2009 @author: Uri Shkolnik The following version does find & replace LOG Ids for all C source files in a dir (and below) with sequential counter, The files are assumed to be UTF-8 encoded. (which works fine if they are ASCII, because ASCII is a subset of UTF-8) It also assemble new index file, composed from all new IDs and format fields ''' import os, sys, re, shutil mydir= '/home/uri/proj1' searched_pattern0 = 'ZR_LOG0' def search_and_replace(filepath): ''' replaces all string by a regex substitution ''' backupName=filepath+'~re~' print 'reading:', filepath input = open(filepath,'rb') s=unicode(input.read(),'utf-8') input.close() m = re.match(ur'''[:space:]ZR_LOG[0-3].*\(.*[0-9]{0,10},LOG_''', s) print m def c_files_search(dummy, dirr, filess): ''' search directories for file pattern *.c ''' for child in filess: if '.c' == os.path.splitext(child)[1] and os.path.isfile(dirr+'/'+child): filepath = dirr+'/'+child search_and_replace(filepath) os.path.walk(mydir, c_files_search, 3) Answer: A few points: * You can match whitespace with '\s'. * The regexp 'capturing groups' are useful here. So, I would do something like this: output = '' counter = 1 for line in lines: # Match only ZR_LOG lines and capture everything surrounding "Id" match = re.match('^(.*\sZR_LOG[0-3]\s*\(\s*)' # group(1), before Id 'Id' '(,.*)$', # group(2), after Id line) if match: # Add everything before Id, the counter value and everything after Id output += match.group(1) + str(counter) + match.group(2) counter += 1 # And do extra logging etc. else: output += line
Using the same handler for multiple wx.TextCtrls? Question: I'm having a bit of trouble with a panel that has two wxPython TextCtrls in it. I want either an EVT_CHAR or EVT_KEY_UP handler bound to both controls, and I want to be able to tell which TextCtrl generated the event. I would think that event.Id would tell me this, but in the following sample code it's always 0. Any thoughts? I've only tested this on OS X. This code simply checks that both TextCtrls have some text in them before enabling the Done button import wx class MyFrame(wx.Frame): def __init__(self, parent, ID, title): wx.Frame.__init__(self, parent, ID, title, wx.DefaultPosition, wx.Size(200, 150)) self.panel = BaseNameEntryPanel(self) class BaseNameEntryPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, -1) self.entry = wx.TextCtrl(self, wx.NewId()) self.entry2 = wx.TextCtrl(self, wx.NewId()) self.donebtn = wx.Button(self, wx.NewId(), "Done") self.donebtn.Disable() vsizer = wx.BoxSizer(wx.VERTICAL) vsizer.Add(self.entry, 1, wx.EXPAND|wx.GROW) vsizer.Add(self.entry2, 1, wx.EXPAND|wx.GROW) vsizer.Add(self.donebtn, 1, wx.EXPAND|wx.GROW) self.SetSizer(vsizer) self.Fit() self.entry.Bind(wx.EVT_KEY_UP, self.Handle) self.entry2.Bind(wx.EVT_KEY_UP, self.Handle) def Handle(self, event): keycode = event.GetKeyCode() print keycode, event.Id # <- event.Id is always 0! def checker(entry): return bool(entry.GetValue().strip()) self.donebtn.Enable(checker(self.entry) and checker(self.entry2)) class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, -1, "Hello from wxPython") frame.Show(True) self.SetTopWindow(frame) return True app = MyApp(0) app.MainLoop() Answer: You could try `event.GetId()` or `event.GetEventObject()` and see if either of these work. Another approach to this is to use lambda or functools.partial to effectively pass a parameter to the handler. So, for example, sub in the lines below into your program: self.entry.Bind(wx.EVT_KEY_UP, functools.partial(self.Handle, ob=self.entry)) self.entry2.Bind(wx.EVT_KEY_UP, functools.partial(self.Handle, ob=self.entry2)) def Handle(self, event, ob=None): print ob And then ob will be either `entry` or `entry2` depending on which panel is clicked. But, of course, this shouldn't be necessary, and GetId and GetEventObject() should both work -- though I don't (yet) have a Mac to try these on.
Terminate a multi-thread python program Question: How to make a multi-thread python program response to Ctrl+C key event? **Edit:** The code is like this: import threading current = 0 class MyThread(threading.Thread): def __init__(self, total): threading.Thread.__init__(self) self.total = total def stop(self): self._Thread__stop() def run(self): global current while current<self.total: lock = threading.Lock() lock.acquire() current+=1 lock.release() print current if __name__=='__main__': threads = [] thread_count = 10 total = 10000 for i in range(0, thread_count): t = MyThread(total) t.setDaemon(True) threads.append(t) for i in range(0, thread_count): threads[i].start() I tried to remove join() on all threads but it still doesn't work. Is it because the lock segment inside each thread's run() procedure? **Edit:** The above code is supposed to work but it always interrupted when current variable was in 5,000-6,000 range and through out the errors as below Exception in thread Thread-4 (most likely raised during interpreter shutdown): Traceback (most recent call last): File "/usr/lib/python2.5/threading.py", line 486, in __bootstrap_inner File "test.py", line 20, in run <type 'exceptions.TypeError'>: unsupported operand type(s) for +=: 'NoneType' and 'int' Exception in thread Thread-2 (most likely raised during interpreter shutdown): Traceback (most recent call last): File "/usr/lib/python2.5/threading.py", line 486, in __bootstrap_inner File "test.py", line 22, in run Answer: Make every thread except the main one a daemon (`t.daemon = True` in 2.6 or better, `t.setDaemon(True)` in 2.6 or less, for every thread object `t` before you start it). That way, when the main thread receives the KeyboardInterrupt, if it doesn't catch it or catches it but decided to terminate anyway, the whole process will terminate. See [the docs](http://docs.python.org/library/threading.html?highlight=daemon#threading.Thread.daemon). **edit** : having just seen the OP's code (not originally posted) and the claim that "it doesn't work", it appears I have to add...: Of course, if you want your main thread to stay responsive (e.g. to control-C), don't mire it into blocking calls, such as `join`ing another thread -- especially not totally _useless_ blocking calls, such as `join`ing **daemon** threads. For example, just change the final loop in the main thread from the current (utterless and damaging): for i in range(0, thread_count): threads[i].join() to something more sensible like: while threading.active_count() > 0: time.sleep(0.1) if your main has nothing better to do than either for all threads to terminate on their own, or for a control-C (or other signal) to be received. Of course, there are many other usable patterns if you'd rather have your threads not terminate abruptly (as daemonic threads may) -- unless _they_ , too, are mired forever in unconditionally-blocking calls, deadlocks, and the like;-).
Unable to query from entities loaded onto the app engine datastore Question: I am a newbie to python. I am not able to query from the entities- UserDetails and PhoneBook I loaded to the app engine datastore. I have written this UI below based on the youtube video by Brett on "Developing and Deploying applications on GAE" -- shoutout application. Well I just tried to do some reverse engineering to query from the datastore but failed in every step. #!/usr/bin/env python import wsgiref.handlers from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import template import models class showPhoneBook(db.Model): """ property to store user_name from UI to persist for the session """ user_name = db.StringProperty(required=True) class MyHandler(webapp.RequestHandler): def get(self): ## Query to get the user_id using user_name retrieved from UI ## p = UserDetails.all().filter('user_name = ', user_name) result1 = p.get() for itr1 in result1: userId = itr.user_id ## Query to get the phone book contacts using user_id retrieved ## q = PhoneBook.all().filter('user_id = ', userId) values = { 'phoneBookValues': q } self.request.out.write( template.render('phonebook.html', values)) def post(self): phoneBookuser = showPhoneBook( user_name = self.request.get('username')) phoneBookuser.put() self.redirect('/') def main(): app = webapp.WSGIApplication([ (r'.*',MyHandler)], debug=True) wsgiref.handlers.CGIHandler().run(app) if __name__ == "__main__": main() This is my models.py file where I've defined my UserDetails and PhoneBook classes, #!/usr/bin/env python from google.appengine.ext import db #Table structure of User Details table class UserDetails(db.Model): user_id = db.IntegerProperty(required = True) user_name = db.StringProperty(required = True) mobile_number = db.PhoneNumberProperty(required = True) #Table structure of Phone Book table class PhoneBook(db.Model): contact_id = db.IntegerProperty(required=True) user_id = db.IntegerProperty(required=True) contact_name = db.StringProperty(required=True) contact_number = db.PhoneNumberProperty(required=True) Here are the problems I am facing, 1) I am not able to call `user_name` (retrieved from UI-- `phoneBookuser = showPhoneBook(user_name = self.request.get('username'))`) in get(self) method for querying UserDetails to to get the corresponding `user_name`. 2) The code is not able to recognize UserDetails and PhoneBook classes when importing from models.py file. 3) I tried to define UserDetails and PhoneBook classes in the main.py file itself, them I get the error at `result1 = p.get()` saying `BadValueError: Unsupported type for property : <class 'google.appengine.ext.db.PropertiedClass'>` I have been struggling since 2 weeks to get through the mess I am into but in vain. Please help me out in straightening out my code('coz I feel what I've written is a error-prone code all the way). Answer: I recommend that you read the Python documentation of GAE found [here](http://code.google.com/appengine/docs/python/gettingstarted/). Some comments: 1. To use your models found in `models.py`, you either need to use the prefix `models.` (e.g. `models.UserDetails`) or import them using from models import * 2. in `MyHandler.get()` you don't lookup the `username` get parameter 3. To fetch values corresponding to a query, you do `p.fetch(1)` not `p.get()` 4. You should also read [Reference properties in GAE](http://code.google.com/appengine/docs/python/datastore/entitiesandmodels.html#References) as well. I recommend you having your models as: class UserDetails(db.Model): user_name = db.StringProperty(required = True) mobile_number = db.PhoneNumberProperty(required = True) #Table structure of Phone Book table class PhoneBook(db.Model): user = db.ReferenceProperty(UserDetails) contact_name = db.StringProperty(required=True) contact_number = db.PhoneNumberProperty(required=True) Then your `MyHandler.get()` code will look like: def get(self): ## Query to get the user_id using user_name retrieved from UI ## user_name = self.request.get('username') p = UserDetails.all().filter('user_name = ', user_name) user = p.fetch(1)[0] values = { 'phoneBookValues': user.phonebook_set } self.response.out.write(template.render('phonebook.html', values)) (Needless to say, you need to handle the case where the username is not found in the database) 5. I don't quite understand the point of `showPhoneBook` model.