text
stringlengths
226
34.5k
How do I have python httplib accept untrusted certs? Question: How do I have python httplib accept untrusted certs? I created a snake oil/self signed cert on my webserver, and my python client fails to connect as I am using a untrusted cert. I'd rather problematically fix this in my client code rather than have it trusted on my system. import httplib def main(): conn = httplib.HTTPSConnection("127.0.0.1:443") conn.request("HEAD","/") res = conn.getresponse() print res.status, res.reason data = res.read() print len(data) if __name__ == "__main__": main() Answer: Some of my scripts stopped working after updating my computer. Turns out, this was the problem: <https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection> > Changed in version 2.7.9: context was added. > > This class now performs all the necessary certificate and hostname checks by > default. To revert to the previous, unverified, behavior > ssl._create_unverified_context() can be passed to the context parameter. So if your version of Python is >= 2.7.9 (2.7.10 in my case), you'll likely run into this. To fix it, I updated my call: httplib.HTTPSConnection(hostname, timeout=5, context=ssl._create_unverified_context()) This is likely the simplest change to retain the same behavior.
Link generator using django or any python module Question: I want to generate for my users temporary download link. Is that ok if i use django to generate link using url patterns? Could it be correct way to do that. Because can happen that I don't understand some processes how it works. And it will overflow my memory or something else. Some kind of example or tools will be appreciated. Some nginx, apache modules probably? So, what i wanna to achieve is to make url pattern which depend on user and time. Decript it end return in view a file. Answer: A simple scheme might be to use a hash digest of username and timestamp: from datetime import datetime from hashlib import sha1 user = 'bob' time = datetime.now().isoformat() plain = user + '\0' + time token = sha1(plain) print token.hexdigest() "1e2c5078bd0de12a79d1a49255a9bff9737aa4a4" Next you store that token in a memcache with an expiration time. This way any of your webservers can reach it and the token will auto-expire. Finally add a Django url handler for '^download/.+' where the controller just looks up that token in the memcache to determine if the token is valid. You can even store the filename to be downloaded as the token's value in memcache.
Image aspect ratio using Reportlab in Python Question: I want to insert an image inside a frame. I found two ways to do this: 1. drawImage(self, image, x, y, width=None, height=None, mask=None, preserveAspectRatio=False, anchor='c') 2. Image(filename, width=None, height=None) My question is: how can I add an image in a frame while preserving its aspect ratio? from reportlab.lib.units import cm from reportlab.pdfgen.canvas import Canvas from reportlab.platypus import Frame, Image c = Canvas('mydoc.pdf') frame = Frame(1*cm, 1*cm, 19*cm, 10*cm, showBoundary=1) """ If I have a rectangular image, I will get a square image (aspect ration will change to 8x8 cm). The advantage here is that I use coordinates relative to the frame. """ story = [] story.append(Image('myimage.png', width=8*cm, height=8*cm)) frame.addFromList(story, c) """ Aspect ration is preserved, but I can't use the frame's coordinates anymore. """ c.drawImage('myimage.png', 1*cm, 1*cm, width=8*cm, preserveAspectRatio=True) c.save() Answer: You can use the original image's size to calculate its aspect ratio, then use that to scale your target width, height. You can wrap this up in a function to make it reusable: from reportlab.lib import utils def get_image(path, width=1*cm): img = utils.ImageReader(path) iw, ih = img.getSize() aspect = ih / float(iw) return Image(path, width=width, height=(width * aspect)) story = [] story.append(get_image('stack.png', width=4*cm)) story.append(get_image('stack.png', width=8*cm)) frame.addFromList(story, c) Example using a 248 x 70 pixel stack.png: ![enter image description here](http://i.stack.imgur.com/0EN8O.png)
python-Twitter-api Question: import twitter client = twitter.Api() client = twitter.Api(username='uname', password='password') update = client.PostUpdate('Tweetin from python!') This is my code. When i execute this program i get this error TypeError: __init__() got an unexpected keyword argument 'username' Can someone help me? Answer: take a look at this tutorial [Twitter From the Command Line in Python Using OAuth](http://jeffmiller.github.com/2010/05/31/twitter-from-the-command-line- in-python-using-oauth)
SQLAlchemy IntegrityError Question: I'm having a problem using SQLAlchemy with PySide(PyQt). I'm trying to pop-up a `QtGui.QDialog`, but when I do this SQLAlchemy throws an exception: Traceback (most recent call last): File "C:\Python27\lib\site-packages\preo\preodb\dbviewandmodel.py", line 32, in rowCount return len(self.rows()) File "C:\Python27\lib\site-packages\preo\preodb\dbviewandmodel.py", line 30, in rows return self.tableobj.query.all() File "C:\Python27\lib\site-packages\sqlalchemy-0.6.6-py2.7.egg\sqlalchemy\orm\query.py", line 1579, in all return list(self) File "C:\Python27\lib\site-packages\sqlalchemy-0.6.6-py2.7.egg\sqlalchemy\orm\query.py", line 1688, in __iter__ self.session._autoflush() File "C:\Python27\lib\site-packages\sqlalchemy-0.6.6-py2.7.egg\sqlalchemy\orm\session.py", line 862, in _autoflush self.flush() File "C:\Python27\lib\site-packages\sqlalchemy-0.6.6-py2.7.egg\sqlalchemy\orm\session.py", line 1388, in flush self._flush(objects) File "C:\Python27\lib\site-packages\sqlalchemy-0.6.6-py2.7.egg\sqlalchemy\orm\session.py", line 1469, in _flush flush_context.execute() File "C:\Python27\lib\site-packages\sqlalchemy-0.6.6-py2.7.egg\sqlalchemy\orm\unitofwork.py", line 302, in execute rec.execute(self) File "C:\Python27\lib\site-packages\sqlalchemy-0.6.6-py2.7.egg\sqlalchemy\orm\unitofwork.py", line 446, in execute uow File "C:\Python27\lib\site-packages\sqlalchemy-0.6.6-py2.7.egg\sqlalchemy\orm\mapper.py", line 1878, in _save_obj execute(statement, params) File "C:\Python27\lib\site-packages\sqlalchemy-0.6.6-py2.7.egg\sqlalchemy\engine\base.py", line 1191, in execute params) File "C:\Python27\lib\site-packages\sqlalchemy-0.6.6-py2.7.egg\sqlalchemy\engine\base.py", line 1271, in _execute_clauseelement return self.__execute_context(context) File "C:\Python27\lib\site-packages\sqlalchemy-0.6.6-py2.7.egg\sqlalchemy\engine\base.py", line 1302, in __execute_context context.parameters[0], context=context) File "C:\Python27\lib\site-packages\sqlalchemy-0.6.6-py2.7.egg\sqlalchemy\engine\base.py", line 1401, in _cursor_execute context) File "C:\Python27\lib\site-packages\sqlalchemy-0.6.6-py2.7.egg\sqlalchemy\engine\base.py", line 1394, in _cursor_execute context) File "C:\Python27\lib\site-packages\sqlalchemy-0.6.6-py2.7.egg\sqlalchemy\engine\default.py", line 299, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.IntegrityError: (IntegrityError) ('23000', "[23000] [Microsoft][ODBC SQL Server Driver][SQL Server]Violation of UNIQUE KEY constraint 'UQ__users__F3DBC5720DAF0CB0'. Cannot insert duplicate key in object 'dbo.users'. (2627) (SQLExecDirectW); [01000] [Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been terminated. (3621)") u'INSERT INTO users (username, fullname, email, passwordmd5) OUTPUT inserted.id VALUES (?, ?, ?, ?)' (None, None, None, None) This is particularly troubling because I have no code, anywhere, that even attempts to insert records into SQL; I am only ever attempting to query data from the database. In fact, my DB model is read-only with respect to what PySide/PyQt are doing (i.e., I'm using a `QtGui.QTableView` model/view and there is no `insertRows` function in that model). I have no idea what's going on or how to solve it - again, I have no code to modify SQL records at all, but still SQLAlchemy attempts to be inserting blank records into one of my SQL tables. All I can see, in the background, is the `QTableView` data model is querying the database A LOT. It just seems that when I popup this `QDialog` (which does have some code in it to query some table column) this error is thrown. Oddly, this isn't consistent, sometime the popup appears first before the exception, sometimes the popup appears after the exception. Under normal circumstances, the `QTableView` data model works great, just not when I popup this dialog (and ironically, the popup isn't using any `QTableView` at all, just standard widgets like QLineEdit, QTextEdit, etc.) If it helps, I'm using Python 2.7 with SQLAlchemy 0.6.6 (also with Elixir 0.7.1), and PySide 1.0.0 (and PyQt4 4.8.3). I'm on Windows 7 using SQL 2008 R2 (Express). And yes, I've tried rebooting the PC, but the problem still occurs after a reboot. I'm reluctant to post more code because I have a lot of it in this particular project and I can't nail down the problem anything specific. I'm hoping someone might know of oddities in SQLAlchemy and/or PyQt that might be related to this. I'm also hoping I can continue using SQLAlchemy as I have a large data model built; I'm reluctant, at this point, to abandon this and use PyQt's SQL features. Answer: I've managed to make this problem go away, but it's still not really clear to me why SQLAlchemy was trying to insert rows in my database - that really bothers me, but it's not happening anymore. At any rate, what was, I think, happening, was related to my SQLAlchemy data model and the way I was accessing it, here is a snippet of that model: from elixir import * metadata.bind = 'mssql+pyodbc://username:password/dbname' metadata.bind.echo = False class Users(Entity): using_options(tablename = 'users') username = Field(String(50), unique=True) fullname = Field(String(255)) email = Field(String(255)) passwordmd5 = Field(String(32)) def __repr__(self): return "<Users ({})({})({})>".format(self.username, self.fullname, self.email) def prettyname(self): return {'username':'User Name', 'fullname':'Full Name', 'email':'Email Address', 'passwordmd5':'$hidden$'} In my code I needed a way of getting 'pretty' label names for a GUI without having to hard code this in a GUI (I've been trying to create a dynamic way of building GUI forms). So, I added the 'prettyname' method to my data model to give me some application specific metadata in that data model. All I'm doing is returning a dictionary of items. I had a secondary problem in that sometimes I needed to get this data from the class instance for Users and sometimes for a query result for Users (for example, Users.get_by(id=1)). As it turned out, retrieving this data had to be done in two ways. In the class instances I had to get the value this way: prettyname = Users().prettyname()['username'] But when I was using query results it was: prettyname = queryresult.prettyname()['username'] SQLAlchemy seems to have a real problem when I was using the former method (the class instance method) - as this was being used everytime I was seeing the crash. When I was using the latter instance I was never seeing a crash. Still, I needed access to that metadata in the class instance. The fix, or should I say what turned out to fix this came from another Stackoverflow article (thank you everyone at Stackoverflow - I'd be nothing without you). I changed the structure of the dbmodel: class Users(Entity): using_options(tablename = 'users') username = Field(String(50), unique=True, info={'prettyname':'User Name'}) fullname = Field(String(255), info={'prettyname':'Full Name'}) email = Field(String(255), info={'prettyname':'Email Address'}) passwordmd5 = Field(String(32), info={'hidden':True}) def __repr__(self): return "<Users ({})({})({})>".format(self.username, self.fullname, self.email) This allows me to use a common method of introspection to get the dictionary data in the info argument, regardless if I'm looking at a class instance, or a query result. In this case I use the '.table' method of either the class or query result, then get the column that I need (.c), then use the .info method of that column to return the dictionary. Whatever the case, now SQLAlchemy no longer tries to arbitrarily insert rows in the database anymore.
Python: how to know function return type and argument types? Question: While I am aware of the duck-typing concept of Python, I sometimes struggle with the type of arguments of functions, or the type of the return value of the function. Now, if I wrote the function myself, I DO know the types. But what if somebody wants to use and call my functions, how is he/she expected to know the types? I usually put type information in the function's docstring (like: `"...the id argument should be an integer..."` and `"... the function will return a (string, [integer]) tuple."`) But is looking up the information in the docstring (and putting it there, as a coder) really the way it is supposed to be done? **Edit:** While the majority of answers seem to direct towards "yes, document!" I feel this is not always very easy for 'complex' types. For example: how to describe _concisely_ in a docstring that a function returns a list of tuples, with each tuple of the form (node_id, node_name, uptime_minutes) and that the elements are respectively a string, string and integer? The docstring PEP documentation doesn't give any guidelines on that. I guess the counterargument will be that in that case classes should be used, but I find python very flexible because it allows passing around these things using lists and tuples, i.e. _without_ classes. Answer: This is how dynamic languages work. It is not always a good thing though, especially if the documentation is poor - anyone tried to use a poorly documented python framework? Sometimes you have to revert to reading the source. Here are some strategies to avoid problems with duck typing: * create a language for your problem domain * this will help you to name stuff properly * use types to represent concepts in your domain language * name function parameters using the domain language vocabulary Also, one of the most important points: * **keep data as local as possible!** There should only be a few well-defined and documented types being passed around. Anything else should be obvious by looking at the code: Don't have weird parameter types coming from far away that you can't figure out by looking in the vicinity of the code... Related, (and also related to docstrings), there is a technique in python called `doctests`. Use that to document how your methods are expected to be used - and have nice unit test coverage at the same time!
How can I get a file's permission mask? Question: How can I get a file's permission mask like 644 or 755 on *nix using python? Is there any function or class for doing that? Could you guys help me out? Thank you very much! Answer: `os.stat` is a wrapper around the [stat(2)](http://linux.die.net/man/2/stat) system call interface. >>> import os >>> from stat import * >>> os.stat("test.txt") # returns 10-tupel, you really want the 0th element ... posix.stat_result(st_mode=33188, st_ino=57197013, \ st_dev=234881026L, st_nlink=1, st_uid=501, st_gid=20, st_size=0, \ st_atime=1300354697, st_mtime=1300354697, st_ctime=1300354697) >>> os.stat("test.txt")[ST_MODE] # this is an int, but we like octal ... 33188 >>> oct(os.stat("test.txt")[ST_MODE]) '0100644' From here you'll recognize the typical octal permissions. S_IRWXU 00700 mask for file owner permissions S_IRUSR 00400 owner has read permission S_IWUSR 00200 owner has write permission S_IXUSR 00100 owner has execute permission S_IRWXG 00070 mask for group permissions S_IRGRP 00040 group has read permission S_IWGRP 00020 group has write permission S_IXGRP 00010 group has execute permission S_IRWXO 00007 mask for permissions for others (not in group) S_IROTH 00004 others have read permission S_IWOTH 00002 others have write permission S_IXOTH 00001 others have execute permission You are really only interested in the lower _bits_ , so you could chop off the rest: >>> oct(os.stat("test.txt")[ST_MODE])[-3:] '644' >>> # or better >>> oct(os.stat("test.txt").st_mode & 0777) * * * Sidenote: the upper parts determine the filetype, e.g.: S_IFMT 0170000 bitmask for the file type bitfields S_IFSOCK 0140000 socket S_IFLNK 0120000 symbolic link S_IFREG 0100000 regular file S_IFBLK 0060000 block device S_IFDIR 0040000 directory S_IFCHR 0020000 character device S_IFIFO 0010000 FIFO S_ISUID 0004000 set UID bit S_ISGID 0002000 set-group-ID bit (see below) S_ISVTX 0001000 sticky bit (see below)
Why is Paramiko raising EOFError() when the SFTP object is stored in a dictionary? Question: I'm having trouble with an application I'm writing that downloads and uploads files to and from other boxes via SSH. The issue I'm experiencing is that I can get (download) files just fine but when I try to put (upload) them onto another server I get an EOFError() exception. When I looked at _write_all() in paramiko\sftp.py it seemed like the error was caused when it couldn't write any data to the stream? I have no network programming experience so if someone knows what it's trying to do and could communicate that to me I'd appreciate it. I wrote a simplified version of the function that handles my connections as ssh(). runCommand() shows how the upload is failing in my application while simpleTest() shows how sftp put does work, but I can't see any difference between runCommand() and simpleTest() other than how my SFTP objects are being stored. One is stored in a dictionary and the other by itself. It seems like if the dictionary was the problem that downloading files wouldn't work but that is not the case. Does anyone know what could cause this behavior or could recommend another way to manage my connections if this way is causing problems? I'm using Python 2.7 with Paramiko 1.7.6. I've tested this code on both Linux and Windows and got the same results. **EDIT: code included now.** import os import paramiko class ManageSSH: """Manages ssh connections.""" def __init__(self): self.hosts = {"testbox": ['testbox', 'test', 'test']} self.sshConnections = {} self.sftpConnections = {} self.localfile = "C:\\testfile" self.remotefile = "/tmp/tempfile" self.fetchedfile = "C:\\tempdl" def ssh(self): """Manages ssh connections.""" for host in self.hosts.keys(): try: self.sshConnections[host] print "ssh connection is already open for %s" % host except KeyError, e: # if no ssh connection for the host exists then open one # open ssh connection ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(self.hosts[host][0], 22, self.hosts[host][1], self.hosts[host][2]) self.sshConnections[host] = ssh print "ssh connection to %s opened" % host try: self.sftpConnections[host] print "sftp connection is already open for %s" % host except KeyError, e: # open sftp connection ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(self.hosts[host][0], 22, self.hosts[host][1], self.hosts[host][2]) self.sftpConnections[host] = ssh.open_sftp() print "sftp connection to %s opened" % host def runCommand(self): """run commands and return output""" for host in self.hosts: command = "if [ -d /tmp ]; then echo -n 1; else echo -n 0; fi" stdin, stdout, stderr = self.sshConnections[host].exec_command(command) print "%s executed on %s" % (command, host) print "returned %s" % stdout.read() self.sftpConnections.get(self.remotefile, self.fetchedfile) print "downloaded %s from %s" % (self.remotefile, host) self.sftpConnections[host].put(self.localfile, self.remotefile) print "uploaded %s to %s" % (self.localfile, host) self.sftpConnections[host].close() self.sshConnections[host].close() def simpleTest(self): host = "testbox" ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, 22, 'test', 'test') sftp = ssh.open_sftp() print "sftp connection to %s opened" % host sftp.get(self.remotefile, self.fetchedfile) print "downloaded %s from %s" % (self.localfile, host) sftp.put(self.localfile, self.remotefile) print "uploaded %s to %s" % (self.localfile, host) sftp.close() if __name__ == "__main__": test = ManageSSH() print "running test that works" test.simpleTest() print "running test that fails" test.ssh() test.runCommand() output: running test that works sftp connection to testbox opened downloaded C:\testfile from testbox uploaded C:\testfile to testbox running test that fails ssh connection to testbox opened sftp connection to testbox opened if [ -d /tmp ]; then echo -n 1; else echo -n 0; fi executed on testbox returned 1 downloaded /tmp/tempfile from testbox Traceback (most recent call last): File "paramikotest.py", line 71, in <module> test.runCommand() File "paramikotest.py", line 47, in runCommand self.sftpConnections[host].put(self.localfile, self.remotefile) File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 561, in put fr = self.file(remotepath, 'wb') File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 245, in open t, msg = self._request(CMD_OPEN, filename, imode, attrblock) File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 627, in _request num = self._async_request(type(None), t, *arg) File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 649, in _async_request self._send_packet(t, str(msg)) File "C:\Python27\lib\site-packages\paramiko\sftp.py", line 172, in _send_packet self._write_all(out) File "C:\Python27\lib\site-packages\paramiko\sftp.py", line 138, in _write_all raise EOFError() EOFError Answer: I was able to resolve my issue. I was supposed to be using Paramiko.Transport and then creating the SFTPClient with Paramiko.SFTPClient.from_transport(t) instead of using open_sftp() from SSHClient(). The following code works: t = paramiko.Transport((host, 22)) t.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(t)
Memory issues with as.dist function in R/rpy2 Question: I'm trying to perform a hierarchical clustering using a custom distance measure. I perform all the calculations in Python and then pass the data structures to R to do the clustering import rpy2.robjects as robjects r=robjects.r from rpy2.robjects.packages import importr stats = importr('stats') m = r.matrix(robjects.FloatVector(list_of_data), ncol=size, byrow=True) dist_mat=stats.as_dist(m) hc=stats.hclust(new_dist_mat) So my distance measures are held in a Python list, converted to an R matrix, which is then converted into a `dist` object required for the clustering. This works to an extent. However, when the matrix becomes too big and I get this error: python(18944,0xb0081000) malloc: *** mmap(size=168898560) failed (error code=12) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug Error: cannot allocate vector of size 161.1 Mb This occurs at the point where I convert to a `dist` object (`as.dist`). I haven't tested at what size it falls apart, but it works with 3000x3000 matrix, but fails with a 6500x6500 matrix, so somewhere in-between. I'm using the `del` function in Python to try remove any unnecessary objects from memory, but from what I've read this doesn't guarantee that the memory will become immediately available for use. So, ultimately, is there a more memory efficient way to get a `dist` object? Or is there perhaps an alternative method I could use? I've found some other methods in R's `cluster` library, which do not use a `dist` object, but these methods use built-in distance metrics. Thanks in advance! Answer: Calling Python's del() does not guarantee that the memory is becoming immediately available for use. Calling the garbage collector explicitly helps. The answer to an other question here ([Clearing memory used by rpy2](http://stackoverflow.com/questions/5199334/clearing-memory-used-by-rpy2 "Clearing memory used by rpy2")) points to the relevant section in the rpy2 documentation. Regarding clustering algorithms hierachical clustering with hclust() does require a "distance" matrix (of size n * (n + 1) / 2 ; R saves a bit of memory since the matrix is symetrical). There exists other clustering algorithms, or if keen on hierachical clustering tricks to minimize the size of the starting matrix by creating initial blocks, but that's outside the scope of a programming-related question.
Read-write pipe() communication in R Question: Most languages support two-way process communication. For example, in Python, I can (sloppily) do: >>> from subprocess import * >>> p = Popen('nslookup', stdin=PIPE, stdout=PIPE) >>> p_stdin, p_stdout = p.communicate("www.google.com") >>> print p_stdin Server: ... In R, I can only seem to go one way, regardless of whether I open my pipe with "r+" or "w+". Furthermore, even if I run a script via `R -f ...` or `R < ...`, weird behavior ensues in the actual console stdin/stdout. My question boils down to the following - is it possible (without writing a C method!) to reproduce the two-way process communication in the above Python example in R? Answer: One way to do it on UNIX-like systems would be to open a pipe to a process that is redirecting `stdout` and `stderr` to a fifo: # Setup system('mkfifo output.fifo') p_out <- fifo('output.fifo', 'r') p_in <- pipe('pdflatex &> output.fifo', 'w') # See what TeX said on startup readLines(p_out) [1] "This is pdfTeX, Version 3.1415926-1.40.11 (TeX Live 2010)" readLines(p_out) character(0) # TeX has nothing more to say # Tell TeX to do something writeLines('\\documentclass{article}', p_in) flush(p_in) # See what it said in response readLines(p_out) [1] "**entering extended mode" [2] "LaTeX2e <2009/09/24>" [3] "Babel <v3.8l> and hyphenation patterns for english, dumylang, nohyphenation, ba" [4] "sque, danish, dutch, finnish, french, german, ngerman, swissgerman, hungarian, " [5] "italian, bokmal, nynorsk, polish, portuguese, spanish, swedish, loaded." [6] "" Unfortunately, `fifo` isn't supported on Windows.
Python regex: matching a parenthesis within parenthesis Question: I've been trying to match the following string: string = "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))" But unfortunately my knowledge of regular expressions is very limited, as you can see there are two parentheses that need to be matched, along with the content inside the second one I tried using `re.match("\(w*\)", string)` but it didn't work, any help would be greatly appreciated. Answer: Try this: import re w = "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))" # find outer parens outer = re.compile("\((.+)\)") m = outer.search(w) inner_str = m.group(1) # find inner pairs innerre = re.compile("\('([^']+)', '([^']+)'\)") results = innerre.findall(inner_str) for x,y in results: print "%s <-> %s" % (x,y) **Output:** index.html <-> home base.html <-> base **Explanation:** `outer` matches the first-starting group of parentheses using `\(` and `\)`; by default `search` finds the longest match, giving us the outermost `( )` pair. The match `m` contains exactly what's between those outer parentheses; its content corresponds to the `.+` bit of `outer`. `innerre` matches exactly one of your `('a', 'b')` pairs, again using `\(` and `\)` to match the content parens in your input string, and using two groups inside the `' '` to match the strings inside of those single quotes. Then, we use `findall` (rather than `search` or `match`) to get all matches for `innerre` (rather than just one). At this point `results` is a list of pairs, as demonstrated by the print loop. **Update:** To match the whole thing, you could try something like this: rx = re.compile("^TEMPLATES = \(.+\)") rx.match(w)
How to split a list into pairs in all possible ways Question: I have a list (say 6 elements for simplicity) L = [0, 1, 2, 3, 4, 5] and I want to chunk it into pairs in **ALL** possible ways. I show some configurations: [(0, 1), (2, 3), (4, 5)] [(0, 1), (2, 4), (3, 5)] [(0, 1), (2, 5), (3, 4)] and so on. Here `(a, b) = (b, a)` and the order of pairs is not important i.e. [(0, 1), (2, 3), (4, 5)] = [(0, 1), (4, 5), (2, 3)] The total number of such configurations is `1*3*5*...*(N-1)` where `N` is the length of my list. How can I write a generator in Python that gives me all possible configurations for an arbitrary `N`? Answer: Take a look at [`itertools.combinations`](http://docs.python.org/library/itertools.html#itertools.combinations). matt@stanley:~$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import itertools >>> list(itertools.combinations(range(6), 2)) [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
Altering python-gearman worker tasks during job processing Question: I'm attempting to change the tasks available on a python-gearman worker during its work cycle. My reason for doing this is to allow me a little bit of control over my worker processes and allowing them to reload from a database. I need every worker to reload at regular intervals, but I don't want to simply kill the processes, and I want the service to be constantly available which means that I have to reload in batches. So I would have 4 workers reloading while another 4 workers are available to process, and then reload the next 4 workers. Process: 1. Start reload process 4 times. 1. unregister the `reload` process 2. reload the dataset 3. register a `finishReload` task 4. return 2. Repeat step 1 until there are no workers with the `reload` task registered. 3. Start `finishReload`(1) task until there are no workers with the `finishReload` task available. (1) the finishReload task unregisters the `finishReload` task and registers the `reload` task and then returns. Now, the problem that I'm running into is that the job fails when I change the tasks that are available to the worker process. There are no error messages or exceptions, just an "ERROR" in the gearmand log. Here's a quick program that replicates the problem. ## WORKER import gearman def reversify(gmWorker, gmJob): return "".join(gmJob.data[::-1]) def strcount(gmWorker, gmJob): gmWorker.unregister_task('reversify') # problem line return str(len(gmJob.data)) worker = gearman.GearmanWorker(['localhost:4730']) worker.register_task('reversify', reversify) worker.register_task('strcount', strcount) while True: worker.work() ## CLIENT import gearman client = gearman.GearmanClient(['localhost:4730']) a = client.submit_job('reversify', 'spam and eggs') print a.result >>> sgge dna maps a = client.submit_job('strcount', 'spam and eggs') ... Please let me know if there are anything things that I can elucidate. EDIT: I know that someone will ask to see the log I mentioned. I've posted this question to the gearman group on Google as well, and [log is available there](http://groups.google.com/group/gearman/browse_thread/thread/9987337cae4adf52). Answer: It looks like subclassing the GearmanWorker class and adding a few flags can work around this issue. I need to allow the job to complete before I start issuing new commands from the worker to the server, which seems to interrupt the current job. So if we overwrite the `on_job_complete` function we can check for the enable/disable flag and act on those after we issue the `send_job_complete` command. The new worker program follows: WORKER import gearman def reversify(gmWorker, gmJob): return "".join(gmJob.data[::-1]) def enable_reversify(gmWorker, gmJob): myWorker.enableReversify = 1 return 'OK' def strcount(gmWorker, gmJob): myWorker.enableReversify = -1 return str(len(gmJob.data)) class myWorker(gearman.GearmanWorker): enableReversify = 0 # 0 = do nothing, -1 = turn off, 1 = turn on def on_job_complete(self, current_job, job_result): self.send_job_complete(current_job, job_result) ### check the flag here and enable or disable tasks ### if myWorker.enableReversify == -1: self.unregister_task('reversify') if myWorker.enableReversify == 1: self.register_task('reversify', reversify) myWorker.enableReversify = 0 # reset the flag return True worker = myWorker(['localhost:4730']) worker.register_task('reversify', reversify) worker.register_task('strcount', strcount) worker.register_task('enableReversify', enable_reversify) while True: worker.work()
Reloading submodules in IPython Question: Currently I am working on a python project that contains sub modules and uses numpy/scipy. Ipython is used as interactive console. Unfortunately I am not very happy with workflow that I am using right now, I would appreciate some advice. In IPython, the framework is loaded by a simple `import` command. However, it is often necessary to change code in one of the submodules of the framework. At this point a model is already loaded and I use IPython to interact with it. Now, the framework contains many modules that depend on each other, i.e. when the framework is initially loaded the main module is importing and configuring the submodules. The changes to the code are only executed if the module is reloaded using `reload(main_mod.sub_mod)`. This is cumbersome as I need to reload all changed modules individually using the full path. It would be very convenient if `reload(main_module)` would also reload all sub modules, but without reloading numpy/scipy.. Answer: IPython comes with some automatic reloading magic: %load_ext autoreload %autoreload 2 It will reload all changed modules every time before executing a new line. The way this works is slightly different than `dreload`. Some caveats apply, type `%autoreload?` to see what can go wrong. * * * If you want to always enable this settings, modify your IPython configuration file `~/.ipython/profile_default/ipython_config.py`[1] and appending: c.InteractiveShellApp.extensions = ['autoreload'] c.InteractiveShellApp.exec_lines = ['%autoreload 2'] _Credit to @Kos via a comment below._ [1] If you don't have the file `~/.ipython/profile_default/ipython_config.py`, you need to call `ipython profile create` first. Or the file may be located at `$IPYTHONDIR`.
How to let Python code continue after telnet (telnetlib) timeout Question: I am using Python for Automated telnet program using telnetlib. The problem is: when the device that I am trying to telnet to doesn't responsd, means timeout; the program gives me timeout message and doesn't continue to next commands. My Code: import telnetlib HOST = ("x.x.x.x") USER = ("xxxxx") PWD = ("yyyyy") ENABLE = ("zzzzz") TNT = telnetlib.Telnet(HOST, 23, 5) TNT.read_until(b"Username:") TNT.write(USER.encode('ascii') + b"\n") TNT.read_until(b"Password:") TNT.write(PWD.encode('ascii') + b"\n") TNT.write(b"enable\n") TNT.read_until(b"Password:") TNT.write(ENABLE.encode('ascii') + b"\n") TNT.write(b"terminal length 0\n") TNT.write(b"show run\n") TNT.write(b"exit\n") print (TNT.read_all().decode('ascii')) TNT.close() raw_input ("Press any Key to Quit: ") Error Message: Traceback (most recent call last): File "D:\Python\Telnet (Python 2.7) V1.5.py", line 8, in <module> TNT = telnetlib.Telnet(HOST, 23, 5) File "C:\Python27\lib\telnetlib.py", line 209, in __init__ self.open(host, port, timeout) File "C:\Python27\lib\telnetlib.py", line 225, in open self.sock = socket.create_connection((host, port), timeout) File "C:\Python27\lib\socket.py", line 571, in create_connection raise err timeout: timed out >>> How can let the program to just notify me that this device isn't reachable and let it continue with the next commands ?? Answer: Wrap the operations in a try block, and handle the exception in a catch block.
python: force non-relative import? Question: I wanted to make a module called `utils/django.py` in my project. On the top I have the line: from django.db import models However, it tries to import from itself, and that causes an error. I know I can force a relative import with a prepended `.`: from .django.db import models is there any way to force a non-relative import? Answer: No. You need to explicitly enable [absolute imports](http://www.python.org/dev/peps/pep-0328/). from __future__ import absolute_import
How do I stop Tornado web server? Question: I've been playing around a bit with the [Tornado web server](http://www.tornadoweb.org/) and have come to a point where I want to stop the web server (for example during unit testing). The following simple example [exists on the Tornado web page](http://www.tornadoweb.org/documentation#overview): import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start() Once `tornado.ioloop.IOLoop.instance().start()` is called, it blocks the program (or current thread). Reading the [source code](https://github.com/facebook/tornado/blob/master/tornado/ioloop.py#L288) for the `IOLoop` object gives this example in the documentation for the `stop` function: To use asynchronous methods from otherwise-synchronous code (such as unit tests), you can start and stop the event loop like this: ioloop = IOLoop() async_method(ioloop=ioloop, callback=ioloop.stop) ioloop.start() ioloop.start() will return after async_method has run its callback, whether that callback was invoked before or after ioloop.start. However, I have no idea how to integrate this into my program. I actually have a class that encapsulates the web server (having it's own `start` and `stop` functions), but as soon as I call start, the program (or tests) will of course block anyway. I've tried to start the web server in another process (using the `multiprocessing` package). This is the class that is wrapping the web server: class Server: def __init__(self, port=8888): self.application = tornado.web.Application([ (r"/", Handler) ]) def server_thread(application, port): http_server = tornado.httpserver.HTTPServer(application) http_server.listen(port) tornado.ioloop.IOLoop.instance().start() self.process = Process(target=server_thread, args=(self.application, port,)) def start(self): self.process.start() def stop(self): ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(ioloop.stop) However, stop does not seem to entirely stop the web server since it is still running in the next test, even with this test setup: def setup_method(self, _function): self.server = Server() self.server.start() time.sleep(0.5) # Wait for web server to start def teardown_method(self, _function): self.kstore.stop() time.sleep(0.5) How can I start and stop a Tornado web server from within a Python program? Answer: I just ran into this and found this issue myself, and using info from this thread came up with the following. I simply took my working stand alone Tornado code (copied from all the examples) and moved the actual starting code into a function. I then called the function as a threading thread. My case different as the threading call was done from my existing code where I just imported the startTornado and stopTornado routines. The suggestion above seemed to work great, so I figured I would supply the missing example code. I tested this code under Linux on a FC16 system (and fixed my initial type-o). import tornado.ioloop, tornado.web class Handler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/", Handler) ]) def startTornado(): application.listen(8888) tornado.ioloop.IOLoop.instance().start() def stopTornado(): tornado.ioloop.IOLoop.instance().stop() if __name__ == "__main__": import time, threading threading.Thread(target=startTornado).start() print "Your web server will self destruct in 2 minutes" time.sleep(120) stopTornado() Hope this helps the next person.
Iteratively write XML nodes in python Question: There are many ways to read XML, both all-at-once (DOM) and one-bit-at-a-time (SAX). I have used SAX or lxml to iteratively read large XML files (e.g. wikipedia dump which is 6.5GB _compressed_). However after doing some iterative processing (in python using ElementTree) of that XML file, I want to write out the (new) XML data to another file. Are there any libraries to iteratively write out XML data? I _could_ create the XML tree and then write it out, but that is not possible without oodles of ram. Is there anyway to write the XML tree to a file iteratively? One bit at a time? I know I could generate the XML myself with `print "<%s>" % tag_name`, etc., but that seems a bit... _hacky_. Answer: Fredrik Lundh's [elementtree.SimpleXMLWriter](http://svn.effbot.org/public/elementtree-1.3/elementtree/) will let you write out XML incrementally. Here's the demo code embedded in the module: from elementtree.SimpleXMLWriter import XMLWriter import sys w = XMLWriter(sys.stdout) html = w.start("html") w.start("head") w.element("title", "my document") w.element("meta", name="generator", value="my application 1.0") w.end() w.start("body") w.element("h1", "this is a heading") w.element("p", "this is a paragraph") w.start("p") w.data("this is ") w.element("b", "bold") w.data(" and ") w.element("i", "italic") w.data(".") w.end("p") w.close(html)
building a tree from a csv file using python Question: My csv file has the following format Col1 Col2 a b b c c d d e x b y c z c m x h b i b I will create a dictionary to hold this data like this { b:[a,x,h,i] , c:[b,y,z], d:[c], e:[d], x:[m] } From this dictionary I want to be able to build a hierarchy. For example: when I walk through the dictionary for 'a' I should be able to display a -> b -> c -> d -> e Similarly for 'y' y -> c -> d -> e I can think of this as a tree structure and imagine this to be a depth first traversal, but I am unsure about how to achieve this with a dictionary in python. This would not be a decision tree or a binary tree etc. Answer: You can use [**Python-Graph**](http://code.google.com/p/python-graph/). pairs = read_from_csv(...) from pygraph.classes.digraph import digraph gr = digraph() gr.add_nodes(set([x for (x,y) in pairs]+[y for (x,y) in pairs])) for pair in pairs: gr.add_edge(pair) #and now you can do something with the graph... from pygraph.algorithms.searching import depth_first_search print ' -> '.join(depth_first_search(gr, root='a')[1]) print ' -> '.join(depth_first_search(gr, root='y')[1])
Faster bitwise modulus for Lucas-Lehmer primality test Question: The [Lucas-Lehmer primality test](http://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test) tests prime numbers to determine whether they are also [Mersenne primes](http://en.wikipedia.org/wiki/Mersenne_prime). One of the bottlenecks is the modulus operation in the calculation of `(s**2 − 2) % (2**p - 1)`. Using bitwise operations can speed things up considerably (see the L-L link), the best I have so far being: def mod(n,p): """ Returns the value of (s**2 - 2) % (2**p -1)""" Mp = (1<<p) - 1 while n.bit_length() > p: # For Python < 2.7 use len(bin(n)) - 2 > p n = (n & Mp) + (n >> p) if n == Mp: return 0 else: return n A simple test case is where `p` has 5-9 digits and `s` has 10,000+ digits (or more; not important what they are). Solutions can be tested by `mod((s**2 - 2), p) == (s**2 - 2) % (2**p -1)`. Keep in mind that p - 2 iterations of this modulus operation are required in the L-L test, each with exponentially increasing `s`, hence the need for optimization. Is there a way to speed this up further, using pure Python (Python 3 included)? Is there a better way? Answer: In the case where n is much longer than 2^p, you can avoid some quadratic-time pain by doing something like this: def mod1(n,p): while n.bit_length() > 3*p: k = n.bit_length() // p k1 = k>>1 k1p = k1*p M = (1<<k1p)-1 n = (n & M) + (n >> k1p) Mp = (1<<p)-1 while n.bit_length() > p: n = (n&Mp) + (n>>p) if n==Mp: return 0 return n [EDITED because I screwed up the formatting before; thanks to Benjamin for pointing this out. Moral: don't copy-and-paste from an Idle window into SO. Sorry!] (Note: the criterion for halving the length of n rather than taking p off it, and the exact choice of k1, are both a bit wrong, but it doesn't matter so I haven't bothered fixing them.) If I take p=12345 and n=9**200000 (yes, I know p then isn't prime, but that doesn't matter here) then this is about 13 times faster. **Unfortunately this will not help you** , because in the L-L test n is never bigger than about (2^p)^2. Sorry.
python - capturing stderr of subprocesses with their shell stdout alive Question: Here are things I'm trying to do: -python process captures stderr of multiple subprocesses to watch the subprocesses -each subprocess runs on the separate window displaying stdout. When I use **Popen(_command_ ,stderr = _fp4tempfile_)**, (good) the python process can capture stderr of the subprocesses (bad ) the subprocess shells stop displaying stdout. When I use **Popen(_command_)**, (good) each subprocess shells displays stdout (as well as stderr, which does not matter for me), (bad ) the python process cannot capture stderr. I want both "good"s. What can I do for this? Thanks in advance. (currently, I'm using python3.2 developing in windows7) Here's the parent process source written in python: import os,subprocess import time fpws = [] fprs = [] def run_command(command): <specifying a file to write -- skipped> fpw = open(ftempname,'w') fpr = open(ftempname,'r') #cmd_redirect = "%s 2>%s" % (command,ftempname)#didnt do anything #starting a sub-program: pp = subprocess.Popen(command,stderr = fpw) #++ #pp = subprocess.Popen(command) #@@ fpws.append(fpw) fprs.append(fpr) def watch_program(): while True: #running forever for simplfication for fpr in fprs: outchunk = fpr.read() <do something for subprocesses stderr -- skipped> time.sleep(1.0) if __name__ == '__main__': cmd1 = '(path to program1)' cmd2 = '(path to program2)' run_command(cmd1) #kicking cmd1 run_command(cmd2) #kicking cmd2 watch_program() #hearing stderr msg from the other process Note: in the subprocess side, fflush(stdout) and fflush(stderr) are called as needed. Answer: Haven't tested this, but can you do import sys pp = subprocess.Popen(command, stderr = fpw, stdout = sys.stdout)
Python Run a daemon sub-process & read stdout Question: I need to run a program and gather its output to stdout. This program (socat) needs to run in the background for the duration of the python script. Socat sits in dameon mode once it's run, but first it outputs some lines to stdout that I need for the rest of my script. Command: `socat -d -d PTY: PTY:` Output: 2011/03/23 21:12:35 socat[7476] N PTY is /dev/pts/1 2011/03/23 21:12:35 socat[7476] N PTY is /dev/pts/2 2011/03/23 21:12:35 socat[7476] N starting data transfer loop with FDs [3,3] and [5,5] ... I basically want to run that at the start of my program and leave it running till script termination, but I need to read the two /dev/pts/X names into python. Can anyone tell me how to do this? I came up with this which just hangs, I guess because it's blocking for the child process to terminate. #!/usr/bin/python from subprocess import Popen, PIPE, STDOUT cmd = 'socat -d -d PTY: PTY: &' p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) output = p.stdout.read() # Process the output print(output) Thanks for any help EDIT: Seems it may write to stderr, but the script still just hanges with and without the & even reading from stderr. Answer: #!/usr/bin/python from subprocess import Popen, PIPE, STDOUT import pty import os cmd = 'socat -d -d PTY: PTY:' master, slave = pty.openpty() p = Popen(cmd, shell=True, stdin=PIPE, stdout=slave, stderr=slave, close_fds=True) stdout = os.fdopen(master) print stdout.readline() print stdout.readline() There are two problems with your version. Firstly, you call read without argument which means it will attempt to read everything. But since socat doesn't terminate, it never decides that it has read everything. By using readline, python only reads until it finds a newline. From my understanding of your problem that is what you need. The second problem is that the C standard library will buffer outputs on pipes. We solve that by creating a pty with the openpty() function and passing it to both stdout and stderr of the subprocess. We use fdopen to make that file descriptor into a regular python object and we get rid of the buffering. I don't know what you are doing with the socat, but I wonder whether it could replaced by using the pty module. You are copying one pty to another, and openpty is creating a pair of ptys. Perhaps you can use those directly?
No handlers could be found for logger "myapp.lib" Question: I just upgraded to Django 1.3 which brings it's own logging module. I did set up logging and it is working when the modules are accessed by Apache/mod_wsgi. But when I am working with the django shell, Logging does not work - I always get the infamous error "**No handlers could be found for logger 'myapp.lib'** " when working on the shell. This is the logging-part of my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'class': 'logging.handlers.RotatingFileHandler', 'formatter': 'simple', 'filename': '/var/log/myapp.log', 'maxBytes': '4096', 'backupCount': '5' }, 'console': { 'level':'DEBUG', 'class':'logging.StreamHandler', 'formatter': 'simple' } }, 'loggers': { 'myapp.lib': { 'handlers': ['file', 'console',], 'level': 'INFO', }, } } And this is the Python code causing the error: import logging l=logging.getLogger(__name__) l.warn("foo") Answer: To log from the django shell you would need to run: import logging l=logging.getLogger('myapp.lib') l.warn("foo") `__name__` is `__main__` at the shell.
How to interfere some text in a html link string in python Question: In the company I am working they use the above command to construct a link from a list of data we are holding on a map link=a % firstUpper(b) which produces something like <a href="path/tomyhtml/foo.html">foo</a> I would like to alter the link string and add a title attribute to it so it becomes like <a href="path/tomyhtml/foo.html" title="Some cool title">foo</a> my thought was to alter add the title in 3rd character which looks to be "most" of the times a space, but in my mind is not the most elegant solution. Answer: Using [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/): from BeautifulSoup import BeautifulSoup soup = BeautifulSoup('<a href="path/tomyhtml/foo.html">foo</a>') soup.a["title"] = "Some cool title"
Squid-style external redirector for polipo doesn't work Question: I am trying to write a trivial squid-style redirector for polipo http proxy, as specified [in the documentation](http://www.pps.jussieu.fr/~jch/software/polipo/manual/External- redirectors.html#External-redirectors). Here is the code: #!/usr/bin/python # based on # http://gofedora.com/how-to-write-custom-redirector-rewritor-plugin-squid-python/ import sys def modify_url(line): l = line.split(" ") old_url = l[0] new_url = "\n" if "experts-exchange" in old_url: new_url = "http://127.0.0.1/" + new_url return new_url while True: line = sys.stdin.readline().strip() new_url = modify_url(line) sys.stdout.write(new_url) sys.stdout.flush() When running polipo with this redirector and trying to access <http://www.experts-exchange.com/>, I get the following error: 500 Couldn't test for forbidden URL: Redirector error Actually, I get the same error when trying to access any URL, which makes me think it's a problem with my redirector code. The output in polipo's log doesn't provide more hints, all I see there is: Redirector returned incomplete reply. What am I doing wrong? Edit: I have fixed modify_url() to return a value, because it did not. I'm still getting the same error. Answer: That site (gofedora) mentions that you need to return either a blank line or the modified url in modify_url to make it work. Also you'll see the error if you run this manually. Your solution is to return new_url at the end of modify_url. Please note that you also need to chmod +x to permit your proxy to run the script.
Django, uWSGI & nginx: Process dies for "no reason" Question: I am using uWSGI and nginx to run two parallell Django apps. One of them, the one with somewhat more load (both are very small) keeps dying about once every 24 hours with the following message: `[pid: 16358|app: 0|req: 1000/1000] 127.0.0.1 () {46 vars in 847 bytes} [Thu Mar 24 16:38:31 2011] GET /aktivitet/409/picknick/ => generated 18404 bytes in 117 msecs (HTTP/1.0 200) 3 headers in 156 bytes (1 switches on core 0) **...The work of process 16358 is done. Seeya!**` I am launching the processess using Supervisor with the following config: `[program:uttrakad] command=/home/myuser/webapps/uwsgi_test/bin/uwsgi -s /home/myuser/webapps/uwsgi_test/app1.sock -C /home/myuser/webapps/django/app1.wsgi --processes 1 --harakiri 120 --max- requests 1000 autostart=true autorestart=true stdout_logfile=/home/myuser/logs/user/uwsgi_app1.log redirect_stderr=true stopsignal=QUIT` The .wsgi file is simple: ` import os import sys sys.path =['/home/openworks/webapps/django/lib/python2.6/','/home/openworks/webapps/django/','/home/openworks/webapps/django/app1/'] + sys.path from django.core.handlers.wsgi import WSGIHandler os.environ['DJANGO_SETTINGS_MODULE'] = 'app1.prod_settings' application = WSGIHandler() ` nginx is set up with 2 worker processes, 2048 worker_connections and like this: ` location / { uwsgi_pass unix:///home/openworks/webapps/uwsgi_test/app1.sock; include uwsgi_params; } ` As I said, there is one more app configured the exact same way that has been running without interuption, but is almost has no traffic. Any clues? Why do I get the "_...The work of process 16358 is done. Seeya_ " messsage? Thanks Answer: Look at the log: req: 1000/1000 And you have set 1000 as the number of maxium requests. You should always add --master/-M on uwsgi even under supervisord, this will allow to restart apps without losing the socket (and without spitting out an error to clients during restart).
element tree search help(python, xml) Question: I'm trying to find all child elements whose attribute `class` is 'TRX' and whose attribute `distName` Starts with 'PLMN-PLMN/BSC-208812/BCF-1/BTS-1' Is something like this possible? root[0].findall("*[@class='TRX'][@distName='PLMN-PLMN/BSC-208812/BCF-1/BTS-1*']") I'm using cElementTree over lxml because it is much much faster on my comp. Answer: ElementTree can in fact do this. You may need to use `.//*` instead of `*`. [Python docs ElementTree](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element "ElementTree") version 1.3.0 which comes with Python 2.7 has the XPath capabilities you seek. **Example** from xml.etree import ElementTree et = ElementTree.fromstring(""" <r> <b> <a class='c' foo='e'>this is e</a> <a class='c' foo='f'>this is f</a> <a class='c' foo='g'>this is g</a> </b> </r> """) if __name__ == '__main__': print ElementTree.VERSION print "* c and f", et.findall("*[@class='c'][@foo='f']") print ".//* c and f", et.findall(".//*[@class='c'][@foo='f']") print ".//* c", et.findall(".//*[@class='c']") print ".//* f", et.findall(".//*[@foo='f']") **Output** 1.3.0 * c and f [] .//* c and f [<Element 'a' at 0x10049be50>] .//* c [<Element 'a' at 0x10049bdd0>, <Element 'a' at 0x10049be50>, <Element 'a' at 0x10049bf10>] .//* f [<Element 'a' at 0x10049be50>]
Load website's content through python Question: How can i load a specific content from a website through python?For example,i want to load some posts of a blog and appear them to my own site.How can i do this? Answer: An answer: import urllib2 from BeautifulSoup import BeautifulSoup def fetchtags(req, name, attrs, num): try: website = urllib2.urlopen(req) except urllib2.HTTPError, e: print 'A problem occured. Please try again.' return soup = BeautifulSoup(website, convertEntities=BeautifulSoup.HTML_ENTITIES) tags = soup.findAll(name=name, attrs=attrs, limit=num) return tags Then you can use it like: fetchtags('http://www.website.com', 'div', {'class':'c'}, 10) To get 10 divs of class c from the specified url... See Beautiful Soup for more details on the returned object.
learn python the hard way exercise 40 help Question: hey guys i am having trouble understanding this, i dont get when themap is referenced to the cities dict really. or the last line, what is the(cities, state) part? thanks. cities = { 'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} cities['NY'] = 'New York' cities['OR'] = 'Portland' def find_city(themap, state): if state in themap: return themap[state] else: return 'not found' #ok pay attention! cities['_find'] = find_city while True: print 'State? (ENTER to quit)' state = raw_input('> ') if not state: break #this line is the most important ever! study! city_found = cities['_find'] (cities, state) print city_found Answer: `cities['_find']` is exactly `find_city`. So `cities['_find'](cities, state)` is the same as `find_city(cities, state)`. The reason for my first statement is this line: cities['_find'] = find_city That doesn't call `find_city`, it sticks the function itself in the dictionary. Python functions are just objects like lists and class instances. If you don't put parentheses after them, they can be assigned to variables.
Adding Zooming in and out with a Tkinter Canvas Widget in Python Question: How would I add zooming in and out to the following script, i'd like to bind it to the mousewheel. If you're testing this script on linux don't forget to change the MouseWheel event to Button-4 and Button-5. from Tkinter import * import Image, ImageTk class GUI: def __init__(self,root): frame = Frame(root, bd=2, relief=SUNKEN) frame.grid_rowconfigure(0, weight=1) frame.grid_columnconfigure(0, weight=1) xscrollbar = Scrollbar(frame, orient=HORIZONTAL) xscrollbar.grid(row=1, column=0, sticky=E+W) yscrollbar = Scrollbar(frame) yscrollbar.grid(row=0, column=1, sticky=N+S) self.canvas = Canvas(frame, bd=0, xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set, xscrollincrement = 10, yscrollincrement = 10) self.canvas.grid(row=0, column=0, sticky=N+S+E+W) File = "PATH TO JPG PICTURE HERE" self.img = ImageTk.PhotoImage(Image.open(File)) self.canvas.create_image(0,0,image=self.img, anchor="nw") self.canvas.config(scrollregion=self.canvas.bbox(ALL)) xscrollbar.config(command=self.canvas.xview) yscrollbar.config(command=self.canvas.yview) frame.pack() self.canvas.bind("<Button 3>",self.grab) self.canvas.bind("<B3-Motion>",self.drag) root.bind("<MouseWheel>",self.zoom) def grab(self,event): self._y = event.y self._x = event.x def drag(self,event): if (self._y-event.y < 0): self.canvas.yview("scroll",-1,"units") elif (self._y-event.y > 0): self.canvas.yview("scroll",1,"units") if (self._x-event.x < 0): self.canvas.xview("scroll",-1,"units") elif (self._x-event.x > 0): self.canvas.xview("scroll",1,"units") self._x = event.x self._y = event.y def zoom(self,event): if event.delta>0: print "ZOOM IN!" elif event.delta<0: print "ZOOM OUT!" root = Tk() GUI(root) root.mainloop() Answer: To my knowledge the built-in Tkinter Canvas class scale will not auto-scale images. If you are unable to use a custom widget, you can scale the raw image and replace it on the canvas when the scale function is invoked. The code snippet below can be merged into your original class. It does the following: 1. Caches the result of `Image.open()`. 2. Adds a `redraw()` function to calculate the scaled image and adds that to the canvas, and also removes the previously-drawn image if any. 3. Uses the mouse coordinates as part of the image placement. I just pass `x and y` to the `create_image` function to show how the image placement shifts around as the mouse moves. You can replace this with your own center/offset calculation. 4. This uses the Linux mousewheel buttons 4 and 5 (you'll need to generalize it to work on Windows, etc). (**Updated**) Code: class GUI: def __init__(self, root): # ... omitted rest of initialization code self.canvas.config(scrollregion=self.canvas.bbox(ALL)) self.scale = 1.0 self.orig_img = Image.open(File) self.img = None self.img_id = None # draw the initial image at 1x scale self.redraw() # ... rest of init, bind buttons, pack frame def zoom(self,event): if event.num == 4: self.scale *= 2 elif event.num == 5: self.scale *= 0.5 self.redraw(event.x, event.y) def redraw(self, x=0, y=0): if self.img_id: self.canvas.delete(self.img_id) iw, ih = self.orig_img.size size = int(iw * self.scale), int(ih * self.scale) self.img = ImageTk.PhotoImage(self.orig_img.resize(size)) self.img_id = self.canvas.create_image(x, y, image=self.img) # tell the canvas to scale up/down the vector objects as well self.canvas.scale(ALL, x, y, self.scale, self.scale) **Update** I did a bit of testing for varying scales and found that quite a bit of memory is being used by resize / create_image. I ran the test using a 540x375 JPEG on a Mac Pro with 32GB RAM. Here is the memory used for different scale factors: 1x (500, 375) 14 M 2x (1000, 750) 19 M 4x (2000, 1500) 42 M 8x (4000, 3000) 181 M 16x (8000, 6000) 640 M 32x (16000, 12000) 1606 M 64x (32000, 24000) ... reached around ~7400 M and ran out of memory, EXC_BAD_ACCESS in _memcpy Given the above, a more efficient solution might be to determine the size of the viewport where the image will be displayed, calculate a cropping rectangle around the center of the mouse coordinates, crop the image using the rect, then scale just the cropped portion. This should use constant memory for storing the temporary image. Otherwise you may need to use a 3rd party Tkinter control which performs this cropping / windowed scaling for you. **Update 2** Working but oversimplified cropping logic, just to get you started: def redraw(self, x=0, y=0): if self.img_id: self.canvas.delete(self.img_id) iw, ih = self.orig_img.size # calculate crop rect cw, ch = iw / self.scale, ih / self.scale if cw > iw or ch > ih: cw = iw ch = ih # crop it _x = int(iw/2 - cw/2) _y = int(ih/2 - ch/2) tmp = self.orig_img.crop((_x, _y, _x + int(cw), _y + int(ch))) size = int(cw * self.scale), int(ch * self.scale) # draw self.img = ImageTk.PhotoImage(tmp.resize(size)) self.img_id = self.canvas.create_image(x, y, image=self.img) gc.collect()
python pip package install fails , dllwrap error after 'fixing': "unable to find vcvarsall.bat" Question: I can't find this in the archives. Is there something not right with mingw/msys? [I need to get vcvarsall.bat fixed, so I can install other packages.] Failure to install python package 'twisted' using pip.exe. I have python2.6 and mingw/msys installed. %PATH% includes `C:\MinGW\` and `C:\MinGW\mingw32\bin` first: `pip.exe install twisted` fails by saying `error: Unable to find vcvarsall.bat` I create file `G:\Programs (x86)\Python 2.6\Lib\distutils\distutils.cfg`, which contains: [build] compiler=mingw32 Now the error I get is: g:\Programs (x86)\Python 2.6>python Scripts\pip-script.py install twisted Downloading/unpacking twisted Running setup.py egg_info for package twisted Downloading/unpacking zope.interface (from twisted) Running setup.py egg_info for package zope.interface Requirement already satisfied (use --upgrade to upgrade): setuptools in g:\progr ams (x86)\python 2.6\lib\site-packages (from zope.interface->twisted) Installing collected packages: twisted, zope.interface Running setup.py install for twisted C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall "-Ig:\Programs (x86)\Python 2.6\include" "-Ig:\Programs (x86)\Python 2.6\PC" -c conftest.c -o conftest.o conftest.c:1:21: fatal error: rpc/rpc.h: No such file or directory compilation terminated. C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall "-Ig:\Programs (x86)\Python 2.6\include" "-Ig:\Programs (x86)\Python 2.6\PC" -c conftest.c -o conftest.o conftest.c:1:23: fatal error: sys/epoll.h: No such file or directory compilation terminated. building 'twisted.protocols._c_urlarg' extension C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -DWIN32=1 "-Ig:\Programs (x8 6)\Python 2.6\include" "-Ig:\Programs (x86)\Python 2.6\PC" -c twisted/protocols/ _c_urlarg.c -o build\temp.win32-2.6\Release\twisted\protocols\_c_urlarg.o twisted/protocols/_c_urlarg.c: In function 'unquote': twisted/protocols/_c_urlarg.c:41:50: warning: 'tmp' may be used uninitialize d in this function C:\MinGW\bin\dllwrap.exe -mno-cygwin -mdll -static --output-lib build\temp.w in32-2.6\Release\twisted\protocols\lib_c_urlarg.a --def build\temp.win32-2.6\Rel ease\twisted\protocols\_c_urlarg.def -s build\temp.win32-2.6\Release\twisted\pro tocols\_c_urlarg.o "-Lg:\Programs (x86)\Python 2.6\libs" "-Lg:\Programs (x86)\Py thon 2.6\PCbuild" -lpython26 -lmsvcr90 -o build\lib.win32-2.6\twisted\protocols\ _c_urlarg.pyd _c_urlarg.exp: file not recognized: File format not recognized collect2: ld returned 1 exit status dllwrap: gcc exited with status 1 error: command 'dllwrap' failed with exit status 1 Complete output from command "g:\Programs (x86)\Python 2.6\python.exe" -c "i mport setuptools;__file__='g:\\Programs (x86)\\Python 2.6\\build\\twisted\\setup .py';execfile(__file__)" install --single-version-externally-managed --record c: \users\jake\appdata\local\temp\pip-3y_c1e-record\install-record.txt: running install running build running build_py running egg_info writing requirements to Twisted.egg-info\requires.txt writing Twisted.egg-info\PKG-INFO writing top-level names to Twisted.egg-info\top_level.txt writing dependency_links to Twisted.egg-info\dependency_links.txt reading manifest file 'Twisted.egg-info\SOURCES.txt' writing manifest file 'Twisted.egg-info\SOURCES.txt' running build_ext C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall "-Ig:\Programs (x86)\Python 2.6\ include" "-Ig:\Programs (x86)\Python 2.6\PC" -c conftest.c -o conftest.o conftest.c:1:21: fatal error: rpc/rpc.h: No such file or directory compilation terminated. C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall "-Ig:\Programs (x86)\Python 2.6\ include" "-Ig:\Programs (x86)\Python 2.6\PC" -c conftest.c -o conftest.o conftest.c:1:23: fatal error: sys/epoll.h: No such file or directory compilation terminated. building 'twisted.protocols._c_urlarg' extension C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -DWIN32=1 "-Ig:\Programs (x86)\P ython 2.6\include" "-Ig:\Programs (x86)\Python 2.6\PC" -c twisted/protocols/_c_u rlarg.c -o build\temp.win32-2.6\Release\twisted\protocols\_c_urlarg.o twisted/protocols/_c_urlarg.c: In function 'unquote': twisted/protocols/_c_urlarg.c:41:50: warning: 'tmp' may be used uninitialized in this function writing build\temp.win32-2.6\Release\twisted\protocols\_c_urlarg.def C:\MinGW\bin\dllwrap.exe -mno-cygwin -mdll -static --output-lib build\temp.win32 -2.6\Release\twisted\protocols\lib_c_urlarg.a --def build\temp.win32-2.6\Release \twisted\protocols\_c_urlarg.def -s build\temp.win32-2.6\Release\twisted\protoco ls\_c_urlarg.o "-Lg:\Programs (x86)\Python 2.6\libs" "-Lg:\Programs (x86)\Python 2.6\PCbuild" -lpython26 -lmsvcr90 -o build\lib.win32-2.6\twisted\protocols\_c_u rlarg.pyd _c_urlarg.exp: file not recognized: File format not recognized collect2: ld returned 1 exit status dllwrap: gcc exited with status 1 warning: manifest_maker: standard file '-c' not found error: command 'dllwrap' failed with exit status 1 ---------------------------------------- Command "g:\Programs (x86)\Python 2.6\python.exe" -c "import setuptools;__file__ ='g:\\Programs (x86)\\Python 2.6\\build\\twisted\\setup.py';execfile(__file__)" install --single-version-externally-managed --record c:\users\jake\appdata\local \temp\pip-3y_c1e-record\install-record.txt failed with error code 1 Storing complete log in C:\Users\jake\AppData\Roaming\pip\pip.log Answer: This is likely a bug with Python. See <http://bugs.python.org/issue2698> Meanwhile, you could install [ActivePython](http://activestate.com/activepython/downloads) and [install Twisted](http://code.activestate.com/pypm/twisted/) via PyPM (no compilers needed). Alternatively, you can use [the official binary](http://pypi.python.org/packages/2.6/T/Twisted/Twisted-10.2.0.winxp32-py2.6.msi#md5=ded94c0e8d460daf3631378bb58331c5) ... though I recommend the aforementioned solution as you can easily 'upgrade' to newer versions of Twisted in future.
Mathematica Notation and syntax mods Question: I am experimenting with syntax mods in Mathematica, using the Notation package. I am not interested in mathematical notation for a specific field, but general purpose syntax modifications and extensions, especially notations that reduce the verbosity of Mathematica's VeryLongFunctionNames, clean up unwieldy constructs, or extend the language in a pleasing way. An example modification is defining `Fold[f, x]` to evaluate as `Fold[f, First@x, Rest@x]` This works well, and is quite convenient. Another would be defining `*{1,2}` to evaluate as `Sequence @@ {1,2}` as inspired by Python; this may or may not work in Mathematica. Please provide information or links addressing: * Limits of notation and syntax modification * Tips and tricks for implementation * Existing packages, examples or experiments * Why this is a good or bad idea Answer: Not a really constructive answer, just a couple of thoughts. First, a disclaimer - I don't suggest any of the methods described below as good practices (perhaps generally they are not), they are just some possibilities which seem to address your specific question. Regarding the stated goal - I support the idea very much, being able to reduce verbosity is great (for personal needs of a solo developer, at least). As for the tools: I have very little experience with Notation package, but, whether or not one uses it or writes some custom box-manipulation preprocessor, my feeling is that the whole fact that the input expression must be parsed into boxes by Mathematica parser severely limits a number of things that can be done. Additionally, there will likely be difficulties with using it in packages, as was mentioned in the other reply already. It would be easiest if there would be some hook like `$PreRead`, which would allow the user to intercept the input string and process it into another string before it is fed to the parser. That would allow one to write a custom preprocessor which operates on the string level - or you can call it a compiler if you wish - which will take a string of whatever syntax you design and generate Mathematica code from it. I am not aware of such hook (it may be my ignorance of course). Lacking that, one can use for example the _program_ style cells and perhaps program some buttons which read the string from those cells and call such preprocessor to generate the Mathematica code and paste it into the cell next to the one where the original code is. Such preprocessor approach would work best if the language you want is some simple language (in terms of its syntax and grammar, at least), so that it is easy to lexically analyze and parse. If you want the Mathematica language (with its full syntax modulo just a few elements that you want to change), in this approach you are out of luck in the sense that, regardless of how few and "lightweight" your changes are, you'd need to re-implement pretty much completely the Mathematica parser, just to make those changes, if you want them to work reliably. In other words, what I am saying is that IMO it is much easier to write a preprocessor that would generate Mathematica code from some Lisp-like language with little or no syntax, than try to implement a few syntactic modifications to otherwise the standard mma. Technically, one way to write such a preprocessor is to use standard tools like Lex(Flex) and Yacc(Bison) to define your grammar and generate the parser (say in C). Such parser can be plugged back to Mathematica either through MathLink or LibraryLink (in the case of C). Its end result would be a string, which, when parsed, would become a valid Mathematica expression. This expression would represent the abstract syntax tree of your parsed code. For example, code like this (new syntax for `Fold` is introduced here) "((1|+|{2,3,4,5}))" could be parsed into something like "functionCall[fold,{plus,1,{2,3,4,5}}]" The second component for such a preprocessor would be written in Mathematica, perhaps in a rule-based style, to generate Mathematica code from the AST. The resulting code must be somehow held unevaluated. For the above code, the result might look like Hold[Fold[Plus,1,{2,3,4,5}]] It would be best if analogs of tools like Lex(Flex)/Yacc(Bison) were available within Mathematica ( I mean bindings, which would require one to only write code in Mathematica, and generate say C parser from that automatically, plugging it back to the kernel either through MathLink or LibraryLink). I may only hope that they will become available in some future versions. Lacking that, the approach I described would require a lot of low-level work (C, or Java if your prefer). I think it is still doable however. If you can write C (or Java), you may try to do some fairly simple (in terms of the syntax / grammar) language - this may be an interesting project and will give an idea of what it will be like for a more complex one. I'd start with a very basic calculator example, and perhaps change the standard arithmetic operators there to some more weird ones that Mathematica can not parse properly itself, to make it more interesting. To avoid MathLink / LibraryLink complexity at first and just test, you can call the resulting executable from Mathematica with `Run`, passing the code as one of the command line arguments, and write the result to a temporary file, that you will then import into Mathematica. For the calculator example, the entire thing can be done in a few hours. Of course, if you only want to abbreviate certain long function names, there is a much simpler alternative - you can use `With` to do that. Here is a practical example of that - my port of Peter Norvig's [spelling corrector](http://norvig.com/spell-correct.html), where I cheated in this way to reduce the line count: Clear[makeCorrector]; makeCorrector[corrector_Symbol, trainingText_String] := Module[{model, listOr, keys, words, edits1, train, max, known, knownEdits2}, (* Proxies for some commands - just to play with syntax a bit*) With[{fn = Function, join = StringJoin, lower = ToLowerCase, rev = Reverse, smatches = StringCases, seq = Sequence, chars = Characters, inter = Intersection, dv = DownValues, len = Length, ins = Insert, flat = Flatten, clr = Clear, rep = ReplacePart, hp = HoldPattern}, (* body *) listOr = fn[Null, Scan[If[# =!= {}, Return[#]] &, Hold[##]], HoldAll]; keys[hash_] := keys[hash] = Union[Most[dv[hash][[All, 1, 1, 1]]]]; words[text_] := lower[smatches[text, LetterCharacter ..]]; With[{m = model}, train[feats_] := (clr[m]; m[_] = 1; m[#]++ & /@ feats; m)]; With[{nwords = train[words[trainingText]], alphabet = CharacterRange["a", "z"]}, edits1[word_] := With[{c = chars[word]}, join @@@ Join[ Table[ rep[c, c, #, rev[#]] &@{{i}, {i + 1}}, {i, len[c] - 1}], Table[Delete[c, i], {i, len[c]}], flat[Outer[#1[c, ##2] &, {ins[#1, #2, #3 + 1] &, rep}, alphabet, Range[len[c]], 1], 2]]]; max[set_] := Sort[Map[{nwords[#], #} &, set]][[-1, -1]]; known[words_] := inter[words, keys[nwords]]]; knownEdits2[word_] := known[flat[Nest[Map[edits1, #, {-1}] &, word, 2]]]; corrector[word_] := max[listOr[known[{word}], known[edits1[word]], knownEdits2[word], {word}]];]]; You need some training text with a large number of words as a string to pass as a second argument, and the first argument is the function name for a corrector. Here is the one that Norvig used: text = Import["http://norvig.com/big.txt", "Text"]; You call it once, say In[7]:= makeCorrector[correct, text] And then use it any number of times on some words In[8]:= correct["coputer"] // Timing Out[8]= {0.125, "computer"} You can make your custom `With`-like control structure, where you hard-code the short names for some long mma names that annoy you the most, and then wrap that around your piece of code ( you'll lose the code highlighting however). Note, that I don't generally advocate this method - I did it just for fun and to reduce the line count a bit. But at least, this is universal in the sense that it will work both interactively and in packages. Can not do infix operators, can not change precedences, etc, etc, but almost zero work.
Find the default application name for a given file Question: In Linux, is there a way to ask any xdg services, or gtk services, which application is the default application for a given file? I realize that **xdg-open** will in fact, launch the correct application. However, I want to be able to display the application's name in a context menu. So that when the user clicks on the menu item, it will then launch xdg- open, which will launch that app. On OSX I can use LaunchServices for this: def getDefaultDarwinApplication(path): import LaunchServices import CoreData import urllib url = CoreData.CFURLRef.URLWithString_("file://"+urllib.quote(path)) os_status, app_ref, appurl = LaunchServices.LSGetApplicationForURL(url, LaunchServices.kLSRolesAll, None, None) if os_status != 0: return "" apppath = app_ref.as_pathname() name = os.path.basename(apppath).replace(".app", "") return name The hope is that there is something similar on Linux I can use. A builtin python module would be best, but even screen scraping would work. Answer: Use the `xdg-mime` command. It allows you to query for a mimetype, and then get the program associated, without executing it. Note that this returns the name of the associated `.desktop` file. Then you have to locate the actual file and further parse it to get the real name of the program, even localized in any language you want, path of the binary in the disk, etc. Here's the full code: import os import subprocess import codecs import ConfigParser class XDGError(Exception): pass class FileNotFoundError(Exception): pass def _get_app_paths(): paths = os.environ.get('XDG_DATA_HOME', os.path.expanduser('~/.local/share/')).split(os.path.pathsep) paths.extend(os.environ.get('XDG_DATA_DIRS', '/usr/local/share/:/usr/share/').split(os.path.pathsep)) return paths def xdg_query(command, parameter): p = subprocess.Popen(['xdg-mime', 'query', command, parameter], stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, errors = p.communicate() if p.returncode or errors: raise XDGError('xdg-mime returned error code %d: %s' % (p.returncode, errors.strip())) return output.strip() def locate_desktop_file(filename, mode='r', encoding='utf-8', _paths=_get_app_paths()): for path in _paths: for thispath, dirs, files in os.walk(os.path.join(path, 'applications')): if filename not in files: continue fullname = os.path.join(thispath, filename) try: return codecs.open(fullname, mode, encoding) except IOError: pass else: raise FileNotFoundError(filename) def get_defaults(filename): filetype = xdg_query('filetype', filename) desktop_filename = xdg_query('default', filetype) with locate_desktop_file(desktop_filename) as desktop_file: parser = ConfigParser.ConfigParser() parser.readfp(desktop_file, desktop_filename) return dict(parser.items(parser.sections()[0])) Example usage: p = get_defaults('index.html') print p['name'], p['comment']
Verifying signature on android in-app purchase message in Python on Google App Engine Question: The sample application on the android developers site validates the purchase json using java code. Has anybody had any luck working out how to validate the purchase in python. In particular in GAE? The following are the relevant excerpts from the android in-app billing [example program](http://developer.android.com/guide/market/billing/billing_integrate.html#billing- download). This is what would need to be converted to python using [PyCrypto](http://www.dlitz.net/software/pycrypto/) which was re-written to be completely python by Google and is the only Security lib available on app engine. Hopefully Google is cool with me using the excerpts below. private static final String KEY_FACTORY_ALGORITHM = "RSA"; private static final String SIGNATURE_ALGORITHM = "SHA1withRSA"; String base64EncodedPublicKey = "your public key here"; PublicKey key = Security.generatePublicKey(base64EncodedPublicKey); verified = Security.verify(key, signedData, signature); public static PublicKey generatePublicKey(String encodedPublicKey) { try { byte[] decodedKey = Base64.decode(encodedPublicKey); KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM); return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey)); } catch ... } } public static boolean verify(PublicKey publicKey, String signedData, String signature) { if (Consts.DEBUG) { Log.i(TAG, "signature: " + signature); } Signature sig; try { sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(publicKey); sig.update(signedData.getBytes()); if (!sig.verify(Base64.decode(signature))) { Log.e(TAG, "Signature verification failed."); return false; } return true; } catch ... } return false; } Answer: Here's how i did it: from Crypto.Hash import SHA from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from base64 import b64decode def chunks(s, n): for start in range(0, len(s), n): yield s[start:start+n] def pem_format(key): return '\n'.join([ '-----BEGIN PUBLIC KEY-----', '\n'.join(chunks(key, 64)), '-----END PUBLIC KEY-----' ]) def validate_purchase(publicKey, signedData, signature): key = RSA.importKey(pem_format(publicKey)) verifier = PKCS1_v1_5.new(key) data = SHA.new(signedData) sig = b64decode(signature) return verifier.verify(data, sig) This assumes that `publicKey` is your base64 encoded Google Play Store key on one line as you get it from the Developer Console. For people who rather use m2crypto, `validate_purchase()` would change to: from M2Crypto import RSA, BIO, EVP from base64 import b64decode # pem_format() as above def validate_purchase(publicKey, signedData, signature): bio = BIO.MemoryBuffer(pem_format(publicKey)) rsa = RSA.load_pub_key_bio(bio) key = EVP.PKey() key.assign_rsa(rsa) key.verify_init() key.verify_update(signedData) return key.verify_final(b64decode(signature)) == 1
Is there any value to a Switch / Case implementation in Python? Question: Recently, I saw some discussions online about how there is no good "switch / case" equivalent in Python. I realize that there are several ways to do something similar - some with lambda, some with dictionaries. There have been other StackOverflow discussions about the alternatives. There were even two PEPs (PEP 0275 and PEP 3103) discussing (and rejecting) the integration of switch / case into the language. I came up with what I think is an elegant way to do switch / case. It ends up looking like this: from switch_case import switch, case # note the import style x = 42 switch(x) # note the switch statement if case(1): # note the case statement print(1) if case(2): print(2) if case(): # note the case with no args print("Some number besides 1 or 2") So, my questions are: Is this a worthwhile creation? Do you have any suggestions for making it better? I put the [include file on github](https://github.com/jerfelix/switch_case), along with extensive examples. (I think the entire include file is about 50 executable lines, but I have 1500 lines of examples and documentation.) Did I over-engineer this thing, and waste a bunch of time, or will someone find this worthwhile? Edit: Trying to explain why this is different from other approaches: 1) Multiple paths are possible (executing two or more cases), which is harder in the dictionary method. 2) can do checking for comparisons other than "equals" (such as case(less_than(1000)). 3) More readable than the dictionary method, and possibly if/elif method 4) can track how many True cases there were. 5) can limit how many True cases are permitted. (i.e. execute the first 2 True cases of...) 6) allows for a default case. Here's a more elaborate example: from switch_case import switch, case, between x=12 switch(x, limit=1) # only execute the FIRST True case if case(between(10,100)): # note the "between" case Function print ("%d has two digits."%x) if case(*range(0,100,2)): # note that this is an if, not an elif! print ("%d is even."%x) # doesn't get executed for 2 digit numbers, # because limit is 1; previous case was True. if case(): print ("Nothing interesting to say about %d"%x) # Running this program produces this output: 12 has two digits. Here's an example attempting to show how switch_case can be more clear and concise than conventional if/else: # conventional if/elif/else: if (status_code == 2 or status_code == 4 or (11 <= status_code < 20) or status_code==32): [block of code] elif status_code == 25 or status_code == 45: [block of code] if status_code <= 100: [block can get executed in addition to above blocks] # switch_case alternative (assumes import already) switch(status_code) if case (2, 4, between(11,20), 32): # significantly shorter! [block of code] elif case(25, 45): [block of code] if case(le(100)): [block can get executed in addition to above blocks] The big savings is in long if statements where the same switch is repeated over and over. Not sure how frequent of a use-case that is, but there seems to be certain cases where this makes sense. The example file on github has even more examples. Answer: There have been a plethora of discussions that address this issue on Stackoverflow. You can use the search function at the top to look for some other discussions. However, I fail to see how your solution is better than a basic dictionary: def switch(x): return { 1 : 1, 2 : 2, }[x] Although, adding a default clause is non-trivial with this method. However, your example seems to replicate a complex if/else statement anyway ? Not sure if I would include an external library for this.
Python multiprocessing pool.map for multiple arguments Question: In the Python multiprocessing library, is there a variant of pool.map which support multiple arguments? text = "test" def harvester(text, case): X = case[0] return text+ str(X) if __name__ == '__main__': pool = multiprocessing.Pool(processes=6) case = RAW_DATASET pool.map(harvester(text,case),case, 1) pool.close() pool.join() Answer: > is there a variant of pool.map which support multiple arguments? Python 3.3 includes [`pool.starmap()` method](http://docs.python.org/dev/library/multiprocessing.html#multiprocessing.pool.Pool.starmap): #!/usr/bin/env python3 from functools import partial from itertools import repeat from multiprocessing import Pool, freeze_support def func(a, b): return a + b def main(): a_args = [1,2,3] second_arg = 1 with Pool() as pool: L = pool.starmap(func, [(1, 1), (2, 1), (3, 1)]) M = pool.starmap(func, zip(a_args, repeat(second_arg))) N = pool.map(partial(func, b=second_arg), a_args) assert L == M == N if __name__=="__main__": freeze_support() main() For older versions: #!/usr/bin/env python2 import itertools from multiprocessing import Pool, freeze_support def func(a, b): print a, b def func_star(a_b): """Convert `f([1,2])` to `f(1,2)` call.""" return func(*a_b) def main(): pool = Pool() a_args = [1,2,3] second_arg = 1 pool.map(func_star, itertools.izip(a_args, itertools.repeat(second_arg))) if __name__=="__main__": freeze_support() main() ### Output 1 1 2 1 3 1 Notice how [`itertools.izip()`](https://docs.python.org/2.7/library/itertools.html#itertools.izip) and [`itertools.repeat()`](https://docs.python.org/2.7/library/itertools.html#itertools.repeat) are used here. Due to [the bug mentioned by @unutbu](http://bugs.python.org/issue5228) you can't use [`functools.partial()`](http://docs.python.org/library/functools.html#functools.partial) or similar capabilities on Python 2.6, so the simple wrapper function `func_star()` should be defined explicitly. See also [the workaround](http://paste.pocoo.org/show/351774/) [suggested by `uptimebox`](http://bugs.python.org/issue5228#msg130548).
Add Python arguments in script's shebang line (script made with buildout and zc.recipe.egg:scripts) Question: How to specify arguments for Python when building script with buildout? Here's my buildout.cfg: [buildout] parts = python develop = . [python] recipe = zc.recipe.egg:scripts eggs = myproject And setup.py: from setuptools import setup, find_packages setup( name = 'myproject', packages = find_packages(), entry_points = """ [console_scripts] myscript = myproject:main """, ) I get the following shebang with this configuration: $ pip install . $ head -n1 /usr/local/bin/myscript #!/usr/bin/python And I want this: #!/usr/bin/python -u How to do it? I tried adding `arguments = -u` and `interpreter = python -u` to `buildout.cfg`. It didn't work. Answer: You can force unbuffered I/O from within your Python script by re-opening stdin or stdout using os.fdopen on the filenumber: import sys, os unbuffered = os.fdopen(sys.stdout.fileno(), 'w', 0) You can then reassign sys.stdout if you want to use other modules or build-ins that use stdout or stdin: sys.stdout = unbuffered Also see [unbuffered stdout in python (as in python -u) from within the program](http://stackoverflow.com/questions/881696/unbuffered-stdout-in- python-as-in-python-u-from-within-the-program)
How to remove unsafe characters to save file Question: I would like to save a file with the name that has the **most valid characters** remaining intact, f.e. if I get supplied the filename: `>This\ Ăwesomé_Song?©.mp3` and I want to save it under `Windows 7`, it won't let me save it until I remove `>`, `\` and `?`. The characters `Ă`, `©` and `é` are totally fine and I would like to keep them intact (instead of f.e. just running everything through an `ASCII` filter). I don't know which characters are allowed f.e. under `Unix` and the like but I would like it to work _platform-independently_. The way I would solve this problem is by implementing a list of strings that each contain a class of characters, ranked from most vicious (f.e. `?`) to most harmless (f.e. the letter `a`) and knocking them out string by string until I get a filename that i can save. Language is `Python`, thanks! Answer: >>> import re >>> print re.sub(r'[\\/:"*?<>|]+', "", "This\ Ăwesomé_Song?©.mp3") This Ăwesomé_Song©.mp3 >>>
URL encoding for Python OAuth2 Question: I am using %20 to encode a url using oauth2 for python. It does not seem to work. I see that it encodes %20 as %252B . Is there a way around? Edited with example import oauth2 as oauth client = oauth.Client(consumer) url = 'http://localhost:8080/api/v1/search?Name=Julian' method= 'GET' response,content = client.request(url,method) print content The above code works. If I try Name=Julian%20Assange or Name=Julian+Assange, it does not work. The %20 is encoded to %252B Answer: This could be a double quoting issue. urllib2.quote('%') '%25' Can you try not encoding your url before giving it to oauth?
python omnicompletion in vim not working Question: I am trying to use vim on my python journey, based on [this guide](http://blog.dispatched.ch/2009/05/24/vim-as-python-ide/) I think I have the same problem as [a paid nerd](http://stackoverflow.com/questions/2084875/vims-omnicompletion-with- python-just-doesnt-work) but since he didn't find a solution I am posting again here. For some reason I can't get omnicompletion to work in vim, with python. I have installed the fabolous [R-plugin](http://www.vim.org/scripts/script.php%3Fscript_id%3D2628) and built the tags list. So I get omnicompletion with R. But not for python. A few observations: 1. `:echo &omnifunc` prints `pythoncomplete#Complete`. 2. the `.vim/doc/tags` file has R tags, but no python (but this is because python is supported by default right?) 3. If I do `import math` in my `.py` file I can autocomplete eg. `ma` to `math.` but no methods are found? So - in conclusion i am really baffeled :-/ - and if anyone could help ... Answer: It appears that the default omnicompletion for python (`pythoncomplete#Complete`) does not know about buildins/keywords. When you `Ctrl-X``Ctrl-O` on `math.` (if you have imported "math") you should see the available `math.` functions but to do so for `print`, `sorted` etc **I think** you need a plugin like: * [Pydiction](http://www.vim.org/scripts/script.php?script_id=850) or * [PySmell](http://www.vim.org/scripts/script.php?script_id=2421)
Attribute error using __builtin__ functions inside class method Question: I installed rdiff-backup on my arch linux box only to end up with the attribute error: AttributeError: 'module' object has no attribute 'reduce' The error exists in one of rdiff_backup classes, but I can not spot the error. The function `reduce` should be builtin, and I can not get the code to find the function. The code from rdiff looks like this: def get_total_dest_size_change(self): """Return total destination size change This represents the total change in the size of the rdiff-backup destination directory. """ addvals = [self.NewFileSize, self.ChangedSourceSize, self.IncrementFileSize] subtractvals = [self.DeletedFileSize, self.ChangedMirrorSize] for val in addvals + subtractvals: if val is None: result = None break else: def addlist(l): return reduce(lambda x,y: x+y, l) result = addlist(addvals) - addlist(subtractvals) self.TotalDestinationSizeChange = result return result And the error occurs in the locally defined addlist function. I've tried to import the builtin module in the top of the file (statistics.py), both like import __builtin__ and from __builtin__ import reduce and tried to change the namespace of the method like so: def addlist(l): return __builtin__.reduce(lambda x,y: x+y, l) But alas. Still the same error. I've not been able to find any good information or solution so far, so maybe someone with a little tighter knowledge about python could take stab at it. Thanks m Answer: `reduce(lambda x,y: x+y, l)` is an equivalent of `sum(l)`. Can you try whether `sum(l)` works? Also, which python version are you using (`sum` is available in version >= 2.3)
error using pywinauto Question: I am new to python and have just installed pywinauto using easy_install. I am trying to execute a simple code as follow: from pywinauto import application app = application.Application.start ('notepad.exe') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: type object 'Application' has no attribute 'start' As you see I am getting an error. I tried searching for an answer for this on the web but could not find out why this is happening. Please help. thanks in advance. VG Answer: Pywinauto is very confused about the naming convention used (I know - I wrote it!). There are two choices: a) create an instance of the Application class first and then call start() on it. >>> from pywinauto import Application >>> app = Application() >>> app.start('notepad.exe') <pywinauto.application.Application object at 0x022991B0> >>> app.UntitledNotepad.MenuItem("File -> Exit").Select() b) call the Application.Start() class method. (starts with uppercase 'S') >>> app = Application.Start('Notepad') >>> app.UntitledNotepad.MenuItem("File -> Exit").Select() Option b) is less typing :)
Adding and removing data to/from iCal Question: I need to add/remove calendar data to/from iCal. I google and found that I can uses [python library](http://mashupguide.net/1.0/html/ch15s04.xhtml) to create the ics file. With this, I can come up with applescript to run iCal to import the generated ics file to add calendar info to iCal, but for deleting calendar info, I don't know exactly what to do. * Q1 : How to delete calendar data in iCal with applescript or python? * Q2 : What would be other way to add calendar data in iCal? Answer: To delete the an event within iCal you need to be able to identify it. This can be done via the event's uid property or by some other identifying piece of information. Here's a quick example: tell application "iCal" tell calendar "Chuck" set evt to make new event at end with properties ¬ {description:"description", summary:"Summary", start date:get current date} set evtID to uid of evt set delEvt to every event whose summary is "Summary" delete delEvt end tell end tell You can find a list of the properties that are available for an event by taking a look at iCal's dictionary (File>Open Dictionary in Script Editor).
how to print this number in a shortest time using thread in python Question: this is my code : import thread k=0 b=0 def a(n): i = 0 while i<n: print i i += 1 j = 5000 while k < 5000: a(k) k+=1 for n in range(2,5): thread.start_new_thread(a,(j*n,)) and i want to Run three threads and a main thread, the main thread print 1,2,3,4,5,....5000 and the thread1 print 5001,5002,5003,...10000 the thread2 print 10001,10002,10003,...15000 the thread3 print 15001,15002,15003,...20000 they are at the same time so what can i do , thanks Answer: You should use threading instead of thread, since it's easier to implement and it works in almost every case. Now your code will be like: import threading class PrintNumber(Thread): def __init__(self, n): self.n = n def run(self): for i in range(n, n+5000): print i # create your threads here # use a cicle if needed thread = PrintNumber(0) # first 5000 numbers thread.start() thread = PrintNumber(5000) # next 5000 thread.start() Coded from mind and have not tested it, should be working anyway
returned dictionary value is 'None' python Question: I have a function in a file which I am calling in a separate script (as shown below). Printing directly from the function works correctly, however when I try to return the value to the script it sends 'None'. Any help would be appreciated. Thanks script: import modules.functions as f restype = 'THR' atomtype = 'CA' print f.AtomType(restype,atomtype) function: (this is the part of the function which returns the value) def AtomType(resName,atomType): def threonine(): print 'well im here' atoms = {'N' : 1, 'CA': 6, 'C' : 8, 'O' : 2, 'CB': 6, 'OG1': 1, 'CG2': 4, } print atoms[atomType] return atoms[atomType] residues = {'ALA' : hydrophobic, 'ARG' : arginine, 'ASN' : asparagine, 'ASP' : aspartate, 'CYS' : cysteine, 'GLN' : glutamine, 'GLU' : glutamate, 'GLY' : hydrophobic, 'HIS' : histidine, 'ILE' : hydrophobic, 'LEU' : hydrophobic, 'LYS' : lysine, 'MET' : methionine, 'PHE' : phenylalanine, 'PRO' : proline, 'SER' : serine, 'THR' : threonine, 'TRP' : tryptophan, 'TYR' : tyrosine, 'VAL' : hydrophobic, } residues[resName]() and the output I get is: well im here 6 None edit: added entire function Answer: Here's a guess: `AtomType` calls `threonine`, but doesn't return its return value.
Using Python object exported from DLL in an exe Question: I have a two-part event generator: **pyglobalexe (a stub to simulate events)** : #pragma comment(lib, "pyglobalextension.lib") #include <Python.h> __declspec(dllimport) PyObject* PyInit_pyglobalextension; __declspec(dllimport) PyObject* event_queue; int main() { int i; for(i=0; i<10; i++) { PyObject_CallMethod(event_queue, "put", "O", PyLong_FromLong(i*2)); } return 0; } **pyglobalextension** #include <Python.h> __declspec(dllexport) PyObject *event_queue = NULL; static PyObject * set_queue(PyObject *self, PyObject *args) { PyObject *temp; if(!PyArg_ParseTuple(args, "O", &temp)){ return NULL; } Py_XINCREF(temp); Py_XDECREF(event_queue); event_queue = temp; Py_INCREF(Py_None); return Py_None; } static PyMethodDef PyGlobalExtensionMethods[] = { {"set_queue", set_queue, METH_VARARGS, "Set a queue global."}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef PyGlobalExtensionModule = { PyModuleDef_HEAD_INIT, "pyglobalextension", NULL, -1, PyGlobalExtensionMethods }; PyMODINIT_FUNC PyInit_pyglobalextension(void) { return PyModule_Create(&PyGlobalExtensionModule); } Both files compile fine. pyglobalexe.exe crashes on the `PyObject_CallMethod` call. What do I have to change so that I can use the event_queue global from pyglobalextension in pyglobalexe? ===EDIT=== Sorry, should have made the use case more clear. Command prompt 1 (running python.exe) >>> import pyglobalextension >>> from queue import Queue >>> q = Queue() >>> pyglobalextension.set_queue(q) Command prompt 2 (once I'm done in command prompt 1). $> pyglobalexe I was hoping that I'd be able to go back to command prompt 1 and q.get() 10 numbers. Answer: 1. `event_queue` will be NULL, because nothing has called `set_queue` before you do `CallMethod`. 2. `PyInit_...` is a function, not a variable; and you don't call it, so the module and the `set_queue` don't even exist. Ad. edit: Above still stands. What you're doing requires interprocess communication, simple global variable won't do what you want to do (both processes have their own copy of it — only code of the DLL may be shared, data _is not_ — and in pyglobalexe, it's NULL).
Django - consume XML - RESTful Question: I have a python script running fine on my localhost. Its not an enterprise app or anything, just something I'm playing around with. It uses the "bottle" library. The app basically consumes an XML file (stored either locally or online) which contains elements with their own unique IDs, as well as some coordinates, eg mysite.com/23 will bring back the lat/long of element 23. I'm sure you're all familiar with REST at this stage anyway. Now, I want to put this online, but have had trouble finding a host that supports "bottle". I have, however, found a host that has django installed. So, my question is, how hard would it be to convert the following code from bottle to django? And can someone give me some pointers? I've tried to use common python libraries. thanks. from xml.dom.minidom import parseString from bottle import route, run import xml import urllib file = open('myfile.xml','r') data = file.read() dom = parseString(data) @route('/:number') def index(number="1"): rows = dom.getElementsByTagName("card")[0].getElementsByTagName("markers")[0].getElementsByTagName("marker") for row in rows: if row.getAttribute("number") == str(number): return str(xml.dumps({'long': row.getAttribute("lng"), 'lat': row.getAttribute("lat")}, sort_keys=True, indent=4)) return "Not Found" run(host='localhost', port=8080) Answer: I took your question as an opportunity to learn a bit more about Django. I used [The Django Book](http://www.djangobook.com/en/2.0/) as a reference. Starting with an empty Django site (`django-admin.py startproject testsite`), I've changed `urls.py` to this: from django.conf.urls.defaults import patterns, include, url from testsite.views import index urlpatterns = patterns('', url(r'^(\d+)$', index), ) And `views.py` to this: from django.http import HttpResponse from xml.dom.minidom import parseString import xml import urllib def index(request, number): data = open('myfile.xml', 'r').read() dom = parseString(data) rows = (dom.getElementsByTagName("card")[0] .getElementsByTagName("markers")[0] .getElementsByTagName("marker")) for row in rows: if row.getAttribute("number") == str(number): return HttpResponse(str(xml.dumps({'long': row.getAttribute("lng"), 'lat': row.getAttribute("lat")}, sort_keys=True, indent=4))) return HttpResponse("Not Found") Caveat: I've not tested the XML code, only Django-related one, which I've tested via `python manage.py runserver`. The Django Book contains a lot of information, including how to deploy this on a production server.
Google App Engine Bulkloader "Unexpected Thread Death" Question: I am trying to upload a moderetly sized csv file to google app engine using the bulkloader functionality, and it appears to die some of the way through with the following result: [INFO ] Logging to bulkloader-log-20110328.181531 [INFO ] Throttling transfers: [INFO ] Bandwidth: 250000 bytes/second [INFO ] HTTP connections: 8/second [INFO ] Entities inserted/fetched/modified: 20/second [INFO ] Batch Size: 10 [INFO ] Opening database: bulkloader-progress-20110328.181531.sql3 [INFO ] Connecting to notmyrealappname.appspot.com/_ah/remote_api [INFO ] Starting import; maximum 10 entities per post ...............................................................[INFO ] Unexpected thread death: WorkerThread-7 [INFO ] An error occurred. Shutting down... .........[ERROR ] Error in WorkerThread-7: <urlopen error [Errno -2] Name or service not known> [INFO ] 1740 entites total, 0 previously transferred [INFO ] 720 entities (472133 bytes) transferred in 32.3 seconds [INFO ] Some entities not successfully transferred It uploads about 700 of the 19k entries I am trying to upload, and I am wondering why it fails. I checked the csv file for errors like additional commas that could throw off the python csv reader and non ascii characters have been stripped out. Answer: Lifting the batch limit (batch_size) and rps limit (rps_limit) works, I use 1000 for the batch size and an rps limit of 500: appcfg.py upload_data --url= --application= --filename= --email= --batch_size=1000 --rps_limit=500
How to differentiate timeout error and other `URLError`s in Python? Question: How to differentiate timeout error and other `URLError`s in Python? **EDIT** When I catch a `URLError`, it can be `Temporary failure in name resolution` or `timeout`, or some other error? How can I tell one from another? Answer: I use code like Option 2, below... but for a comprehensive answer, look at [Michael Foord's urllib2 page](http://www.voidspace.org.uk/python/articles/urllib2.shtml) If you use either option 1 or option 2 below, you can add as much intelligence and branching as you like in the except clauses by looking at `e.code` or `e.reason` Option 1: from urllib2 import Request, urlopen, URLError, HTTPError req = Request(someurl) try: response = urlopen(req) except HTTPError, e: print 'The server couldn\'t fulfill the request.' print 'Error code: ', e.code except URLError, e: print 'We failed to reach a server.' print 'Reason: ', e.reason else: # everything is fine Option 2: from urllib import urlencode from urllib2 import Request # insert other code here... error = False error_code = "" try: if method.upper()=="GET": response = urlopen(req) elif method.upper()=="POST": response = urlopen(req,data) except IOError, e: if hasattr(e, 'reason'): #print 'We failed to reach a server.' #print 'Reason: ', e.reason error = True error_code = e.reason elif hasattr(e, 'code'): #print 'The server couldn\'t fulfill the request.' #print 'Error code: ', e.code error = True error_code = e.code else: # info is dictionary of server parameters, such as 'content-type', etc... info = response.info().dict page = response.read()
Truncating division in Python 3.2 Question: 1. Is integer floor division `//` faster than float division `/` in Python 3.2? If I know I'm going to be working with integers only, should I favour `//` instead of defaulting to `/`? 2. How do I get integer truncation behaviour in Python 3.2? `1/2 = 0` `-1/2 = 0` Thanks. Answer: from math import (floor, ceil) def trunc_div(a, b): c = a / b return floor(c) if c > 0 else ceil(c) Test it to make sure it's right. It's late and I'm doing math while sleepy. Actually, don't do that. While seeing if I could subclass int to do truncated division (don't do that either (also, it didn't work)), it occurred to me that `int()` itself will truncate reals, resulting in this: def trunc_div(a, b): return int(a / b) Which is a rather foolish wrapper. So, just use float division, and truncate it with `int()`: >>> int(1 / 2) 0 >>> int(-1 / 2) 0 This gets you pretty close to the infix notation you desired. The moral of this story is... don't let your friends code while drowsy.
returning data in python Question: I'm currently looking through the "Dive Into Python" to pick up the language and I was a bit confused about chapter 5's example 5.10. UserDict Normal Methods Example 5.10. UserDict Normal Methods def copy(self): if self.__class__ is UserDict: return UserDict(self.data) import copy return copy.copy(self) where `data` is a dictionary. I notice that if the class is a UserDict type, then it returns `UserDict(self.data)`. What I'm confused about is, why do you need to return `UserDict(self.data)` instead of just returning `self.data`? Isn't self.data a dictionary which you can return? If someone can explain the difference between returning `UserDict(self.data)` and `self.data`, I would appreciate it greatly. Answer: It returns a new `UserDict` object because `.copy()` is expected to return an object of the same type its copying.
Python: Imaplib error Question: import serial import imaplib from time import sleep IMAP_SERVER='imap.gmail.com' IMAP_PORT=993 ser= serial.Serial ('/dev/ttyACM0',9600) while True: M = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT) rc, resp = M.login('user@gmail.com', 'Password') print rc, resp M.select() for msg_num in M.search("INBOX", "UNDELETED")[1][0].split(): msg = M.fetch('1', '(BODY.PEEK[TEXT])') try: String = msg[1][0][1][139:148] except TypeError: continue print String if String == "This is just a test...": ser.write('0') sleep(1) I'm a new beginner in python programming and the above python code is one that I'm using for a program I want to do. When I run this in a terminal I get the response that I have authenticated my account and then it displays the message between characters 139 & 161, which is the following in the example email: This is just a test... This is printed out in the terminal. After a few times the program checks my email this error comes out: Traceback (most recent call last): File "/home/wilson/Desktop/Best_Gmail_yet _Dont_touch.py", line 11, in <module> rc, resp = M.login('user@gmail.com', 'password') File "/usr/lib/python2.6/imaplib.py", line 500, in login raise self.error(dat[-1]) imaplib.error: [ALERT] Web login required: http://mail.google.com/support /bin/answer.py?answer=78754 (Failure) Does anyone have any ideas to help out and is there any other way to write to serial, Thanks in advance! Answer: From the error message url (<http://mail.google.com/support/bin/answer.py?answer=78754>): > Make sure your mail client isn't set to check for new mail too often. If > your mail client checks for new messages more than once every 10 minutes, > your client might repeatedly request your username and password. I'd guess you're connecting to the server too frequently, and gmail gets suspicious. You also appear to be opening multiple imap connections without closing any of them. I don't know exactly what you're trying to do but I'd guess there's a more parsimonious way, probably involving just one connection that you maintain and poll from time to time.
Python + MongoDB - Cursor iteration too slow Question: I'm actually working in a search engine project. We are working with python + mongoDb. I'm having the following problem: I have a pymongo cursor after excecuting a find() command to the mongo db. The pymongo cursor have around 20k results. I have noticed that the iteration over the pymongo cursor is really slow compared with a normal iteration over for example a list of the same size. I did a little benchmark: -iteration over a list of 20k strings: 0.001492 seconds -iteration over a pymongo cursor with 20k results: 1.445343 seconds The difference is really a lot. Maybe not a problem with this amounts of results, but if I have millons of results the time would be unacceptable. Has anyone got an idea of why pymongo cursors are too slow to iterate? Any idea of how can I iterate the cursor in less time? Some extra info: * Python v2.6 * PyMongo v1.9 * MongoDB v1.6 32 bits Answer: Is your pymongo installation using the included [C extensions](http://api.mongodb.org/python/current/installation.html#dependencies- for-installing-c-extensions-on-unix)? >>> import pymongo >>> pymongo.has_c() True I spent most of last week trying to debug a moderate-sized query and corresponding processing that took 20 seconds to run. Once the C extensions were installed, the whole same process took roughly a second. To install the C extensions in Debian, install the python development headers before running easy install. In my case, I also had to remove the old version of pymongo. Note that this will compile a binary from C, so you need all the usual tools. (GCC, etc) # on ubuntu with pip $ sudo pip uninstall pymongo $ sudo apt-get install python-dev build-essential $ sudo pip install pymongo
Mod_wsgi pylons (ckan) installation not working Question: I am setting up CKAN, a pylons application according to these instructions: <http://packages.python.org/ckan/deployment.html> But when I point to the server (no DNS setup yet) using IP or hostname, I only see apache's greeting page, sugesting the ckan app is not being loaded. here is my mod_wsgi script: import os instance_dir = '/home/flavio/var/srvc/ckan.emap.fgv.br' config_file = 'ckan.emap.fgv.br.ini' pyenv_bin_dir = os.path.join(instance_dir, 'pyenv', 'bin') activate_this = os.path.join(pyenv_bin_dir, 'activate_this.py') execfile(activate_this, dict(__file__=activate_this)) from paste.deploy import loadapp config_filepath = os.path.join(instance_dir, config_file) from paste.script.util.logging_config import fileConfig fileConfig(config_filepath) application = loadapp('config:%s' % config_filepath) here is my virtual host configuration: <VirtualHost *:80> ServerName dck093 ServerAlias dck093 WSGIScriptAlias / /home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/bin/ckan.emap.fgv.br.py # pass authorization info on (needed for rest api) WSGIPassAuthorization On ErrorLog /var/log/apache2/ckan.emap.fgv.br.error.log CustomLog /var/log/apache2/ckan.emap.fgv.br.custom.log combined <Directory /home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/bin> Order deny,allow Allow from all </Directory> </VirtualHost> I try to disable the 000-default site (with a2dissite), but that dind't help.After doing this I get an Internal server error page. After a fixing some permissions I managed to get this Pylons error log: sudo tail /var/log/apache2/ckan.emap.fgv.br.error.log [Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = self.application(environ, start_response) [Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/usr/lib/pymodules/python2.6/repoze/who/middleware.py", line 107, in __call__ [Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = app(environ, wrapper.wrap_start_response) [Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/lib/python2.6/site-packages/pylons/middleware.py", line 201, in __call__ [Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] self.app, environ, catch_exc_info=True) [Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/home/flavio/var/srvc/ckan.emap.fgv.br/pyenv/lib/python2.6/site-packages/pylons/util.py", line 94, in call_wsgi_application [Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] app_iter = application(environ, start_response) [Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] File "/usr/lib/pymodules/python2.6/weberror/evalexception.py", line 226, in __call__ [Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] "The EvalException middleware is not usable in a " [Wed Mar 30 12:38:32 2011] [error] [client 10.250.48.110] AssertionError: The EvalException middleware is not usable in a multi-process environment Can anyone point out what am I missing? Answer: Since you're deploying on apache, ensure that you are not in interactive debug mode - which uses EvalException. In your Pylons config file (ckan.emap.fgv.br.ini) ensure you have this: [app:main] set debug = false
os.environ does not contain HOST variable Question: What could be the cause that os.environ does not contain the HOST environment variable under Linux, except I set it explicitly for the interpreter environment? > echo $HOST; python -c 'import os; print "HOST" in os.environ' bbox False > echo $HOST; HOST=$HOST python -c 'import os; print "HOST" in os.environ' bbox True EDIT: Thanks for the suggestion to `export`, however, why are most of the other variables available, like `USER, PS1, LANG,...` without explicitly exporting them? Answer: This means that you've got a variable called `HOST` defined in your shell, but have not exported it. Try this: export HOST Environment variables are not passed to child processes unless they have been exported this way.
Error parsing a DTD using lxml Question: I'm trying to write a validation script that will validate XML against the NITF DTD, <http://www.iptc.org/std/NITF/3.4/specification/dtd/nitf-3-4.dtd>. Based on [this post](http://stackoverflow.com/questions/15798/how-do-i- validate-xml-against-a-dtd-file-in-python) I came up with the following simple script to validate a NITF XML document. Bellow is the error message I get when the script is run, which isn't very descriptive and makes it hard to debug. Any help is appreciated. #!/usr/bin/env python def main(): from lxml import etree, objectify from StringIO import StringIO f = open('nitf_test.xml') xml_doc = f.read() f.close() f = open('nitf-3-4.dtd') dtd_doc = f.read() f.close() dtd = etree.DTD(StringIO(dtd_doc)) tree = objectify.parse(StringIO(xml_doc)) dtd.validate(tree) if __name__ == '__main__': main() Traceback error message: Traceback (most recent call last): File "./test_nitf_doc.py", line 23, in <module> main() File "./test_nitf_doc.py", line 16, in main dtd = etree.DTD(StringIO(dtd_doc)) File "dtd.pxi", line 43, in lxml.etree.DTD.__init__ (src/lxml/lxml.etree.c:126056) File "dtd.pxi", line 117, in lxml.etree._parseDtdFromFilelike (src/lxml/lxml.etree.c:126727) lxml.etree.DTDParseError: error parsing DTD If I change the line: dtd = etree.DTD(StringIO(dtd_doc)) To: dtd = etree.DTD(dtd_doc) The error I get is: lxml.etree.DTDParseError: failed to load external entity "NULL" Answer: I took a look at the `nitf-3-4.dtd` and found that it references an external module `xhtml-ruby-1.mod` which can be [downloaded at this link](http://www.iptc.org/std/NITF/3.4/specification/dtd/xhtml-ruby-1.mod). This needs to be present in the current directory so the DTD parser can load it. Full working example (assuming you have a valid NITF document handy): % wget http://www.iptc.org/std/NITF/3.4/specification/dtd/nitf-3-4.dtd % wget http://www.iptc.org/std/NITF/3.4/specification/dtd/xhtml-ruby-1.mod Python code: from lxml import etree, objectify dtd = etree.DTD(open('nitf-3-4.dtd', 'rb')) tree = objectify.parse(open('nitf_test.xml', 'rb')) print dtd.validate(tree) Output: % python nitf_test.py True
join two lists of dictionaries on a single key Question: Given `n` lists with `m` dictionaries as their elements, I would like to produce a new list, with a joined set of dictionaries. Each dictionary is guaranteed to have a key called "index", but could have an arbitrary set of keys beyond that. The non-index keys will never overlap across lists. For example, imagine the following two lists: l1 = [{"index":1, "b":2}, {"index":2, "b":3}, {"index":3, "green":"eggs"}] l2 = [{"index":1, "c":4}, {"index":2, "c":5}] (`"b"` would never appear in `l2`, since it appeared in `l1`, and similarly, `"c"` would never appear in `l1`, since it appeared in `l2`) I would like to produce a joined list: l3 = [{"index":1, "b":2, "c":4}, {"index":2, "b":3, "c":5}, {"index":3, "green":"eggs"}] What is the most efficient way to do this in Python? Answer: from collections import defaultdict l1 = [{"index":1, "b":2}, {"index":2, "b":3}, {"index":3, "green":"eggs"}] l2 = [{"index":1, "c":4}, {"index":2, "c":5}] d = defaultdict(dict) for l in (l1, l2): for elem in l: d[elem['index']].update(elem) l3 = d.values() # l3 is now: [{'b': 2, 'c': 4, 'index': 1}, {'b': 3, 'c': 5, 'index': 2}, {'green': 'eggs', 'index': 3}] **EDIT** : Since `l3` is not guaranteed to be sorted (`.values()` returns items in no specific order), you can do as @user560833 suggests: from operator import itemgetter ... l3 = sorted(d.values(), key=itemgetter("index"))
Error parsing emails using Python's email module when the encoding is in shift_jis Question: I am getting an error that says "UnicodeDecodeError: 'shift_jis' codec can't decode bytes in position 2-3: illegal multibyte sequence" when I try to use my email parser to decode a shift_jis encoded email and convert it to unicode. The code and email can be found below: import email.header import base64 import sys import email def getrawemail(): line = ' ' raw_email = '' while line: line = sys.stdin.readline() raw_email += line return raw_email def getheader(subject, charsets): for i in charsets: if isinstance(i, str): encoding = i break if subject[-2] == "?=": encoded = subject[5 + len(encoding):len(subject) - 2] else: encoded = subject[5 + len(encoding):] return (encoding, encoded) def decodeheader((encoding, encoded)): decoded = base64.b64decode(encoded) decoded = unicode(decoded, encoding) return decoded raw_email = getrawemail() msg = email.message_from_string(raw_email) subject = decodeheader(getheader(msg["Subject"], msg.get_charsets())) print subject Email: <http://pastebin.com/L4jAkm5R> I have read on another Stack Overflow question that this may be related to a difference between how Unicode and shift_jis are encoded (they referenced [this](http://support.microsoft.com/kb/170559 "this") Microsoft Knowledge Base article). If anyone knows what in my code could be causing it to not work, or if this is even reasonably fixable, I would very much appreciate finding out how. Answer: Starting with this string: In [124]: msg['Subject'] Out[124]: '=?ISO-2022-JP?B?GyRCNS5KfSRLJEgkRiRiQmdAWiRKJCpDTiRpJDskLCQiJGo' `=?ISO-2022-JP?B?` means the string is ISO-2022-JP encoded, then base64 encoded. In [125]: msg['Subject'].lstrip('=?ISO-2022-JP?B?') Out[125]: 'GyRCNS5KfSRLJEgkRiRiQmdAWiRKJCpDTiRpJDskLCQiJGo' Unfortunately, trying to reverse that process results in an error: In [126]: base64.b64decode(msg['Subject'].lstrip('=?ISO-2022-JP?B?')) TypeError: Incorrect padding Reading this [SO answer](http://stackoverflow.com/questions/419977/japanese- email-subject-encoding/492543#492543) lead me to try adding '?=' to the end of the string: In [130]: print(base64.b64decode(msg['Subject'].lstrip('=?ISO-2022-JP?B?')+'?=').decode('ISO-2022-JP')) 貴方にとても大切なお知らせがあり According to google translate, this may be translated as "You know there is a very important". So it appears the subject line has been truncated.
django render_to_response is not defined error Question: Hi I am getting this error, while I tried make a simple app. NameError at /first/ global name 'render_to_response' is not defined Request Method: GET Request URL: http://localhost:8000/first/?preview Django Version: 1.3 Exception Type: NameError Exception Value: global name 'render_to_response' is not defined Exception Location: /home/naveen/django_projects/myproject/first/views.py in index, line 5 Python Executable: /usr/bin/python Python Version: 2.6.6 Python Path: ['/home/naveen/django_projects/myproject', '/usr/local/lib/python2.6/dist-packages/pip-0.8.3-py2.6.egg', '/usr/local/lib/python2.6/dist-packages', '/usr/local/lib/python2.6/dist-packages/django_evolution-0.6.2-py2.6.egg', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0'] Server time: Thu, 31 Mar 2011 14:50:32 -0500 any ideas?! Answer: Did you try import render_to_response as `from django.shortcuts import render_to_response`?
Best 3D library to model robotic motion Question: A short while I asked for suggestions on choosing a Python-compatible 3D graphics library for robotic motion modelling (using inverse kinematics in Python). After doing a bit of research and redefining my objectives I hope I can ask once again for a bit of assistance. At the time I thought Blender was the best option - but now I'm having doubts. One key objective I have is the ability integrate the model into a custom GUI (wxPython). Seems like this might be rather difficult (and I'm unsure of the performance requirements). I think I'm now leaning more towards OpenGL (PyOpenGL + wxglcanvas), but I'm still struggling to to determine if it's the right tool for the job. I'm more of a CAD person, so I have trouble envisioning how to draw complex objects in the API and create motion. I read I could design the object in, say Blender, then import it into OpenGL somehow, but I'm unsure of the process? And how difficult is manipulating motion of objects? For example, if I create a joint between two links, and I move one link, would the other link move dynamically according to the first, or would I need to program each link's movement independently? Have I missed any obvious tools? I'm not looking for complete robotic modelling packages, I would like to start from scratch so I can incorporate it into my own program. For for learning more than anything. So far I've already looked into vPython, Pyglet, Panda3D, Ogre, and several professional CAD packages. Thanks Answer: There is a similar project going on that implements a [robotic toolbox](http://code.google.com/p/robotics-toolbox-python/) for matlab and python, it has "Rudimentary 3D graphics", but you can always interface it with blender with a well knit [script](http://en.wikibooks.org/wiki/Blender_3D%3a_Noob_to_Pro/Advanced_Tutorials/Python_Scripting/Introduction), it will be less work than reinventing the wheel
Error loading MySQLdb module in MACOSX10.6 (Apache & mod_wsgi) Question: > **Possible Duplicate:** > [Python import MySQLdb error - Mac > 10.6](http://stackoverflow.com/questions/4730787/python-import-mysqldb- > error-mac-10-6) I have a question that when I was using apache with wsgi to run a django project the system, mysqldb cannot be loaded, and the system report such an error like following: ... [Fri Apr 01 11:00:11 2011] [error] [client ::1] File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/admin/util.py", line 1, in <module> [Fri Apr 01 11:00:11 2011] [error] [client ::1] from django.db import models [Fri Apr 01 11:00:11 2011] [error] [client ::1] File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/__init__.py", line 78, in <module> [Fri Apr 01 11:00:11 2011] [error] [client ::1] connection = connections[DEFAULT_DB_ALIAS] [Fri Apr 01 11:00:11 2011] [error] [client ::1] File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/utils.py", line 93, in __getitem__ [Fri Apr 01 11:00:11 2011] [error] [client ::1] backend = load_backend(db['ENGINE']) [Fri Apr 01 11:00:11 2011] [error] [client ::1] File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/utils.py", line 33, in load_backend [Fri Apr 01 11:00:11 2011] [error] [client ::1] return import_module('.base', backend_name) [Fri Apr 01 11:00:11 2011] [error] [client ::1] File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module [Fri Apr 01 11:00:11 2011] [error] [client ::1] __import__(name) [Fri Apr 01 11:00:11 2011] [error] [client ::1] File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/gis/db/backends/mysql/base.py", line 1, in <module> [Fri Apr 01 11:00:11 2011] [error] [client ::1] from django.db.backends.mysql.base import * [Fri Apr 01 11:00:11 2011] [error] [client ::1] File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 14, in <module> [Fri Apr 01 11:00:11 2011] [error] [client ::1] raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) [Fri Apr 01 11:00:11 2011] [error] [client ::1] TemplateSyntaxError: Caught ImproperlyConfigured while rendering: Error loading MySQLdb module: dlopen(/Users/LechterLin/.python-eggs/MySQL_python-1.2.3-p y2.7-macosx-10.6-intel.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib [Fri Apr 01 11:00:11 2011] [error] [client ::1] Referenced from: /Users/LechterLin/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so [Fri Apr 01 11:00:11 2011] [error] [client ::1] Reason: image not found the wsgi file in django project and httpd.conf in apache are correct, cause I use the same file(or command) in WindowsXP the project can run successfully. This report is similar with the error I only install python and MySQL without MySQL-python adapter. So do these two error have some relationship? I searched this error through google, seems this problem can be only found in MACOSX10.6. My system issues are like following: Os: MACOSX10.6.7 snow leopard MySQL: 5.5.10 python: 2.7 MySQL-python adapter: 1.2.3 Apache: 2.2.17 mod_wsgi: 3.3 django: 1.3 Hope to get your help! Thanks very much! Answer: Go read: <https://groups.google.com/d/topic/modwsgi/aNSeRUiF1OY/discussion> Go through the checks there, adjusting as necessary based on where you have things installed. Then follow up to that discussion on mod_wsgi mailing list with what results you get so can be debugged further. StackOverflow does not work as a very good place to try and debug issues, only useful if someone knows the exact answer already. Unfortunately the last person with the problem could not be bothered to respond to the questions or indicate how they solved the problem so don't have a definitive short answer as yet.
Http connection freezes when request's content-length exceeds real content length Question: I have a very basic python script that does HTTP connection. import socket def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = "192.168.56.21" s.connect((host, 80)) msg = """GET /lol /HTTP1.1 Content-Length: 10 %s""" % ("*" * 9) s.send(msg) print msg print s.recv(1000) if __name__ == "__main__": main() As you can see, Content-Length header exceeds real content length. When I run this script, it freezes for 5 mins, and after that I got record in apache log that request took 5min to execute and got HTTP 400 response. 192.168.56.21 - - [01/Apr/2011:15:07:52 +0300] "GET /lol /HTTP1.1" 400 358 "-" "-" 47 531 300011809 I am ok with that, but what I do not understand is why apache freezes for 5 min and keeps connection open during that time. apache2 3947 www-data 19u IPv6 17165 TCP 192.168.56.21:www->192.168.56.21:53112 (ESTABLISHED) python2.6 4636 meuser 3u IPv4 17164 TCP 192.168.56.21:53112->192.168.56.21:www (ESTABLISHED) I assume that apache waits for amount of bytes specified in Content-Length until some timeout happens and it throws 400 Bad Request. I tried it against production sites and obviously I got response immediately. Can someone explain what is going on here on TCP level and what I am missing apache configuration - I want to get rid of such 5 min waiting. Answer: OK, it is Timeout directive in apache conf. <http://httpd.apache.org/docs/2.2/mod/core.html#timeout>
Python Smooth Time Series Data Question: I have some data in python that is unixtime, value: [(1301672429, 274), (1301672430, 302), (1301672431, 288)...] Time constantly steps by one second. How might I reduce this data so the timestamp is every second, but the value is the average of the surrounding 10 values? Fancier rolling averages would be good too, but this data is graphed so it is mostly to smooth out the graph. Follow up of ( [TSQL Rolling Average of Time Groupings](http://stackoverflow.com/questions/5515090/tsql-rolling-average-of- time-groupings) after coming to the conclusion that trying to do this in SQL is a route of pain). Answer: Using <http://www.scipy.org/Cookbook/SignalSmooth>: import numpy def smooth(x,window_len=11,window='hanning'): if x.ndim != 1: raise ValueError, "smooth only accepts 1 dimension arrays." if x.size < window_len: raise ValueError, "Input vector needs to be bigger than window size." if window_len<3: return x if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']: raise ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'" s=numpy.r_[2*x[0]-x[window_len-1::-1],x,2*x[-1]-x[-1:-window_len:-1]] if window == 'flat': #moving average w=numpy.ones(window_len,'d') else: w=eval('numpy.'+window+'(window_len)') y=numpy.convolve(w/w.sum(),s,mode='same') return y[window_len:-window_len+1] I get what seems to be good results with (Not that I understand the math): if form_results['smooth']: a = numpy.array([x[1] for x in results]) smoothed = smooth(a,window_len=21) results = zip([x[0] for x in results], smoothed)
Trying to implement import-> debug mode module Question: So I am attempting to make a module that, when imported, will cause any exception to drop into pdb. I'm thinking it will look something like this: #file A.py import pdbOnException a = 1/0 print a #file pdbOnException import sys, pdb magic_object = # do magic stuff to get an object that, when called, does what I want :D try: magic_object() except: tb = sys.exc_info()[2] pdb.post_mortem(tb) Hopefully it is fairly obvious what I am trying to do. I am trying to make it so that any module that imports this will have its unhandled exceptions go to pdb. Edit: I thought I should add what I want to use this for, and see if you know anything about that. I am planning on adding the module to eclipse's "Forced Builtins" so that eclipse will have this functionality (it is SORELY needed) Can anyone help me out? Edit2: after playing with eclipse a bunch, it looks like there is NO WAY to force eclipse to run a set of code (i.e. like PYTHONSTARTUP) prior to running any code. Which sucks. Therefore I think I will just go for the decorator. If you still have an idea of how to do this by just importing modules, I am all ears. It could be added to the IDLE startup script. Update: I just got something working using decorators, but the user has to call it for their main function (which isn't the end of the world... but I would like even more functionality). Here it is: def pdb_on_exception(function): def returnfunction(*args, **kwargs): try: return function(*args, **kwargs) except Exception as E: traceback.print_tb(sys.exc_info()[2]) print E tb = sys.exc_info()[2] pdb.post_mortem(tb) return returnfunction This will drop you into pdb if there is an unhandled exception on the function that is being decorated. Which is cool but still not what I want :D Answer: That's pretty trivial, you just hook into sys.excepthook: fullofeels.py: import sys, pdb def except_hook(exctype, value, traceback): if previous_except_hook: previous_except_hook(exctype, value, traceback) pdb.post_mortem(traceback) previous_except_hook = sys.excepthook sys.excepthook = except_hook Usage: Normally we just get a traceback: >>> 1/0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero But import fullofeels, and we fall into pdb: >>> import fullofeels >>> 1/0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero > <stdin>(1)<module>() (Pdb) Tada! I have no idea how many eels are in that hovercraft, but for simple cases it works.
How do you get all classes defined in a module but not imported? Question: I've already seen the following question but it doesn't quite get me where I want: [Python: Get list of all classes within current module](http://stackoverflow.com/questions/1796180/python-get-list-of-all- classes-within-current-module) In particular, I do not want classes that are imported, e.g. if I had the following module: from my.namespace import MyBaseClass from somewhere.else import SomeOtherClass class NewClass(MyBaseClass): pass class AnotherClass(MyBaseClass): pass class YetAnotherClass(MyBaseClass): pass If I use `clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)` like the accepted answer in the linked question suggests, it would return `MyBaseClass` and `SomeOtherClass` in addition to the 3 defined in this module. How can I get only `NewClass`, `AnotherClass` and `YetAnotherClass`? Answer: Inspect the `__module__` attribute of the class to find out which module it was defined in.
Django AttributeError: type object 'User' has no attribute '_collect_sub_objects' Question: I'm trying to reinstall a site I haven't used in several months and am getting an error I can't seem to find a solution for. Running the latest trunk of django, python 2.6. Here is the stack trace::: [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] mod_wsgi (pid=9458): Exception occurred processing WSGI script '/home/www/vhosts/site/site.wsgi'. [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] Traceback (most recent call last): [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] File "/usr/lib/python2.6/site-packages/django/core/handlers/wsgi.py", line 273, in __call__ [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] response = self.get_response(request) [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 169, in get_response [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 214, in handle_uncaught_exception [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] if resolver.urlconf_module is None: [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] File "/usr/lib/python2.6/site-packages/django/core/urlresolvers.py", line 274, in _get_urlconf_module [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] self._urlconf_module = import_module(self.urlconf_name) [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] File "/usr/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] __import__(name) [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] File "/home/www/vhosts/site.com/site/urls.py", line 7, in <module> [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] from site.feeds import * [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] File "/home/www/vhosts/site.com/site/feeds.py", line 6, in <module> [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] from site.content.models import * [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] File "/home/www/vhosts/site.com/site/content/models.py", line 14, in <module> [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] from site.authors.models import Author [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] File "/home/www/vhosts/site.com/site/authors/models.py", line 11, in <module> [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] class Author(models.Model): [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] File "/usr/lib/python2.6/site-packages/django/db/models/base.py", line 97, in __new__ [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] new_class.add_to_class(obj_name, obj) [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] File "/usr/lib/python2.6/site-packages/django/db/models/base.py", line 217, in add_to_class [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] value.contribute_to_class(cls, name) [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] File "/usr/lib/python2.6/site-packages/django/db/models/fields/related.py", line 891, in contribute_to_class [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] super(ForeignKey, self).contribute_to_class(cls, name) [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] File "/usr/lib/python2.6/site-packages/django/db/models/fields/related.py", line 112, in contribute_to_class [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] self.do_related_class(other, cls) [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] File "/usr/lib/python2.6/site-packages/django/db/models/fields/related.py", line 124, in do_related_class [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] self.contribute_to_related_class(other, self.related) [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] File "/home/www/vhosts/site.com/site/utils/nullableforeignkey.py", line 38, in contribute_to_related_class [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] setattr(cls, _original_csb_attr_name, cls._collect_sub_objects) [Fri Apr 01 19:31:00 2011] [error] [client X.X.X.X] **AttributeError: type object 'User' has no attribute '_collect_sub_objects'** **Here is the file in question ::** from django.db import models, connection class NullableForeignKey(models.ForeignKey): """ Just like a ForeignKey, but when related objects are deleted this object is *not* deleted. As the name implies, this field is always NULLable. """ def __init__(self, *args, **kwargs): kwargs['null'] = kwargs['blank'] = True super(NullableForeignKey, self).__init__(*args, **kwargs) def contribute_to_related_class(self, cls, related): super(NullableForeignKey, self).contribute_to_related_class(cls, related) # define a method name to map the original `_collect_sub_objects` method to _original_csb_attr_name = '_original_collect_sub_objects' this_field = self def _new_collect_sub_objects(self, *args, **kwargs): # NULL out anything related to this object. qn = connection.ops.quote_name for related in self._meta.get_all_related_objects(): if isinstance(related.field, this_field.__class__): table = qn(related.model._meta.db_table) column = qn(related.field.column) sql = "UPDATE %s SET %s = NULL WHERE %s = %%s;" % (table, column, column) connection.cursor().execute(sql, [self.pk]) # Now proceed with collecting sub objects that are still tied via FK getattr(self, _original_csb_attr_name)(*args, **kwargs) # monkey patch the related classes _collect_sub_objects method. # store the original method in an attr named `_original_csb_attr_name` if not hasattr(cls, _original_csb_attr_name): setattr(cls, _original_csb_attr_name, cls._collect_sub_objects) setattr(cls, '_collect_sub_objects', _new_collect_sub_objects) # Prevent deletion completely if item has related children from django.db.models import OneToOneField, ObjectDoesNotExist from django.utils.encoding import StrAndUnicode from django.utils.translation import ugettext as _ class ForeignKeysExist(StrAndUnicode, Exception): def __init__(self, parent, child, field): ''' Arguments: parent - parent instance (that contains child records) child - object that have foreign key pointing to the parent instance field - child instance foreign key field name ''' self.parent = parent #parent instance self.child = child #child that has reference to this parent self.field = field #field in the child class that points to the parent self.msg = 'Child record %s.%s exists for %s' % (_(child), _(field), _(parent)) super(ForeignKeysExist, self) def __unicode__(self): return self.msg class NoDeleteCascadeMixin(object): """ Mixin to prevent deletion of model if there exists any children """ def delete(self): # Copied sanity test from django.db.models.ModelBase.delete assert self._get_pk_val() is not None, "%s object can't be deleted because its %s attribute is set to None." % (self._meta.object_name, self._meta.pk.attname) opts = self._meta for related in opts.get_all_related_objects(): rel_accessor = related.get_accessor_name() if isinstance(related, OneToOneField): try: o = getattr(self, rel_accessor) except ObjectDoesNotExist: pass # No item in one to one else: raise ForeignKeysExist(related.parent_model._meta.object_name, opts.object_name, related.field.name) else: rel_manager = getattr(self, rel_accessor) if rel_manager.count(): raise ForeignKeysExist(related.parent_model._meta.object_name, related.model._meta.object_name, related.field.name) super(NoDeleteCascadeMixin, self).delete() Answer: Looking at the django source code, `_collect_sub_objects` was removed somewhere between release 1.2 and 1.3. See the [`changes`](http://code.djangoproject.com/changeset?old_path=/django/branches/releases/1.2.X/django/db/models/base.py&old=15968&new_path=/django/branches/releases/1.3.X/django/db/models/base.py&new=15968). * * * Django now has an **`on_delete`** option for ForeignKeys, [docs](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.on_delete). **ForeignKey.on_delete** > When an object referenced by a ForeignKey is deleted, Django by default > emulates the behavior of the SQL constraint ON DELETE CASCADE and also > deletes the object containing the ForeignKey. This behavior can be > overridden by specifying the on_delete argument. For example, if you have a > nullable ForeignKey and you want it to be set null when the referenced > object is deleted: `user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)` > The possible values for on_delete are found in django.db.models: * CASCADE: Cascade deletes; the default. * PROTECT: Prevent deletion of the referenced object by raising django.db.models.ProtectedError, a subclass of django.db.IntegrityError. * SET_NULL: Set the ForeignKey null; this is only possible if null is True. * SET_DEFAULT: Set the ForeignKey to its default value; a default for the ForeignKey must be set. * SET(): Set the ForeignKey to the value passed to SET(), or if a callable is passed in, the result of calling it. In most cases, passing a callable will be necessary to avoid executing queries at the time your models.py is imported: def get_sentinel_user(): return User.objects.get_or_create(username='deleted')[0] class MyModel(models.Model): user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user)) * DO_NOTHING: Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add a SQL ON DELETE constraint to the database field (perhaps using initial sql).
Is there a standard Python data structure that keeps thing in sorted order? Question: I have a set of ranges that might look something like this: [(0, 100), (150, 220), (500, 1000)] I would then add a range, say `(250, 400)` and the list would look like this: [(0, 100), (150, 220), (250, 400), (500, 1000)] I would then try to add the range `(399, 450)`, and it would error out because that overlapped `(250, 400)`. When I add a new range, I need to search to make sure the new range does not overlap an existing range. And no range will ever be in the list that overlaps another range in the list. To this end, I would like a data structure that cheaply maintained its elements in sorted order, and quickly allowed me to find the element before or after a given element. Is there a better way to solve this problem? Is there a data structure like that available in Python? I know the `bisect` module exists, and that's likely what I will use. But I was hoping there was something better. **Edit:** I solved this problem using the `bisect` module. Here is a link to the code. It's a bit longish, so I won't post it here: [Implementation of byte range list](http://paste.lisp.org/+2LJE) Answer: It looks like you want something like [bisect's](http://docs.python.org/release/2.7.1/library/bisect.html) insort_right/insort_left. The bisect module works with lists and tuples. import bisect l = [(0, 100), (150, 300), (500, 1000)] bisect.insort_right(l, (250, 400)) print l # [(0, 100), (150, 300), (250, 400), (500, 1000)] bisect.insort_right(l, (399, 450)) print l # [(0, 100), (150, 300), (250, 400), (399, 450), (500, 1000)] You can write your own `overlaps` function, which you can use to check before using `insort`. I assume you made a mistake with your numbers as `(250, 400)` overlaps `(150, 300)`. `overlaps()` can be written like so: def overlaps(inlist, inrange): for min, max in inlist: if min < inrange[0] < max and max < inrange[1]: return True return False
Export each object on scene to another file Question: I want to ask you, how can I export all objects to scene to seperate files in blender using python scripts ? I want to export it to fbx, to have something like this: Object File Car Car.fbx Boat Boat.fbx etc.. Each object will be have his of file. I'm tring to use 'export_fbx.py', I paste source to editor in blender, and write something below pasted code like: for ob in bpy.data.objects: save(bpy.ops.mesh,ob,'C:\\images\\'+ ob.name + '.fbx') But this doesn't work :/ I need something like this, beacouse I have 45 objects in scene, and I have to export each other to fbx, to import it in XNA. Answer: as per <http://www.blender.org/documentation/blender_python_api_2_61_0/bpy.ops.export_scene.html#bpy.ops.export_scene.fbx> loop over all objects in the scene selecting each individually and calling bpy.ops.export_scene.fbx with the use_selection parameter set
multiply a matrix by an integer in python Question: I know how to multiply two matrices(under a class). Below I show my code. However I can not seem to figure out how to multiply a matrix and an integer in Python. **Update** : Example of a matrix. L=[[1,2],[3,4],[5,6]] 3*L # [[1,6],[9,12],[15,18]] def __mul__(self,other): '''this will multiply two predefined matrices where the number of columns in the first is equal to the number of rows in the second.''' L=self.L L2=other.L result=[] if len(L[0])==len(L2): for i in range(len(L)): row=[] for j in range(len(L2[0])): var=0 for k in range(len(L2)): var=var+L[i][k]*L2[k][j] row=row+[var] result = result+[row] return matrix(result) else: raise ValueError('You may not only multiply m*n * n*q matrices.') Answer: Depends on what you mean by `matrix`, but with [numpy](http://numpy.org/), it would be just like: import numpy as np M= np.arange(9).reshape(3, 3) # array([[0, 1, 2], # [3, 4, 5], # [6, 7, 8]]) 2* M # array([[ 0, 2, 4], # [ 6, 8, 10], # [12, 14, 16]]) or M= np.matrix([[1, 2], [3, 4]]) # matrix([[1, 2], # [3, 4]]) 2* M # matrix([[2, 4], # [6, 8]])
Installing the Swampy Python module on Windows Question: I am trying to install the [Swampy module](http://www.greenteapress.com/thinkpython/swampy/install.html) on Python, but there is a lot that is unclear in the instructions given on the site and the documentation. I have put the Swampy folder into the site- packages folder of Python 2.7.1, but I don't know how to make the .pth file that will get it installed so that the module can be imported. Can anyone give me instructions on how to make one of these magical .pth files? Answer: After you unzip your swampy-2.0 folder in the site-packages directory, you only have to create, also in site-packages, a text file called `misite.pth` (the only important thing here is the .pth extension, you can use whatever filename you like). The .pth file should simply contain one line: the name of your folder ('swampy-2.0'). That is all. Python search for files with the extension .pth and put the directory names in these files in the module search path. A path file can contain the name of one or several folders, one per line.
Using urllib2 in Python. How do I get the name of the file I am downloading? Question: I am a python beginner. I am using urllib2 to download files. When I download a file, I specify a filename to with which to save the downloaded file on my hard drive. However, if I download the file using my browser, a default filename is automatically provided. Here is a simplified version of my code: def downloadmp3(url): webFile = urllib2.urlopen(url) filename = 'temp.zip' localFile = open(filename, 'w') localFile.write(webFile.read()) The file downloads just fine, but if I type the string stored in the variable "url" into my browser, there is a default filename given to the file when I download it. I want to use this filename for my downloaded file not 'temp.zip' or whatever I assign it. How do I use urllib2 (or some other Python library) to save the file with the filename that the server I am downloading from intends it to have? If anyone doesn't understand this question, please say so, so that I can try to make it clearer. Answer: The filename is usually included by the server through the content-disposition header: content-disposition: attachment; filename=foo.pdf You have access to the headers through result = urllib2.urlopen(...) result.info() <- contains the headers i>>> import urllib2 ur>>> result = urllib2.urlopen('http://zopyx.com') >>> print result <addinfourl at 4302289808 whose fp = <socket._fileobject object at 0x1006dd5d0>> >>> result.info() <httplib.HTTPMessage instance at 0x1006fbab8> >>> result.info().headers ['Date: Mon, 04 Apr 2011 02:08:28 GMT\r\n', 'Server: Zope/(unreleased version, python 2.4.6, linux2) ZServer/1.1 Plone/3.3.4\r\n', 'Content-Length: 15321\r\n', 'Content-Type: text/html; charset=utf-8\r\n', 'Via: 1.1 www.zopyx.com\r\n', 'Cache-Control: max-age=3600\r\n', 'Expires: Mon, 04 Apr 2011 03:08:28 GMT\r\n', 'Connection: close\r\n'] See <http://docs.python.org/library/urllib2.html> But be aware that this header does not need to be present. Otherwise you need to generate a reasonable name yourself from the URL requested - e.g. from the last component of the URI. Use the urlparse() method of Python in this case.
FTPES - FTP over explicit TLS/SSL in Python Question: I need a python client to do FTPES (explicit), does anyone has experience with any python package that can do this. I am not able to do this in python, but can connect to FTP server using tools like FileZilla Thanks Answer: FTP-SSL Explicit is well supported by native Python. After setting up the connection, you can use all the standard ftplib commands. More can be found at: <http://docs.python.org/2/library/ftplib.html#ftplib.FTP_TLS> Here's a basic example for downloading a file: from ftplib import FTP_TLS ftps = FTP_TLS('ftp.MySite.com') ftps.login('testuser', 'testpass') # login anonymously before securing control channel ftps.prot_p() # switch to secure data connection.. IMPORTANT! Otherwise, only the user and password is encrypted and not all the file data. ftps.retrlines('LIST') filename = 'remote_filename.bin' print 'Opening local file ' + filename myfile = open(filename, 'wb') ftps.retrbinary('RETR %s' % filename, myfile.write) ftps.close()
django-transmeta into admin, displaying "None" in the field.label_tag Question: I'm trying to integrate django-transmeta into my django installation on ubuntu 10.10 (python-django version on system is 1.2.3-1ubuntu0.2.10.10.1) Following the instructions in the project home/summary [here](http://code.google.com/p/django-transmeta/) I end up with the correct new fields in the database, but when I open the admin interface and I try to add an object, the translated filed "description" is not shown in the admin panel and it's shown only **None**. Looking in the source code and after a bit of debug, the variable passed to the template which the value is **None** seems to be **field.label_tag** This is the class inside models.py: class Place(models.Model): __metaclass__ = TransMeta lat = models.FloatField(blank=True, null=True) lon = models.FloatField(blank=True, null=True) alt = models.FloatField(blank=True, null=True) description = models.CharField(max_length=100) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) attributes = models.ManyToManyField(Attribute, through='PlaceAttribute') is_online = models.BooleanField(default=False) class Meta: translate = ('description', ) def __unicode__(self): return self.description In the settings.py I added this: LANGUAGE_CODE = 'en-us' ugettext = lambda s: s # dummy ugettext function, as django's docs say LANGUAGES = ( ('en-us', ugettext('English')), ('it', ugettext('Italian')), ('de', ugettext('Deutsch')), ('fr', ugettext('French')), ('ru', ugettext('Russian')), ('cn', ugettext('Chinese')), ('th', ugettext('Thai')), ) TRANSMETA_DEFAULT_LANGUAGE = 'en-us' and this is a screenshot of the result in the admin interface: (sorry I'm new here and can't post images in questions for antispam reasons, yet) [admin screenshot here](http://i.stack.imgur.com/B9Tyk.png) In the above admin form it should be something like: Description en-us: Description it: Description de: .... Have you an idea of what could the problem be? Or maybe it's a bug? To improve my debug, could you kindly point me in the correct place inside the django admin view where the **field.label_tag** is generated? (I'm quite new to Django) If some debug data is needed, please tell me and I'll gladly provide it. Thanks in advance Fabio Answer: It looks like you're missing verbose_name attributes on your fields. from django.utils.translation import gettext_lazy as _ class Place(models.Model): __metaclass__ = TransMeta # ... description = models.CharField(max_length=100, verbose_name=_("Description")) # ... class Meta: translate = ('description', ) def __unicode__(self): return self.description
Determining redirected URL in Python Question: I make a little parser using HTMLparser and I would like to know where a link is redirected. I don't know how to explain this, so please look this example: On my page I have a link on the source: `http://www.myweb.com?out=147`, which redirects to `"http://www.mylink.com"`. I can parse `"http://www.myweb.com?out=147"` without any problems, but I don't know how to have get `http://www.mylink.com`. Thanks a lot for your help guys ! Answer: You can use [`urllib2`](https://docs.python.org/2/library/urllib2.html#module- urllib2) ([`urllib.request`](https://docs.python.org/3/library/urllib.request.html#module- urllib.request) in Python 3) and its [`HTTPRedirectHandler`](https://docs.python.org/2/library/urllib2.html#httpredirecthandler- objects) in order to find out where a URL will redirect you. Here's a function that does that: import urllib2 def get_redirected_url(url): opener = urllib2.build_opener(urllib2.HTTPRedirectHandler) request = opener.open(url) return request.url print get_redirected_url("http://google.com/") # prints "http://www.google.com/"
Model API or load bulk data? Question: I want to add scrapped data to my database. I like the fact that the API enables validation but I assume that the overhead is too high. I'm writing maybe 10k rows at a time, at most. Is that accurate? Alright, so one other issue I was having, which was preventing me from testing this hypothesis is that I'm currently unable to import my models module. I get an error message claiming that my DJANGO_SETTINGS_MODULE is undefined. my django.wsgi script does define it and it works within the context of django. I assume that when I try to execute a python file from the command line, the .wsgi script is not run. Again, assumptions, I know. Do I have to add my django project to my PYTHONPATH within the bashrc file to make this work? Answer: You'll need to set your project's settings file in ~/.bashrc if you want to use it in a script. export PYTHONPATH=$PYTHONPATH:/path/to/django/project export DJANGO_SETTINGS_MODULE=settings or export DJANGO_SETTINGS_MODULE=/path/to/django/project/settings
soap ui generated code Question: I have a webservice I am trying to build a client for. I have the following wsdl: http://www.cmicdataservices.com/datacenter/service.asmx?wsdl It requires authentication. Looking at the WSDL description I see no method that takes an authentication object, nor username and passwords as arguments. Using Netbeans I have generated jax-ws sources for the WSDL. I however can not figure out what to do after that. Using soapui I can connect to the webservice and run all the methods. But once again, I want to build this into a client that can be run without my interaction. My problem comes in figuring out how to use this generated code, which it appears netbeans.tv had a video(netbeans soapui plugin video 2) which has since been lost. Does anyone know of any tutorials or know of any examples of how I can use this generated code to access the webservice? so I have a method CheckifAuthorized() Running in soapui I get the following xml <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:cmic="http://www.cmicdataservices.com/"> <soap:Header> <cmic:Authentication> <!--Optional:--> <cmic:UserName>username</cmic:UserName> <!--Optional:--> <cmic:Password>password</cmic:Password> </cmic:Authentication> </soap:Header> <soap:Body> <cmic:CheckIfAuthorized/> </soap:Body> </soap:Envelope> I can then run that request in soap ui and get back the response that authentication was a success. With the jax-ws code generated with netbeans and with soapui as well I have the following: package javaapplication7; /** * * @author grant */ public class Main { public static void main(String[] args) { Boolean result = checkIfAuthorized(); System.out.println("The result is: " + result); } private static boolean checkIfAuthorized() { javaapplication7.CMICDatacenterService service = new javaapplication7.CMICDatacenterService(); javaapplication7.CMICDatacenterServiceSoap port = service.getCMICDatacenterServiceSoap(); return port.checkIfAuthorized(); } } This will fail with the following error run: Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Server was unable to process request. ---> Object reference not set to an instance of an object. at com.sun.xml.internal.ws.fault.SOAP11Fault.getProtocolException(SOAP11Fault.java:178) at com.sun.xml.internal.ws.fault.SOAPFaultBuilder.createException(SOAPFaultBuilder.java:111) at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:108) at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:78) at com.sun.xml.internal.ws.client.sei.SEIStub.invoke(SEIStub.java:107) at $Proxy30.checkIfAuthorized(Unknown Source) at javaapplication7.Main.checkIfAuthorized(Main.java:24) at javaapplication7.Main.main(Main.java:17) Java Result: 1 This is the same problem I ran into when trying to use python for the service. I have since chosen to go with Java as I feel I may have quicker turnaround on parsing the xml and creating objects as I already have the entities for this created. Thank you. Grant I did not want to answer this because I would still like to figure out what I can do here, but I did just end up writing the request by hand with the following. Now I can just convert this into an xml object and go about my way, but I imagine soapui makes all of this much easier. What I really do not understand is how to use soapui to build this request and incorporate it into my project: public class Main { public final static String DEFAULT_SERVER = "http://www.cmicdataservices.com/datacenter/service.asmx"; public final static String SOAP_ACTION = "http://www.cmicdataservices.com/CheckIfAuthorized"; public static void main(String[] args) { String server = DEFAULT_SERVER; String UserName = "Username"; String Password="Password"; try{ URL url = new URL(server); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8"); connection.setRequestProperty("Host", "www.cmicdataservices.com"); OutputStream out = connection.getOutputStream(); Writer wout = new OutputStreamWriter(out); // Uncomment the following and comment out the previous two lines to see your xml //BufferedWriter wout = new BufferedWriter(new FileWriter("/tmp/testXML.xml")); //Start writing soap request - Envelope wout.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"); wout.write("<soap12:Envelope "); wout.write("xmlns:xsi="); wout.write("'http://www.w3.org/2001/XMLSchema-instance' "); wout.write("xmlns:xsd="); wout.write("'http://www.w3.org/2001/XMLSchema' "); wout.write("xmlns:soap12="); wout.write("'http://www.w3.org/2003/05/soap-envelope'>\r\n"); //Soap request header start wout.write("<soap12:Header>\r\n"); //Start writing soap request - Authentication wout.write("<Authentication xmlns="); wout.write("'http://www.cmicdataservices.com/'>\r\n"); wout.write("<UserName>" + UserName + "</UserName>\r\n"); wout.write("<Password>" + Password + "</Password>\r\n"); // End Authentication wout.write("</Authentication>\r\n"); //End the header wout.write("</soap12:Header>\r\n"); //Start writing the body wout.write("<soap12:Body>"); wout.write("<GetCurrentDataVer1 xmlns="); wout.write("'http://www.cmicdataservices.com/' />\r\n"); // End the Body wout.write("</soap12:Body>\r\n"); // End the Envelope wout.write("</soap12:Envelope>\r\n"); wout.flush(); wout.close(); //BufferedWriter fout = new BufferedWriter(new FileWriter("/tmp/testXMLResponse.xml")); InputStream in = connection.getInputStream(); createFile(in, "/tmp/testXMLResponse.xml"); } catch (IOException e) { System.err.println(e); } } public static void createFile(InputStream io, String fileName) throws IOException { FileOutputStream fout = new FileOutputStream(fileName); byte[] buf = new byte[256]; int read = 0; while ((read = io.read(buf)) != -1){ fout.write(buf, 0, read); } } Answer: The problem with your code is lack of Authentication element in the SOAP header. Take a look at the WSDL, it should always be there: <wsdl:operation name="CheckIfAuthorized"> <soap:operation soapAction="http://www.cmicdataservices.com/CheckIfAuthorized" style="document"/> <wsdl:input> <soap:body use="literal"/> <soap:header message="tns:CheckIfAuthorizedAuthentication" part="Authentication" use="literal"/> </wsdl:input> <wsdl:output> <soap:body use="literal"/> </wsdl:output> </wsdl:operation> You server fails with exception because of incorrect XML when there is no Authentication element in the CheckIfAuthorized request. Here is sample client in Python to demonstrate the idea of solving the problem, I think it's not a problem for you to convert it to Java. from suds.client import Client client = Client("http://www.cmicdataservices.com/datacenter/service.asmx?wsdl") auth = client.factory.create('Authentication') auth.UserName = "username" auth.Password = "password" client.set_options(soapheaders=auth) client.service.CheckIfAuthorized()
Call a function in Python and pass only the arguments it expects Question: How do I call a function and only pass it the arguments that it expects. For example say I have the following functions: func1 = lambda a: True func2 = lambda a, b: True func3 = lambda c: True I want some Python code that is able to successfully call these functions without raising a `TypeError` by passing unexpected arguments. i.e. kwargs = dict(a=1, b=2, c=3) for func in (func1, func2, func3): func(**kwargs) # some magic here I'm not interested in just adding `**kwargs` to the functions when I define them. Answer: You can use `inspect.getargspec()`: from inspect import getargspec kwargs = dict(a=1, b=2, c=3) for func in (func1, func2, func3): func(**dict((name, kwargs[name]) for name in getargspec(func)[0]))
PIL - libjpeg.so.8: cannot open shared object file: No such file or directory Question: Compiled the libjpeg v8, PIL 1.1.7 and and import for _imaging works on the system Python, but spouts this error inside the virtualenv: libjpeg.so.8: cannot open shared object file: No such file or directory here is the error run with a python -v interpreter inside the virtualenv >>> import _imaging dlopen("/home/ygamretuta/dev/py/django/lib/python2.6/site-packages/PIL/_imaging.so", 2); Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: libjpeg.so.8: cannot open shared object file: No such file or directory and here are the paths: /home/ygamretuta/dev/py/django/lib/python2.6/site-packages/distribute-0.6.14-py2.6.egg /home/ygamretuta/dev/py/django/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg /home/ygamretuta/dev/py/django/lib/python2.6 /home/ygamretuta/dev/py/django/lib/python2.6/plat-linux2 /home/ygamretuta/dev/py/django/lib/python2.6/lib-tk /home/ygamretuta/dev/py/django/lib/python2.6/lib-old /home/ygamretuta/dev/py/django/lib/python2.6/lib-dynload /usr/lib/python2.6 /usr/lib/python2.6/plat-linux2 /usr/lib/python2.6/lib-tk /home/ygamretuta/dev/py/django/lib/python2.6/site-packages /home/ygamretuta/dev/py/django/lib/python2.6/site-packages/PIL I am using Ubuntu 10.10 and this is the uname-a output: Linux ygam-desktop 2.6.35-28-generic #49-Ubuntu SMP Tue Mar 1 14:40:58 UTC 2011 i686 GNU/Linux I am using Python 2.6 I followed the following guides already: <http://appelfreelance.com/2010/06/libjpeg-pil-snow-leopard- python2-6-_jpeg_resync_to_restart/> <http://www.jooncode.com/2010/12/02/python-pil-jpeg-resync-restart-error- imaging-module-solve/> <http://djangodays.com/2008/09/03/django-imagefield-validation-error-caused- by-incorrect-pil-installation-on-mac/> Answer: See an explanation here: [Why can't Python find shared objects that are in directories in sys.path?](http://stackoverflow.com/questions/1099981/why-cant- python-find-shared-objects-that-are-in-directories-in-sys-path) A quick fix is to add the directory that contains `libjpeg.so.8` to your `/etc/ld.so.conf` file, and then run `ldconfig`
What's with binary files on Windows? Question: I made a script to download a file, but it only works on Unix/Linux/OSX when I'm downloading binary executables, swf's, images, etc \#Modfied section from PWB.py import sys if sys.version_info<(2,8): import urllib as request else: import urllib.request as request x=request.urlopen("http://homestarrunner.com/intro.swf") y=x.read() x.close() z=open("intro.swf","w") z.write(y) z.close() I will get the the file, and the usual unreadable garbage in the file, but it will be unreadable. It seems binary files always have these sorts of problem on Windows. Why is this? PS. How could I write my python code so that it will download? Answer: Open binary files in binary mode. z = open("intro.swf","wb")
Is there a way to wrap a tkinter GUI in a class that can be created and interacted with from another object? (*without* hanging in mainloop) Question: Is there a way to wrap a tkinter GUI in a class that can be created and interacted with from another object? For this to be really useful, the class has to work so mainloop or its equivalent doesn't hold the application. If so, can someone point me to a working example? **For context** , what I'm trying to do is make a SimpleUI class that I can use in any application to allow it to display information or register functions to be executed on button or key presses. So any threading, queues, etc. I would like to have hidden in the SimpleUI class. Based on what I've gathered from reading around, the answer is No without re- implementing mainloop. Rather, the GUI should be the main application which farms out work through one method or another. However, this would make any application with tkinter (perhaps other GUIs as well?) feel like the tail is wagging the dog. Hopefully I have misunderstood what I have beeing reading. I know this may seem like a repost of [this](http://stackoverflow.com/questions/4812323/can-the-main-loop-of-a- program-be-moved-out-of-gui) and other similar questions but I can't comment on those and the answers seem to be doing the opposite of what I want to do. In addition to that question, I've found bits and pieces of related code in many places, but I have not been able to put them together. If there is a way, I'll learn Python threads or whatever to make it work. I'm using Python 3.1 if it makes any difference. Example of how I would like it to work. ui = SimpleUI() ui.hide() ui.show() ui.add_frame... ui.add_button... ui.register_function(button, function) Answer: Is this what you're looking for? #The threading module allows you to subclass it's thread class to create #and run a thread, in this case we will be starting SimpleUI in a seperate thread import threading from Tkinter import * def printfunction(): print "ButtonPress" class NewClass: def __init__(self): self.ui = SimpleUI() self.ui.add_frame("frame1") self.ui.add_button("button1","frame1") self.ui.register_function("button1",printfunction) self.ui.start() #self.ui = Threader().start() def PrintSuccess(self): print "Success!" class SimpleUI: def __init__(self): self.root = Tk() self.frames = {} self.buttons = {} def start(gui): class Threader(threading.Thread): def run(self): gui.root.mainloop() Threader().start() def hide(self): self.root.withdraw() if(raw_input("press enter to show GUI: ")==""):self.show() def show(self): self.root.update() self.root.deiconify() def add_frame(self,name): tmp = Frame(self.root) tmp.pack() self.frames[name] = tmp def add_button(self,name,frame): tmp = Button(self.frames[frame]) tmp.pack() self.buttons[name] = tmp def register_function(self,button,function): self.buttons[button].config(command=function) NC = NewClass() NC.PrintSuccess()
Is shared readonly data copied to different processes for Python multiprocessing? Question: The piece of code that I have looks some what like this: glbl_array = # a 3 Gb array def my_func( args, def_param = glbl_array): #do stuff on args and def_param if __name__ == '__main__': pool = Pool(processes=4) pool.map(my_func, range(1000)) Is there a way to make sure (or encourage) that the different processes does not get a copy of glbl_array but shares it. If there is no way to stop the copy I will go with a memmapped array, but my access patterns are not very regular, so I expect memmapped arrays to be slower. The above seemed like the first thing to try. This is on Linux. I just wanted some advice from Stackoverflow and do not want to annoy the sysadmin. Do you think it will help if the the second parameter is a genuine immutable object like `glbl_array.tostring()`. Answer: You can use the shared memory stuff from `multiprocessing` together with Numpy fairly easily: import multiprocessing import ctypes import numpy as np shared_array_base = multiprocessing.Array(ctypes.c_double, 10*10) shared_array = np.ctypeslib.as_array(shared_array_base.get_obj()) shared_array = shared_array.reshape(10, 10) #-- edited 2015-05-01: the assert check below checks the wrong thing # with recent versions of Numpy/multiprocessing. That no copy is made # is indicated by the fact that the program prints the output shown below. ## No copy was made ##assert shared_array.base.base is shared_array_base.get_obj() # Parallel processing def my_func(i, def_param=shared_array): shared_array[i,:] = i if __name__ == '__main__': pool = multiprocessing.Pool(processes=4) pool.map(my_func, range(10)) print shared_array which prints ` [[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 2. 2. 2. 2. 2. 2. 2. 2. 2. 2.] [ 3. 3. 3. 3. 3. 3. 3. 3. 3. 3.] [ 4. 4. 4. 4. 4. 4. 4. 4. 4. 4.] [ 5. 5. 5. 5. 5. 5. 5. 5. 5. 5.] [ 6. 6. 6. 6. 6. 6. 6. 6. 6. 6.] [ 7. 7. 7. 7. 7. 7. 7. 7. 7. 7.] [ 8. 8. 8. 8. 8. 8. 8. 8. 8. 8.] [ 9. 9. 9. 9. 9. 9. 9. 9. 9. 9.]] However, Linux has copy-on-write semantics on `fork()`, so even without using `multiprocessing.Array`, the data will not be copied unless it is written to.
Casting in python Question: I have problem with casting in python. I have a method in file module_A.py: import Common.Models.Pax as Pax def verify_passangers_data(self,paxes): for i in range(len(paxes)): pax=paxes[i] Here is my Pax.py class Pax: """""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" #---------------------------------------------------------------------- class Adult(Pax): def __init__(self,last_day_of_travel,first_name,last_name,nationality,address=None): self.birth_day=datetime.today() - timedelta(days = random.randrange(6563, 20793-(date.today()-last_day_of_travel).days)) self.first_name=first_name self.last_name=last_name self.nationality=nationality self.address=address This is how I create collection in another module(module_C.py): paxes=[] paxes.append(Pax.Adult(last_day_of_travel,'FirstName','LastName',Nationality.Poland,DataRepository.addresses['Default'])) but, look at my output from debug probe (in wing ide) >>> type(pax) <class 'Common.Models.Pax.Adult'> >>> pax is Common.Models.Pax.Adult Traceback (most recent call last): File "<string>", line 1, in <fragment> builtins.NameError: name 'Common' is not defined How can I check is pax is instance of Adult? Answer: > How can I check is pax is instance of Adult? Use the `isinstance` function: isinstance(pax, Common.Models.Pax.Adult) Make you have imported the class, though (e.g., `import Common.Models.Pax`). (Although purists would argue that there's rarely a need to check the type of a Python object. Python is dynamically typed, so you should generally check to see if an object responds to a particular method call, rather than checking its type. But you may have a good reason for needing to check the type, too.)
matplotlib won't work on ubuntu 10.10 Question: I'm having a problem getting matplotlib to work in ubuntu 10.10. First I install the matplotlib using apt-get, and later I found that the version is 0.99 and some examples on the official site just won't work. Then I download the 1.01 version and install it without uninstalling the 0.99 version. To make the situation more specific, here is the configuration: BUILDING MATPLOTLIB matplotlib: 1.0.1 python: 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) [GCC 4.4.5] platform: linux2 REQUIRED DEPENDENCIES numpy: 1.6.0b1 freetype2: 12.2.6 OPTIONAL BACKEND DEPENDENCIES libpng: 1.2.44 Tkinter: no * Using default library and include directories for * Tcl and Tk because a Tk window failed to open. * You may need to define DISPLAY for Tk to work so * that setup can determine where your libraries are * located. Tkinter present, but header files are not * found. You may need to install development * packages. wxPython: no * wxPython not found pkg-config: looking for pygtk-2.0 gtk+-2.0 * Package pygtk-2.0 was not found in the pkg-config * search path. Perhaps you should add the directory * containing `pygtk-2.0.pc' to the PKG_CONFIG_PATH * environment variable No package 'pygtk-2.0' found * Package gtk+-2.0 was not found in the pkg-config * search path. Perhaps you should add the directory * containing `gtk+-2.0.pc' to the PKG_CONFIG_PATH * environment variable No package 'gtk+-2.0' found * You may need to install 'dev' package(s) to * provide header files. Gtk+: no * Could not find Gtk+ headers in any of * '/usr/local/include', '/usr/include', '.' Mac OS X native: no Qt: no Qt4: no Cairo: 1.8.8 OPTIONAL DATE/TIMEZONE DEPENDENCIES datetime: present, version unknown dateutil: 1.4.1 pytz: 2010b OPTIONAL USETEX DEPENDENCIES dvipng: no ghostscript: 8.71 latex: no pdftops: 0.14.3 [Edit setup.cfg to suppress the above messages] and now i can import matplotlib but once i run the example code, it just terminated and I get no results. I tried to 'clean install' several times, which means I delete all the files include the .matplotlib and the matplotlib directory under dist-package, but I still can't get things done. What makes weirder is that after I reinstall the 0.99 version, it works pretty well. Any ideas? Answer: Ben Gamari has [packaged](https://launchpad.net/~bgamari/+archive/matplotlib- unofficial) matplotlib 1.0 for Ubuntu.
Using Python's Subprocess to Display Output in New Xterm Window Question: I am trying to output different information in two terminals from the same Python script (much like [this fellow](http://stackoverflow.com/questions/2933601/how-i-can-open-different- linux-terminal-to-output-differnt-kinds-of-debug-informa)). The way that my research has seemed to point to is to open a new xterm window using subprocess.Popen and running cat to display the stdin of the terminal in the window. I would then write the necessary information to the stdin of the subprocess like so: from subprocess import Popen, PIPE terminal = Popen(['xterm', '-e', 'cat'], stdin=PIPE) #Or cat > /dev/null terminal.stdin.write("Information".encode()) The string "Information" would then display in the new xterm. However, this is not the case. The xterm does not display anything and the stdin.write method simply returns the length of the string and then moves on. I'm not sure is there is a misunderstanding of the way that subprocess and pipes work, but if anyone could help me it would be much appreciated. Thanks. Answer: This doesn't work because you pipe stuff to `xterm` itself not the program running inside `xterm`. Consider using named pipes: import os from subprocess import Popen, PIPE import time PIPE_PATH = "/tmp/my_pipe" if not os.path.exists(PIPE_PATH): os.mkfifo(PIPE_PATH) Popen(['xterm', '-e', 'tail -f %s' % PIPE_PATH]) for _ in range(5): with open(PIPE_PATH, "w") as p: p.write("Hello world!\n") time.sleep(1)
How do I handle Python unicode strings with null-bytes the 'right' way? Question: **Question** It seems that PyWin32 is comfortable with giving null-terminated unicode strings as return values. I would like to deal with these strings the 'right' way. Let's say I'm getting a string like: `u'C:\\Users\\Guest\\MyFile.asy\x00\x00sy'`. This appears to be a C-style null-terminated string hanging out in a Python unicode object. I want to trim this bad boy down to a regular ol' string of characters that I could, for example, display in a window title bar. Is trimming the string off at the first null byte the right way to deal with it? I didn't expect to get a return value like this, so I wonder if I'm missing something important about how Python, Win32, and unicode play together... or if this is just a PyWin32 bug. **Background** I'm using the Win32 file chooser function [`GetOpenFileNameW`](http://docs.activestate.com/activepython/2.7/pywin32/win32gui__GetSaveFileNameW_meth.html) from the PyWin32 package. According to the documentation, this function returns a tuple containing the full filename path as a Python unicode object. When I open the dialog with an existing path and filename set, I get a strange return value. For example I had the default set to: `C:\\Users\\Guest\\MyFileIsReallyReallyReallyAwesome.asy` In the dialog I changed the name to `MyFile.asy` and clicked save. The full path part of the return value was: u'C:\Users\Guest\MyFile.asy\x00wesome.asy'` I expected it to be: `u'C:\\Users\\Guest\\MyFile.asy'` The function is returning a recycled buffer without trimming off the terminating bytes. Needless to say, the rest of my code wasn't set up for handling a C-style null-terminated string. **Demo Code** The following code demonstrates null-terminated string in return value from GetSaveFileNameW. Directions: In the dialog change the filename to 'MyFile.asy' then click Save. Observe what is printed to the console. The output I get is `u'C:\\Users\\Guest\\MyFile.asy\x00wesome.asy'`. import win32gui, win32con if __name__ == "__main__": initial_dir = 'C:\\Users\\Guest' initial_file = 'MyFileIsReallyReallyReallyAwesome.asy' filter_string = 'All Files\0*.*\0' (filename, customfilter, flags) = \ win32gui.GetSaveFileNameW(InitialDir=initial_dir, Flags=win32con.OFN_EXPLORER, File=initial_file, DefExt='txt', Title="Save As", Filter=filter_string, FilterIndex=0) print repr(filename) Note: If you don't shorten the filename enough (for example, if you try MyFileIsReally.asy) the string will be complete without a null byte. **Environment** Windows 7 Professional 64-bit (no service pack), Python 2.7.1, PyWin32 Build 216 **UPDATE: PyWin32 Tracker Artifact** Based on the comments and answers I have received so far, this is likely a pywin32 bug so I filed a [tracker artifact](https://sourceforge.net/tracker/?func=detail&aid=3277647&group_id=78018&atid=551954). **UPDATE 2: Fixed!** Mark Hammond reported in the tracker artifact that this is indeed a bug. A fix was checked in to rev f3fdaae5e93d, so hopefully that will make the next release. I think Aleksi Torhamo's answer below is the best solution for versions of PyWin32 before the fix. Answer: I'd say it's a bug. The right way to deal with it would probably be fixing pywin32, but in case you aren't feeling adventurous enough, just trim it. You can get everything before the first `'\x00'` with `filename.split('\x00', 1)[0]`.
Having trouble with ZMySQLDb with Plone 4.0.4 on Windows Question: I'm installing ZMYSQLDA for Z MYSQL Databae connection through buildout. Here are my initial definitions: parts= ..... zmysqlda [zmysqlda] recipe = cns.recipe.zmysqlda target = ${productdistros:location} It seem ok, does build the instance and site works. For information I have already installed MySQL_python throught exe file so I''m able to import MySQLdb. When I introduce Products.ZMySQLDA in the eggs it tries to fetch MYSQL-python. I don't understand why since it's already installed. Buidout log is Unused options for buildout: 'eggs' 'download-directory'. Updating productdistros. Installing instance. Getting distribution for 'MySQL-python==1.2.3'. install_dir C:\Program Files\Plone 404/buildout-cache/eggs\tmparsmo9 error: The system cannot find the file specified An error occured when trying to install MySQL-python 1.2.3. Look above this mess age for any errors that were output by easy_install. While: Installing instance. Getting distribution for 'MySQL-python==1.2.3'. Error: Couldn't install: MySQL-python 1.2.3 *************** PICKED VERSIONS **************** [versions] collective.saconnect = 1.3 pas.plugins.sqlalchemy = 0.2 products.ploneboard = 2.2 products.ploneboardsubscription = 0.2 products.zmysqlda = 3.1.1 sqlalchemy = 0.6.6 #Required by: #collective.saconnect 1.3 plone.app.z3cform = 0.5.3 #Required by: #collective.saconnect 1.3 rwproperty = 1.0 #Required by: #pas.plugins.sqlalchemy 0.2 z3c.saconfig = 0.12 #Required by: #pas.plugins.sqlalchemy 0.2 zope.sqlalchemy = 0.6.1 Answer: It's trying to install mysql-python because the one you've already installed is not on the buildout's PYTHONPATH. I would start by removing the **'target='** option in the [zmysqlda] section. You really shouldn't be pointing anything at 'productdistros' these days. It may just be that buildout can't find zmysqlda's dependencies in **'target'**. If that doesn't solve it, rerun the buildout with the **-vv** option and post the results here. However, as long as you're using sqlalchemy anyway, why not use the SQLAlchemyDA which plays well with it...? Then you just need to add Products.SQLAlchemyDA (and the MySql db adapter - which I presume you have for sqlalchemy anyway) to the eggs list, and you don't need anything corresponding to the [zmysqlda] part.
Why is this shell script calling itself as python script? Question: Obviously this shell script is calling itself as a Python script: #!/bin/sh ## repo default configuration ## REPO_URL='git://android.git.kernel.org/tools/repo.git' REPO_REV='stable' magic='--calling-python-from-/bin/sh--' """exec" python -E "$0" "$@" """#$magic" if __name__ == '__main__': import sys if sys.argv[-1] == '#%s' % magic: del sys.argv[-1] del magic : : (Whole script: <http://android.git.kernel.org/repo>) Can anyone explain * the purpose of calling it this way? Why not having `#!/usr/bin/env python` in the first line so it gets interpreted as Python script from the beginning? * the purpose of adding that magic last command line argument, that is removed afterwards in the beginning of the Python code? Answer: Your first question: this is done to fix unix systems (or emulations thereof) that do not handle the #! correctly or at all. The high art is to make a script that is coreect in shell as well as in the other language. For perl, one often sees something like: exec "/usr/bin/perl" if 0; The exec is interpreted and executed by the shell, but the perl interpreter sees a conditional statetment (.... if ...) and does nothing because the condition is false.
Is it possible to obtain the IP address from a HTTP Request Question: **I am trying to identify users that access my website. I know of assigning a cookie to them & identifying them that way. But is it also possible to use their IP address to identify them?** I know of IP subclassing (is that the correct term) so if many users on the same network access my site & have subclassing, they will all have the same IP address but thats ok, I dont want my IP identification to be exact, its just a backup if the user has no cookie. If I have a HTTP request can I get the ip address of the requester/sender? For example to get the browser type I check the HTTP (header?) user-agent. With my little knowledge of Data Communications, if the HTTP request does contain an IP address, wont it have the IP address of the last hop(router/switch) or am I thinking of TCP? **I am using Python & cgi; so is there a way to determine the HTTP requesters IP address either by looking at the HTTP request, or maybe TCP packets(I never worked with TCP in python, how could I look at data packets in python?).** Answer: Sure. Use `cgi`, and `os`. The client's IP address is located in the `environ` variable with a title of `REMOTE_ADDR`. For example, the following will print out the client's ip address: import cgi import os print "Content-type: text/html" print "" print cgi.escape(os.environ["REMOTE_ADDR"])
Easier way to check conditions? Question: I'm new to python and I need to simplify this checker. How can I change: ... if c == '>' and ( prevTime > currentTime ): c2 = True elif c == '>=' and ( prevTime >= currentTime ): c2 = True ... to something like: if prevTime | condition | currentTime: doSomething() I've tried to use either **evaluate** or **compile** , but during creation of string there is conversion between datetime object to string ( **str** on datetime object). For example: >>> 'result = %s %s %s' % (datetime.now(), '>', datetime.utcfromtimestamp(41)) 'result = 2011-04-07 14:13:34.819317 > 1970-01-01 00:00:41' and it can't be compared. Can someone help me with this? Below working example: def checkEvent( prevEvent, currentEvent, prevTime, currentTime ): def checkCondition( condition ): #condition format #tuple ( (oldEvent, newEvent), time, ip) # eg: (('co', 'co'), '>=', '!=') c1 = c2 = False #check Event if prevEvent == condition[0][0] and currentEvent == condition[0][1]: c1 = True else: return False #check time if condition[1]: c = condition[1] if c == '>' and ( prevTime > currentTime ): c2 = True elif c == '>=' and ( prevTime >= currentTime ): c2 = True elif c == '<' and ( prevTime < currentTime ): c2 = True elif c == '<=' and ( prevTime <= currentTime ): c2 = True elif c == '==' and ( prevTime == currentTime ): c2 = True else: c2 = True return c1 and c2 def add(): print 'add' def changeState(): print 'changeState' def finish(): print 'finish' def update(): print 'update' conditions = (\ ( ( ( 're', 'co' ), None ), ( add, changeState ) ), ( ( ( 'ex', 'co' ), None ), ( add, changeState ) ), ( ( ( 'co', 'co' ), '<' ), ( add, changeState ) ), ( ( ( 'co', 'co' ), '>=' ), ( add, changeState, finish ) ), ( ( ( 'co', 'co' ), '>=' ), ( update, ) ), ( ( ( 'co', 're' ), '>=' ), ( changeState, finish ) ), ( ( ( 'co', 'ex' ), '>=' ), ( changeState, finish ) ) ) for condition in conditions: if checkCondition( condition[0] ): for cmd in condition[1]: cmd() from datetime import datetime checkEvent( 'co', 'co', datetime.utcfromtimestamp(41), datetime.now() ) checkEvent( 'ex', 'co', datetime.utcfromtimestamp(41), datetime.now() ) checkEvent( 'co', 'co', datetime.utcfromtimestamp(41), datetime.utcfromtimestamp(40) ) Answer: You can try making a map of operators, like this: import operator compares = { '>': operator.gt, '>=': operator.ge, '<': operator.lt, '<=': operator.le, '==': operator.eq } def check(c, prev, current): func = compares[c] return func(prev, current) print check('>', 5, 3) # prints: True print check('>=', 5, 5) # prints: True print check('<', 3, 5) # prints: True print check('<=', 3, 3) # prints: True print check('==', 7, 7) # prints: True
Running generated nose tests Question: Suppose I define a testFile.py python module with as follows. def test_evens(): for i in range(0, 5): yield check_even, i, i*3 def check_even(n, nn): assert n % 2 == 0 or nn % 2 == 0 When I let nose identify the tests in collect-only mode I get testFile.test_evens(0, 0) ... ok testFile.test_evens(1, 3) ... ok testFile.test_evens(2, 6) ... ok testFile.test_evens(3, 9) ... ok testFile.test_evens(4, 12) ... ok I can run all tests using > > nosetests -v testFile:test_evens However, what if I only want to run testFile.test_evens(2, 6) (i.e., not all the tests)? Is there any way to do this from the command line? Answer: Nose cannot do this by default, to my knowledge. Here are some options: **1\. Fake it from the command line** Probably not what you're looking for, but I had to mention it. You could also create a wrapper script to simplify this: python -c 'import testFile; testFile.check_even(2, 6)' **2\. Create a custom nose test loader** This is a little more involved, but you can create a custom test loader which interprets the command-line arguments as specifying the generator to load, pulls out tests and arguments from the generator, and returns a suite containing the test(s) with the matching arguments. Below is some example code which should give you enough to build on (**runner.py**): import ast import nose class CustomLoader(nose.loader.TestLoader): def loadTestsFromName(self, name, module=None): # parse the command line arg parts = name.split('(', 1) mod_name, func_name = parts[0].split('.') args = ast.literal_eval('(' + parts[1]) # resolve the module and function - you'll probably want to # replace this with nose's internal discovery methods. mod = __import__(mod_name) func = getattr(mod, func_name) # call the generator and gather all matching tests tests = [] if nose.util.isgenerator(func): for test in func(): _func, _args = self.parseGeneratedTest(test) if _args == args: tests.append(nose.case.FunctionTestCase(_func, arg=_args)) return self.suiteClass(tests) nose.main(testLoader=CustomLoader) Executing it: % python runner.py 'testFile.test_evens(2, 6)' -v testFile.check_even(2, 6) ... ok % python runner.py 'testFile.test_evens(2, 6)' 'testFile.test_evens(4, 12)' -v testFile.check_even(2, 6) ... ok testFile.check_even(4, 12) ... ok % python runner.py 'testFile.test_evens(1, 3)' -v testFile.check_even(1, 3) ... FAIL
Python wrapper amazon product api Question: I was trying to install the following python wrapper for Amazons product api: <http://pypi.python.org/pypi/python-amazon-product-api/0.2.5a1> I'm getting an error "File "setup.py", line 3, in from setuptools import setup, find_packages ImportError: No module named setuptools" once I run the setup.py script. I was wondering if there is something I'm doing wrong. Also, is there some other python wrapper you guys would recommend? Thanks! Answer: You need to install SetupTools first: <http://pypi.python.org/pypi/setuptools#downloads>
Detecting Key Presses using win32api in Python Question: I'm trying to break a loop in Python with a specific key press using win32api. How would one go about this? What is the actual version of **win32api.KeyPress('H')** , in the following code? **Revised:** import win32api while True : cp = win32api.GetCursorPos() print cp if win32api.KeyPress('H') == True : break I want to be able to break a loop by pressing the **h** key. **Edit:** I'm attempting to make a program that repeatedly reports mouse positions and I need a mechanism to exit said program. See revised code. Answer: `win32api` is just an interface to the underlying windows low-level library. See the [`GetAsyncKeyState` Function](http://msdn.microsoft.com/en- us/library/ms646293%28v=vs.85%29.aspx): > Determines whether a key is up or down at the time the function is called, > and whether the key was pressed after a previous call to GetAsyncKeyState. > > Syntax SHORT WINAPI GetAsyncKeyState( __in int vKey ); > Return Value > > Type: `SHORT` > > If the function succeeds, the return value specifies whether the key was > pressed since the last call to GetAsyncKeyState, and whether the key is > currently up or down. If the most significant bit is set, the key is down, > and if the least significant bit is set, the key was pressed after the > previous call to GetAsyncKeyState. Note that the return value is bit-encoded (not a `boolean`). To get at `vKey` values, an application can use the virtual-key code constants in the `win32con` module. For example, testing the "CAPS LOCK" key: >>> import win32api >>> import win32con >>> win32con.VK_CAPITAL 20 >>> win32api.GetAsyncKeyState(win32con.VK_CAPITAL) 0 >>> win32api.GetAsyncKeyState(win32con.VK_CAPITAL) 1 The virtual-key constant for simple letters are ASCII codes, so that testing the state of the "H" key (key was pressed) will look like: >>> win32api.GetAsyncKeyState(ord('H')) 1
Provide C#'s namespace from IronPython Question: I want to write Tomboy add-on using IronPython and I'm stuck and very beginning -- I need to provide C#'s namespace. I mean, here's howto in writing Tomboy add-on's <http://live.gnome.org/Tomboy/HowToCreateAddins> > Let's start with creating the plugin file called InsertDateTime.cs with the > following content: > > > using Tomboy; > > namespace Tomboy.InsertDateTime > { > public class InsertDateTimeAddin : NoteAddin > { > public override void Initialize () > { > } > > public override void Shutdown () > { > } > > public override void OnNoteOpened () > { > } > } > } > Can I do that with IronPython? Thank you. Answer: From Python you can import the clr module and then call clr.AddReference('AssemblyName') where assembly name is a partial or full assembly name - maybe in your case it's Tomboy, it's whatever you'd compile against with C#. Then you can do "import Tomboy" or "from Tomboy import NoteAddin". If you're hosting IronPython via the hosting APIs you can instead do scriptRuntime.LoadAssembly(typeof(NoetAddin).Assembly); so that you don't have to do it in Python. That can be particularly useful to avoid various loader context issues depending on how the assembly gets loaded.
Unable to locate freeimage after install of mahotas in Python Question: Hi I am new to Python and am following the [Python Image Tutorial](http://pythonvision.org/basic-tutorial). The following executes with no errors after installing the packages described in the tutorial import numpy import scipy import pylab import pymorph import mahotas from scipy import ndimage However when I try reading an image image = mahotas.imread('picture_file.jpg') I get > > > image = mahotas.imread('image_file.jpg') Traceback (most recent call > last): File "", line 1, in File "/usr/local/lib/python2.6/dist- > packages/mahotas-0.6.4-py2.6-linux-i686.egg/mahotas/**init**.py", line 68, > in imread raise ImportError('mahotas.imread dependends on freeimage. Could > not find it. Error was: %s' % e) ImportError: mahotas.imread dependends on > freeimage. Could not find it. Error was: mahotas.freeimage: could not find > libFreeImage in any of the following directories: > '/usr/local/lib/python2.6/dist- > packages/mahotas-0.6.4-py2.6-linux-i686.egg/mahotas', '/lib', '/usr/lib', > '/usr/local/lib', '/opt/local/lib' I tried installing FreeImagePy and can import it with no problems but it does not help. I have tried adding to the Python path using package sys but not help either. EDIT: I should have mentioned that all the packages except pymorph and mahotas was installed on my linux box doing '*sudo apt-get install package_name*' while pymorph and mahotas was installed by downloading and doing '_sudo python setup.py install_ '. Answer: **Answer for more recent versions of mahotas** Mahotas itself does not have the functionality to read in images. imread is just a wrapper around one of 3 backends: 1. mahotas-imread (i.e., <https://pypi.python.org/pypi/imread>) 2. FreeImage 3. matplotlib (which only supports PNG & JPEG) Thus, you need to install one of the packages above. Freeimage can be installed on Ubuntu as described below. If you are running on Windows, you may wish to try [Christoph Gohlke’s packages](http://www.lfd.uci.edu/~gohlke/pythonlibs/#mahotas). **Original answer (for older versions of mahotas)** You need to install freeimage to be able to use `mahotas.imread` (everything else will actually work without it, it's an optional dependency). This is not a Python package per se, just a regular library. I don't know what distribution you are in, but try looking for a freeimage package. On debian/ubuntu, you can just do: sudo apt-get install libfreeimage3 You will have a file `libfreeimage.so` in `/usr/lib` or in a similar place and everything will work.
What is the fastest way to learn Javascript? Question: What is the fastest way to learn Javascript for someone eloquent with class- based OOP & typed functional programming (Scala, Java), and having some knowledge of metaprogramming (Python, Ruby, Clojure)? Answer: This is probably a subjective question. :-) * Play with it. * Try to solve real problems with it. * Read Crockford: [online](http://javascript.crockford.com/), [book](http://oreilly.com/catalog/9780596517748). Note that Crockford is intelligent and well-informed, but does sometimes blur the line between fact and his opinion in his writing. (The section on inheritance is particularly affected by this.) * I found [JavaScript: The Definitive Guide](http://oreilly.com/catalog/9780596101992) by Flanagan useful. And apparently so have lots of others, as it's in its sixth edition now. * [The spec](http://ecma-international.org/ecma-262/5.1/) is worth reading as well, if a bit hard going in places. * ~~If you're interested in inheritance, the documentation for my[`Lineage` script](http://code.google.com/p/lineagejs/) may be useful as it compares using the script and doing it without the script, and so goes into some of the plumbing details. (You may also find the script handy.)~~ As of ES2015 (aka "ES6"), `Lineage` is redundant; just use `class` (transpiling if necessary with tools like [Babel](http://babeljs.io).) * Read [questions and answers](http://stackoverflow.com/questions/tagged/javascript) about JavaScript here at StackOverflow. Then you'll see what real problems people have, and how they get solved. * Closures are a very big thing in JavaScript, I'd [read up on them](http://blog.niftysnippets.org/2008/02/closures-are-not-complicated.html) (disclosure: that's my blog again). * * * Side note: If you plan to use JavaScript in a browser environment, to manipulate the DOM, etc., I'd recommend using a library to help smooth over the browser differences (mostly DOM and event related). There are plenty to choose from: [jQuery](http://jquery.com), [Prototype](http://prototypejs.org), [YUI](http://developer.yahoo.com/yui/), [Closure](http://code.google.com/closure/library), or [any of several others](http://en.wikipedia.org/wiki/List_of_JavaScript_libraries). But make no mistake, regardless of what library you use (or if you don't use any), it's important to understand the _language_.
How to specify py2app icon? Question: How do I specify the icon file when using py2app? Just now I create the setup file: py2applet --make-setup MyApplication.py and then build the application bundle: python setup.py py2app -A where is it that I specify the icon file.. getting a little confused. Thanks for any help. according to this link- <http://packages.python.org/py2app/options.html>, I should add it as an option. Currently my setup.py file looks like this: """ This is a setup.py script generated by py2applet Usage: python setup.py py2app """ from setuptools import setup APP = ['hello.py'] DATA_FILES = ['chalkboard.jpg'] OPTIONS = {'argv_emulation': True, 'iconfile': '/Users/grahamethomson/Documents/College/HND/oop/game/personal developoment/G/icon.icns'} setup( app=APP, data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2app'], ) Answer: In your setup.py, add iconfile """ This is a setup.py script generated by py2applet Usage: python setup.py py2app """ from setuptools import setup APP = ['main.py'] DATA_FILES = [] OPTIONS = { 'iconfile':'icon.icns', 'plist': {'CFBundleShortVersionString':'0.1.0',} } setup( app=APP, name='MacApp', data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2app'], )
How can I get input and raw_imput functions to work in Python? Question: Whenever I use input and raw_imput in Python, it gives me an error report. Such as in the simple number guessing game. This is what happens: >>> import random >>> number= random.randint(1,100) >>> guess= input("guess a number. ") Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'input' is not defined The same thing happens when I use raw_input. Does anyone know what's going on? Answer: "imput" is not a standard function in Python. Spell it like "input".
Reading BerkleyDB files from python: `\x01\x0b\x88\x0c\x01`? Question: **This question in a nutshell: what do`\x04++HLMh7EjP3ILSfF\x00` and** '\x01\x0b\x88\x0c\x01-\x10\x02\x06!\x05"\x05#\n$\x0c\'\x0e%\x0b\x01&\x02\'\x06(\n\x00\x00' **mean?** Hi all, I'm trying to read palm pre 2 database files. Some information is available [in the documentation](https://developer.palm.com/content/api/dev- guide/mojo/db8.html), but not enough for me to clearly understand the format. Using the `file` command, I learnt that the format was `objects.db: Berkeley DB (Btree, version 9, native byte-order)`. Trying to open the database directly using `bsddb.open()` didn't work; I had to use >>> env = bsddb.db.DBEnv() >>> env.open(None, bsddb.db.DB_CREATE | bsddb.db.DB_INIT_MPOOL) >>> internal_db = bsddb.db.DB(env) >>> internal_db.open('C:\objects.db', 'objects.db', bsddb.db.DB_BTREE, bsddb.db.DB_RDONLY) Now I've open the database, but the keys and values are encoded in a format which I don't understand: for example, here are some keys: `'\x04++HMvu4v2GZbo1Ox\x00', '\x04++HMwBSPR8Zvwkt5\x00', '\x04++HMwF4OJ0R+WeSS\x00'`, and a value: '\x01\x0b\xb7\r\x00\x05\xee\x89\x10\x029\x060\x04\x00/\x03\x04++HQqD0wWr_hZP75\x00\x00 \x02"\x06\x00$\x04inbox\x001\x02+\x04+33626320868\x00\x00%\x0e\x00\x00\x01.0\x19\xb3\x10&\x04Ok\x00-\rM\\/\x892\n:\r\x00\x05\xee\x89\'\x04sms\x003\n(\x04successful\x00.\rM\\/\x89\x00' I tried to decode it from utf8, but I didn't get any convincing results. Do you recognize which encoding is being used? I don't understand the `native byte-order` part of the output of the `file` command, could it be related to this? Thanks! Answer: ### Educated guess From simple inspection, The message is probably "sms successful", with a phone number: > > > unicode(s, errors='ignore') > u'\x01\x0b\r\x00\x05\x10\x029\x060\x04\x00/\x03\x04++HQqD0wWr_hZP75\x00\x00 > \x02"\x06\x00$\x04inbox\x001\x02+\x04+33626320868\x00\x00%\x0e\x00\x00\x01.0\x19\x10&\x04Ok\x00-\rM\/2\n:\r\x00\x05\'\x04sms\x003\n(\x04successful\x00.\rM\/\x00' I think the other characters are binary data. ### Encodings Decoding it did not help - Both chardet and BeautifulSoup detects this as `windows-1252`: >>> s=u'\x01\x0b\xb7\r\x00\x05\xee\u2030\x10\x029\x060\x04\x00/\x03\x04++HQqD0wWr_hZP75\x00\x00 \x02"\x06\x00$\x04inbox\x001\x02+\x04+33626320868\x00\x00%\x0e\x00\x00\x01.0\x19\xb3\x10&\x04Ok\x00-\rM\\/\u20302\n:\r\x00\x05\xee\u2030\'\x04sms\x003\n(\x04successful\x00.\rM\\/\u2030\x00' >>> from BeautifulSoup import BeautifulSoup >>> soup = BeautifulSoup(s) >>> soup.originalEncoding 'windows-1252' >>> chardet.detect(s) {'confidence': 0.5, 'encoding': 'windows-1252'} However, the 1252 decoding gives nothing meaningful: >>> s.decode('windows-1252') u'\x01\x0b\xb7\r\x00\x05\xee\u2030\x10\x029\x060\x04\x00/\x03\x04++HQqD0wWr_hZP75\x00\x00 \x02"\x06\x00$\x04inbox\x001\x02+\x04+33626320868\x00\x00%\x0e\x00\x00\x01.0\x19\xb3\x10&\x04Ok\x00-\rM\\/\u20302\n:\r\x00\x05\xee\u2030\'\x04sms\x003\n(\x04successful\x00.\rM\\/\u2030\x00'
Script for parsing a biological sequence from a public database in Python Question: Greetings to the stackoverflow community, I am currently following a bioinformatics module as part of a biomedical degree (I am basically a python newbie) and the following task is required as part of a Python programming assignment: extract motif sequences (amino acid sequences, so basically strings in programmatic-speak, that have been excised from algorithms implementing a multiple sequence alignment and subsequently iterative database scanning to generate the best conserved sequences. The ultimate idea is to infer functional significance from such "motifs"). These motifs are stored on a public database in files which have multiple data fields corresponding to each protein (uniprot ID, Accession Number, the alignment itself stored in a hyperlink .seq file), currently one of which is of interest in this scope. The data field is called "extracted motif sets". My question is how to go about writing a script that will essentially parse the "motif strings" and output them to a file. I have now coded the script so that it looks as follows (I don't write the results to files yet): import os, re, sys, string printsdb = open('/users/spyros/folder1/python/PRINTSmotifs/prints41_1.kdat', 'r') protname = None final_motifs = [] for line in printsdb.readlines(): if line.startswith('gc;'): protname = line.lstrip() #string.lower(name) # convert to lowercase break def extract_final_motifs(protname): """Extracts the sequences of the 'final motifs sets' for a PRINTS entry. Sequences are on lines starting 'fd;' A simple regex is used for retrieval""" for line in printsdb.readlines(): if line.startswith('fd;'): final_motifs = re.compile('^\s+([A-Z]+)\s+<') final_motifs = final_motifs.match(line) #print(final_motifs.groups()[0]) motif_dict = {protname : final_motifs} break return motif_dict = extract_final_motifs('ADENOSINER') print(motif_dict) The problem now is that while my code loops over a raw database file (prints41_!.kdat) instead of connecting to the public database using urllib module, as suggested by Simon Cockell below, the ouput of the script is simply "none" on the python shell, whereas it should be creating a list such as [AAYIGIEVLI, AAYIGIEVLI, AAYIGIEVLI, etc..] Does anybody have any idea where the logic error is? Any input appreciated!! I apologize for the extensive text, I just hope to be a clear as possible. Thanks in advance for any help! Answer: First of what you are doing is almost right but you have to change `"extracted motif sets"` lien 2 to a variable say `line` . What the `for` loop will do is to return data form the file line by line as the variable after `for` this case `line`. And now comes the question how the `lysozyme.seq` file is formated. its sounds like that none of the data fields have any spacing. Then that means you might get away whit doing `line.split(" ")` or `line.split("\t")` `\t` meas tab. the split will do what it says it dose split the string every time it sees a `" "` or `"\t"` depending on what you write in the program. Saning directory to find the files shouldn't be to hard theres probably some questions here about it. If you post data or a part of in form one of the files so we can have a look at it the we might be able to help you pars it :).
Haystack indexes not all items Question: I am using **django haystack** with **whoosh** for full-text search. There are nine different models to index, but when I search for indexed entries, it seems that none or not all of them get indexed for some models. I try this at django shell, but I get 0 for some of the models when all nine models are indexed, whereas I get all of them if I index just some models. from haystack.query import SearchQuerySet SearchQuerySet().models(OneOfMyModels).count() For example, I have Article model which is correctly indexed and all 1029 items are found if I rebuild index just for Article. But I get 0 results of Article items, when I rebuild index for all 9 my searchable models. Versions of software that I am using: * python 2.6 * django 1.3 * haystack 1.1 * whoosh 1.8 Are there any limitations in whoosh for the amount of indexed models or found items? What could cause such strange behavior? Have you experienced anything similar? How did you solve it? Answer: Haystack search seems to work well when I downgrade whoosh to 1.3.3.