text
stringlengths
226
34.5k
Is C, Java and Python a good combination for future? Question: i just wanna be a programmer in the future, do you think, that i'm doing right if i'm going to learn this combination (C\Java\Python)? I know Java well, C is also on a good level. I just wanna be able to understand a low level code and also be able to build enterprise apps, is this right combination? Thanks for your responses and sorry for my English. Answer: I would also suggest learning a functional programming language like _Ocaml_ or _Haskell_ or _Clojure_ or maybe _Scala_ or _Scheme_. And most importantly, don't believe that you'll stop learning: you'll need to continue **learning things your whole life** (both technological stuff -new languages and libraries- and conceptual stuff -new ways of thinking and formalizing-). The ability to learn quickly and continuously is at least as important as what you already know.
Python: Replacing certain Unicode entities with entities from dictionary Question: I have read already much about the problem of backslash escaping in python strings (and backslash recognition in Python in different encodings) and using backslashes in regular expressions, but still cannot solve my problem. I would highly appreciate any help (links, code examples, etc). I am trying to replace hexadecimal codes in strings with certain elements from dictionary using **re**. The codes are of type _'\uhhhh'_ where _hhhh_ is hex number. I select strings from sqlite3 table; by default they are read as unicode and not as "raw" unicode strings. import re pattern_xml = re.compile(r""" (.*?) ([\\]u[0-9a-fA-F]{4}) (.*?) """, re.VERBOSE | re.IGNORECASE | re.DOTALL) uni_code=['201C','201D'] decoded=['"','"'] def repl_xml(m): item=m.group(2) try: decodeditem=decoded[uni_code.index(item.lstrip('\u').upper())] except: decodeditem=item return m.group(1) + "".join(decodeditem) + m.group(3) #input text = u'Try \u201cquotated text should be here\u201d try' #text after replacement decoded_text=pattern_xml.subn(repl_xml,text)[0] #desired outcome desired_text=u'Try "quotated text should be here" try' So, I want _decoded_text_ to be equal to _desired_text_. I did not succeed in replacing single backslash with double backslash or forcing python to treat text as raw unicode string (so that backslashes are treated literally and not like escape characters). I also tried using re.escape(text) and setting re.UNICODE, but in my case that doesn't help. I'm using Python 2.7.2. Which solutions can be found to this problem? Edit: I have actually found out a possible solution to this problem on [StandardEncodings](http://docs.python.org/release/2.5.2/lib/standard- encodings.html) and [PythonUnicodeIntegration](http://www.egenix.com/www2002/python/unicode- proposal.txt) by applying the following encoding to _input_ : text.encode('unicode_escape') Is there anything else to do? Answer: The sample text doesn't contain any backslashes. The `\u201c` is just a way of representing a unicode character: >>> text = u'Try \u201cquotated text should be here\u201d try' >>> '\\' in text False >>> print text Try “quotated text should be here” try A regex is not really required here. Just translate the target unicode characters as desired: >>> table = {0x201c: u'"', 0x201d: u'"'} >>> text.translate(table) u'Try "quotated text should be here" try'
Loops and totals in Python Question: I am trying to write a program to draw a histogram of the lengths of words present in a list, so far I am up the stage of increasing the number of words present of a certain length by one every time the loop finds a word with that certain length, at the moment I have: L = [] for i in range(L): length = len(i) for len(i) = 1: total1 = total1 + 1 for len(i) = 2: total2= total2 + 1 for len(i) = 3: total3 = total3 + 1 for len(i) = 4: total4 = total4 + 1 for len(i) = 5: total5 = total5 + 1 However clearly this is a stupid method as it involved naming each version of totaln, where in this case n would be up to 11, so my question is can I simply put L = [] for i in range(L): length = len(i) for len(i) = n: totaln = totaln + 1 to cover all values of n, and then refer to for example total4 later? Or will the interpreter return an error as total4 isn't explicitly defined? As for the rest of the code I think I can work that bit out, it's just this issue I am having trouble with, being very new to programming. Answer: In Python 2.7 or above, you could use a [`Counter`](http://docs.python.org/library/collections.html#collections.Counter): from collections import Counter a = ["basically", "in", "Python", "I", "am", "trying", "to", "write", "a", "program", "to", "draw", "a", "histogram", "of", "the", "lengths", "of", "words", "present", "in", "a", "list"] print Counter(map(len, a)) prints Counter({2: 7, 1: 4, 7: 3, 4: 2, 5: 2, 6: 2, 9: 2, 3: 1}) which is a dictionary mapping word lengths to frequencies.
CTRL-C terminate in python Question: Currently, I have an exe that I need to pass commands to thru python. The code worked when it was by itself. When I merged that snippet with my final program, it failed to work. Basically, after the first two files upload using the program `shell_start` (upload is `-f` in the program i'm passing commands to), python decides to skip the final upload at the bottom with the program called `shell_forward`. The final upload of 3 files with the program `shell_forward`, doesn't even work. So, my main question, if you're confused, is: why is it that when the program `shell_start` finishes uploading the two commands and files, the python shell won't allow me to type anything in it? It acts like a command prompt window that won't let you type anything into it after code is executed. That is why I feel that a ctrl-c is needed to terminate `shell_start.exe` from the previous process, so python might let me type after it's execution. Here's the code: import os, time name = raw_input("Input your name: ") apn = raw_input("Input apn name: ") ecid = raw_input("Input ecid name: ") kernel = raw_input("Input kernel name: ") os.system('shell_start.exe -f %s'%name) time.sleep(1) os.system('shell_start.exe -f %s'%apn) time.sleep(1) os.system('shell_forward.exe --imagefile myfile.img --ecid %(x)s --kernel %(y)s '% {"x" : ecid, "y" : kernel}) Answer: You may have better results by replacing the `os.system` calls with [`subprocess`](http://docs.python.org/library/subprocess.html). > The subprocess module allows you to spawn new processes, connect to their > input/output/error pipes, and obtain their return codes. This module intends > to replace several other, older modules and functions, such as: > > > os.system > os.spawn* > os.popen* > popen2.* > commands.* > > > See also [_PEP 324_](http://www.python.org/dev/peps/pep-0324/) – PEP > proposing the subprocess module
Converting a string of tuples to a list of tuples in Python Question: How can I convert `"[(5, 2), (1,3), (4,5)]"` into a list of tuples `[(5, 2), (1,3), (4,5)]` I am using `planetlab` shell that does not support `"import ast"`. So I am unable to use it. Answer: If [`ast.literal_eval`](http://docs.python.org/library/ast.html#ast.literal_eval) is unavailable, you can use the (unsafe!) [`eval`](http://docs.python.org/library/functions.html#eval): >>> s = "[(5, 2), (1,3), (4,5)]" >>> eval(s) [(5, 2), (1, 3), (4, 5)] However, you should really overthink your serialization format. If you're transferring data between Python applications and need the distinction between tuples and lists, use [pickle](http://docs.python.org/library/pickle.html). Otherwise, use [**JSON**](http://docs.python.org/library/json.html).
QWebKit - Run page's javascript function? Question: Basically I want to go into my Router's settings, set a checkbutton and than call a function on the page, all programmatically. I know all the javascript to do this, and can do it via the Google Chrome console. I can syntactically perform it through QWebKit, but the actual page remains unaffected. import sys from PyQt4 import QtCore, QtGui, QtWebKit class Browser(QtWebKit.QWebView): def __init__(self, parent = None): super(Browser, self).__init__() self.changepage() def changepage(self): self.load(QtCore.QUrl("http://192.168.0.1/adv_mac_filter.php")) x1 = self.page().mainFrame() x1.evaluateJavaScript("entry_enable_1.checked = true;") x1.evaluateJavaScript("check();") app = QtGui.QApplication(sys.argv) x = Browser() x.show() sys.exit(app.exec_()) (Yes, this code requires that I am already logged into my routers settings) I know the JavaScript is being run, as I can test it using Alerts. However, the routers' html "checked()" function or checkbox aren't ran / changed. It's like I'm not actually interacting with the page, but a copy. Am I making a massive rookie mistake here? * * * Specs: python 2.7 PyQt4 QWebKit Windows 7 Answer: You should probably wait for the page to finish loading, by moving the javascript evaluation to a slot connected to the `loadFinished()` signal. But as Pointy suggested, you could also try to send POST requests yourself, through `QNetworkAccessManager`, instead of using a widget.
Connecting to Microsoft Dynamics CRM 2011 SDK from Python Question: Has anyone had any luck connecting to the 2011 endpoints in Microsoft Dynamics CRM 2011 using Python? I've installed SUDS and can grab the WSDL, but service calls return 400 Bad Request. I'm sure it's because I'm not authenticated, but I'm not quite sure how to authenticate using raw SOAP. I know about [Girish's code sample](http://code.msdn.microsoft.com/CRM- Online-2011-WebServices-14913a16) but am not familiar enough with SOAP to go much further. I see this was asked [a year ago on SO](http://stackoverflow.com/questions/3294587/how-can-i-connect-to-a- microsoft-dynamics-crm-server-using-python) but that question seems to be about NTLM. In my case, I want to use WS-Trust. Here is the code I've got: from suds.client import Client import logging logging.basicConfig(level=logging.INFO) url = 'https://dev.crm.dynamics.com/XRMServices/2011/Discovery.svc?wsdl' client = Client(url) req = client.factory.create('ns3:RetrieveOrganizationsRequest') accessTypes = client.factory.create('ns3:AccessType') orgRel = client.factory.create('ns3:OrganizationRelease') req.AccessType = accessTypes.Default req.Release = orgRel.Current headers = dict() headers['Content-Type'] = 'application/soap+xml' client.set_options(headers=headers) resp = client.service.Execute(req) Answer: If using SOAP isn't a requirement -- consider the [RESTish Odata](http://msdn.microsoft.com/en-us/library/gg334279.aspx) service. I'm no Python expert -- but you could run through GET requests in a browser and use the debugger tools to see what the browser sends for headers and mimic this in your Python code. You'd have some choice over what format the service returns (JSON or XML) as well by modifying the Content-Type header.
Monte Carlo and Area -calculation Question: It should be close to 0.3 $ cat monte.py import random,math density=int(1e6) x = [random.uniform(0,1)*7*math.pi for _ in range(density)] y = [random.uniform(0,1) for _ in range(density)] i = [math.sin(xx)*math.cos(xx) > yy for (xx,yy) in zip(x,y)] print sum(i)/(float(density)*10.0)*7*math.pi $ python monte.py 0.350184850795 I am trying to rewrite the below but for some reason the python code is not even close. x = rand(1, 1000000)*7pi; y = rand(1, 1000000); i = sin(x).* cos(x) >y; Area3 = (sum(i) / 10000000)*7pi; Answer: I'm getting identical results between your matlab and python versions... Are you sure that the matlab version is giving you ~2, and not ~0.35? For example: MATLAB: x = rand(1, 1000000)*7*pi; y = rand(1, 1000000); i = sin(x).* cos(x) >y; Area3 = (sum(i) / 10000000)*7*pi This yields: `0.3511` Your pure-python version: import random,math density=int(1e6) x = [random.uniform(0,1)*7*math.pi for _ in range(density)] y = [random.uniform(0,1) for _ in range(density)] i = [math.sin(xx)*math.cos(xx) > yy for (xx,yy) in zip(x,y)] print sum(i)/(float(density)*10.0)*7*math.pi This yields: `0.347935156296` Numpy-based: import numpy as np x = np.random.random(1e6) * 7 * np.pi y = np.random.random(x.size) i = np.sin(x) * np.cos(x) > y print 7 * np.pi * i.sum() / (10 * x.size) This yields: `0.350475133957`
What code is executed when a class is being defined? Question: When I import a module that has a class, what code is executed when that class is first read and the class object created? Is there any way I can influence what happens? * * * **Edit:** I realize my question might be a bit too general... I'm looking for something more low-level which will allow me to do introspection from C++. I extend my C++ application with Python. I have some classes that are defined in C++ and exposed in Python. The user can inherit from these classes in the scripts and I want to be able to grab details about them when they are first defined. Answer: Many possible things can happen. The most basic: The contents of the `class` block are executed when the it is first read. To see this in action, this example: class Foo(object): print "bar" def __init__(self): print "baz" Will print `bar` when the module is imported. If a class has a metaclass defined, the metaclasses `__new__` function will run after the classes block of code is run. Example: class MyMeta(type): def __new__(mcs, name, bases, kwargs): print "I'm the metaclass, just checking in." return type.__new__(mcs, name, bases, kwargs) class Foo(object): __metaclass__ = MyMeta print "I'm the Foo class" Output: I'm the Foo class I'm the metaclass, just checking in. I'm sure other bits can run as well, these are just what I am familiar with.
"IOError No such file or directory" for an image file that IS in the current directory Question: I'm using Python Imaging Library and Tkinter. I am currently trying to display an image as a label, and I'm getting the above exception. My 35 line source: from PIL import Image, ImageTk from Tkinter import Tk, Frame, Label class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Label") self.img = Image.open("diesl.jpg") diesl = ImageTk.PhotoImage(self.img) label = Label(self, image=diesl) label.image = diesl label.pack() self.pack() def setGeometry(self): w, h = self.img.size self.parent.geometry(("%dx%d+300+300") % (w, h)) def main(): root = Tk() ex = Example(root) ex.setGeometry() root.mainloop() if __name__ == '__main__': main() Answer: Actually, you are right in your comment: Notepad++ seems to launch the files from its own directory. You can find the solution to your problem here: <http://damienlearnsperl.blogspot.com/2009/01/launch-your-perl-script-from- notepad.html> (check Lee's comment) if you still intend to use Notepad ++
Conversion from geographic to geomagnetic coordinates Question: I'm trying to convert between geographic and geomagnetic coordinates. I've found the following Prolog script, but I don't understand it enough to convert it myself. The target language is Java, but anything understandable is fine (C, Python, VB, whatever). <http://idlastro.gsfc.nasa.gov/ftp/pro/astro/geo2mag.pro> If someone could either help with the conversion of this script or explain what exactly it is doing (those array operations are baffling to me), I'd really appreciate it. Thanks Answer: Depending on the application, altitude can be an important variables in this coordinate conversion since geomagnetic coordinates are a mapping of the Earth's dipole magnetic field. In Python you can easily convert geographic coordinates to geomagnetic (and vice versa) with SpacePy (<http://sourceforge.net/projects/spacepy/>). Since you are looking for the source code to convert to Java, SpacePy is implementing the Fortran International Radiation Belt Environment Modeling (IRBEM) library, the source of which is available (<http://irbem.svn.sourceforge.net/viewvc/irbem/web/index.html>) In Python, in case others are looking for a quick solution: import spacepy.coordinates as coord from spacepy.time import Ticktock import numpy as np def geotomag(alt,lat,lon): #call with altitude in kilometers and lat/lon in degrees Re=6371.0 #mean Earth radius in kilometers #setup the geographic coordinate object with altitude in earth radii cvals = coord.Coords([np.float((alt/Re+Re))/Re,np.float(lat),np.float(lon)], 'GEO', 'sph',['Re','deg','deg']) #set time epoch for coordinates: cvals.ticks=Ticktock(['2012-01-01T12:00:00'], 'ISO') #return the magnetic coords in the same units as the geographic: return cvals.convert('MAG','sph')
complex SOAP request prints single line response Question: I am completely new to Python and Suds.In order to test different clients, I succeeded in C#, java, perl and now term is about Python-suds...can some one help... here is the client code---- from suds.client import Client wsdl = 'http://www.cbs.dtu.dk/ws/SignalP/SignalP_3_1_ws0.wsdl' client = Client(wsdl) seq="""val1 val2 val3""" print client.service.runService(seq) and sending request envelope is.... <parameters> <organism> val1 </organism> <sequencedata> <sequence> <id>val2</id> <seq>val3</seq> </sequence> </sequencedata> </parameters> Answer: I figured out an answer myself, but it seems it's not 100%; I am getting a correct response envelope, but the request envelope has incorrect formatting for `val2` and `val3`. Here I put altogether (I used logging to know the input/ouput): from suds.client import Client import logging logging.basicConfig(level=logging.INFO) logging.getLogger('suds.client').setLevel(logging.DEBUG) # soap messages (in&out) and http headers wsdl = 'http://www.cbs.dtu.dk/ws/SignalP/SignalP_3_1_ws0.wsdl' client = Client(wsdl, cache=None,) seq = client.factory.create('ns1:sequence') seq.id="XXXXX" seq.seq="KBVGHGKLGKLGKHGJHG" req = client.factory.create('ns1:method') req.parameters.organism="val1" req.parameters.sequencedata.sequence=seq; response = client.service.runService(req)
python libXML2 remove Item Question: I am using libxml2 under python. Unfortunatly the python version of this library is really badly documented and i founded just few example on the web from there i could understand some of the method. I managed the add a soon te a XML Node. Since this element should replace an existing one I would like to remove the previos one before but i could not find which is the method to remove a child. Does anyone know what is the method name? does anyone have a decent documentation about this library? Cheers Answer: You can use the `unlinkNode()` method to remove a given node. In general, most of the methods that apply to nodes are documented, try: pydoc libxml2.xmlNode For `unlinkNode`, the documentation says: unlinkNode(self) Unlink a node from it's current context, the node is not freed For example, given this input: <html> <head> <title>Document Title</title> </head> <body> <div id="content">This is a test.</div> </body> </html> You can parse the file like this: >>> import libxml2 >>> doc = libxml2.parseFile('input.html') Locate the `<div>` node like this: >>> node = doc.xpathEval('//*[@id="content"])[0] And remove it like this: >>> node.unlinkNode() And now if you print out the document, you get this: >>> print doc <head> <title>Document Title</title> </head> <body> </body> </html>
Python C API unicode arguments Question: I have a simple python script import _tph str = u'Привет, <b>мир!</b>' # Some unicode string with a russian characters _tph.strip_tags(str) and C library, which is compiled into _tph.so. This is a `strip_tags` function from it: PyObject *strip_tags(PyObject *self, PyObject *args) { PyUnicodeObject *string; Py_ssize_t length; PyArg_ParseTuple(args, "u#", &string, &length); printf("%d, %d\n", string->length, length); // ... } `printf` function prints this: _1080, 19_. So, `str` length is really 19 symbols, but from what deep of hell I'm getting those 1080 characters? When I'm printing `string`, I got my `str`, null char, and then a lot of junk bytes. Junk memory looks like this: > u'\u041f\u0440\u0438\u0432\u0435\u0442, > <b>\u043c\u0438\u0440!</b>\x00\x00\u0299\Ub7024000\U08c55800\Ub7025904\x00\Ub777351c\U08c79e58\x00\U08c7a0b4\x00\Ub7025904\Ub7025954\Ub702594c\Ub702591c\Ub702592c\Ub7025934\x00\x00\x00 How I can get a normal string here? Answer: The "string" argument here isn't well named. It is a pointer to a Python Unicode object, so your printf is seeing a lot of binary data (the object type, GC headers, the ref count, and the encoded unicode code points) until it happens to find a zero byte which printf interprets as the end of the string. The simplest way to view the string is with `PyObject_Print(string)`. You can find the C functions for manipulating Python unicode objects at: <http://docs.python.org/c-api/unicode.html#unicode-objects>
Tornado datetime Question: How would I create a datetime stamp from a clients offset? I have been messing around with this all day. The idea is to have a user login and based upon their timezone to create the cookie to expire after so long. #!/usr/bin/env python import tornado.auth import tornado.database import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web import tornado.escape import hashlib import unicodedata import markdown import os.path import re import urllib import sys import time import json import MySQLdb import Cookie from tornado.options import define, options import datetime from nptime import nptime define("port", default=8001, help="Server port", type=int) class Application(tornado.web.Application): def __init__(self): handlers = [ (r"/", MainHandler), (r"/test", Test), ] tornado.web.Application.__init__(self, handlers) self.db = tornado.database.Connection( host=options.mysql_host, database=options.mysql_database, user=options.mysql_user, password=options.mysql_password) class BaseHandler(tornado.web.RequestHandler): @property def db(self): return self.application.db class MainHandler(BaseHandler): def get(self): self.set_header("Content-Type", "text/html") self.write() self.finish() class Test(BaseHandler): def post(self): tmz = self.get_argument('tmz', '') cur = datetime.datetime.utcnow().strftime('%A, %B %d, %Y %I:%M:%S %p 'tmz, gmtime()) self.set_header("Content-Type", "text/html") self.write(cur) self.finish() def main(): tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start() if __name__ == "__main__": main() Where tmz would be the timezone sent example -0400 or +0500 Answer: You could have a hidden datetime input pass the client's current time, including timezone, into the login form: <input type="hidden" name="current_datetime" /> That input's value can be populated with javascript. Then, in your post function, you can add hours or days to the value that current_datetime passes in.
python tkinter display animated GIF using PIL Question: Is there any way to display an animated GIF in Tkinter using Python Image Library? I thought the [ImageSequence module](http://www.pythonware.com/library/pil/handbook/imagesequence.htm) would be the way to do it, but I don't know how to use it and if it's possible. The first question is if there is any easy way. For example: load a GIF using PIL and the ImageSequence and just draw it on a Tkinter window using `ImageTk.PhotoImage` and it will be animated. Or do I have to set up a function myself, using the `after` method or something like `time.sleep` to loop through the GIF frames and draw them on a tkinter window? The second question: even if I have to make a function to loop through the GIF frames, is the ImageSequence module supposed to do this or PIL has another module for it? I'm using Python 3.1 and a [private port of PIL](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil), indicated in this [topic](http://stackoverflow.com/questions/3896286/image-library-for- python-3). Answer: > Newsgroups: comp.lang.python > > From: "Fredrik Lundh" > > Date: Mon, 1 May 2006 > > Daniel Nogradi wrote: > > 'The source distribution of the 1.1.4 version comes with a Scripts directory > where you can find player.py, gifmaker.py and explode.py which all deal with > animated gif.' they're still shipped with 1.1.5 (and 1.1.6), and they should work. if all you're missing is a few files from the script directory, you can get them here: <http://svn.effbot.org/public/pil/Scripts/> * * * player.py is run from the command line see if this one works for you: from Tkinter import * from PIL import Image, ImageTk class MyLabel(Label): def __init__(self, master, filename): im = Image.open(filename) seq = [] try: while 1: seq.append(im.copy()) im.seek(len(seq)) # skip to next frame except EOFError: pass # we're done try: self.delay = im.info['duration'] except KeyError: self.delay = 100 first = seq[0].convert('RGBA') self.frames = [ImageTk.PhotoImage(first)] Label.__init__(self, master, image=self.frames[0]) temp = seq[0] for image in seq[1:]: temp.paste(image) frame = temp.convert('RGBA') self.frames.append(ImageTk.PhotoImage(frame)) self.idx = 0 self.cancel = self.after(self.delay, self.play) def play(self): self.config(image=self.frames[self.idx]) self.idx += 1 if self.idx == len(self.frames): self.idx = 0 self.cancel = self.after(self.delay, self.play) root = Tk() anim = MyLabel(root, 'animated.gif') anim.pack() def stop_it(): anim.after_cancel(anim.cancel) Button(root, text='stop', command=stop_it).pack() root.mainloop()
Web2py + MS SQL Server 2008 R2 + LDAP Authentication HelloWorld application? Question: I have been using Web2py in the awesome *nix environment for sometime along with opensource RDMS (MySQL,Postgre,SQLLite,etc) for my personal projects. For my workplace which is completely working in a .Net environment I need to make a quick web app (employee master data maintenance) which runs on the local intranet with authentication and user roles. I planned to develop the application on web2py and deploy it on the default rocket server BUT am stuck with the DAL. I have tried pyodbc, mssql, mssql2 adapters and all work arounds people have done on the google Group and other forums. My production and deployment environment details are: O/S: MS Windows Server 2008 DB: MS SQL Server 2008 R2 (hosted over LAN and with Windows Authentication not SQL Authentication) Python: 2.7 WebServer: IIS 7.0 ideally but I can work on Rocket. Is there any 'HelloWorld' application tutorial out there which covers these topics: 1. Windows Domain Authentication with user roles in Web2py 2. Web2py-to-MSSQLServer2008R2 DAL 3. Web2py-IIS7.0 Deployment If someone can help me I can post this as a web2py appliance once I am done. Answer: This is a partial answer, it only deals with authentication using Active Directory (I assuma it is the same or similar to Domain Authentication). I am not a Windows expert, but had the local windows admin help me. This is code that I put in the db.py file for this app in web2py. if localauth: # I set localauth to 1 when using the app on my home lan, else 0 # I am a consultant and not always connected to the client VPN # FYI, I do have a db of same type and name with same user/pw at home # in this case use the basic login that comes as default with web2py pass else: from gluon.contrib.login_methods.ldap_auth import ldap_auth auth.settings.login_methods = [ldap_auth(mode='ad', server='<server ip address>', base_dn='<base_dn>')] # the above line forces active directory to be the ONLY authentication method # my base_dn looked like this: 'OU=<ou>,DC=<subdomain>,DC=<domain>,DC=<tld e.g. com, net, edu, etc.>' # an active directory knowledgeable person can help you here Jay
ImportError: No Module name Multiarray Question: So I am using IronPython in PyDev and I am trying to import numpy. However, when I am getting the following error: Traceback (most recent call last): File "C:\Users\Dan\workspace\Practice\src\practice.py", line 8, in <module> File "C:\Python27\Lib\site-packages\numpy\__init__.py", line 137, in <module> File "C:\Python27\Lib\site-packages\numpy\add_newdocs.py", line 9, in <module> File "C:\Python27\Lib\site-packages\numpy\lib\__init__.py", line 4, in <module> File "C:\Python27\Lib\site-packages\numpy\lib\type_check.py", line 8, in <module> File "C:\Python27\Lib\site-packages\numpy\core\__init__.py", line 5, in <module> ImportError: No module named multiarray Is it because there is only a `multiarray.pyd` file instead of a `multiarray.py` file? What can I do about this? Thanks in advance. Edit: One more thing, so import numpy works when I use it in the Python IDLE that comes with the python download, and I am using Windows 7. Answer: I don't think you can import the 'regular' numpy from IronPython (but it seems there's a port for IronPython you could use... <http://pytools.codeplex.com/wikipage?title=NumPy%20and%20SciPy%20for%20.Net> )
Python Regular Expression OR not matching Question: For some reason, m = re.search('(<[^pib(strong)(br)].*?>|</[^pib(strong)]>)', '</b>') matches the string, but m = re.search('(</[^pib(strong)]>)', '</b>') does not. I am trying to match all tags that are _not_ <p>, <b>, </p>, </b> and so on. Am I misunderstanding something about how '|' works? Answer: You're doing it wrong. First of all, characters between `[]` are matched differently: `[ab]` will match either `a` or `b`, so in your case `[^pib(strong)]` will match everything that is not a `p`, an `i`, a `b`, a `(`, etc. (note the negation from `^`). Your first regex matching is merely a coincidence. Also, you shouldn't be parsing html/xml with regex. Instead, use a proper xml parsing library, like lxml or beautifulsoup. Here's a simple example with `lxml`: from lxml import html dom = html.fromstring(your_code) illegal = set(dom.cssselect('*')) - set(dom.cssselect('p,b')) for tag in illegal: do_something_with(tag) (this is a small, probably sub-optimal example; it serves just to show you how easy it is to use such a library. Also, note that the library will wrap the code in a `<p>`, so you should take that into consideration)
python sqlite3 error in FreeBSD 9 Question: Trying to install this ipython version. infact there's a django-starter project which uses buildout for his needs.. And that scripts tried to get ipython 0.11 with easy_install.I tried to grep everything out from this package but there's no ipython mentioned in any files at all. so I can't install newer version I need ipython0.11 to work. Please =) roman# easy_install "ipython==0.11" > errors Traceback (most recent call last): File "/usr/local/bin/easy_install", line 8, in <module> load_entry_point('setuptools==0.6c11', 'console_scripts', 'easy_install')() File "build/bdist.freebsd-9.0-RC1-amd64/egg/setuptools/command/easy_install.py", line 1712, in main File "build/bdist.freebsd-9.0-RC1-amd64/egg/setuptools/command/easy_install.py", line 1700, in with_ei_usage File "build/bdist.freebsd-9.0-RC1-amd64/egg/setuptools/command/easy_install.py", line 1716, in <lambda> File "/usr/local/lib/python2.7/distutils/core.py", line 152, in setup dist.run_commands() File "/usr/local/lib/python2.7/distutils/dist.py", line 953, in run_commands self.run_command(cmd) File "/usr/local/lib/python2.7/distutils/dist.py", line 972, in run_command cmd_obj.run() File "build/bdist.freebsd-9.0-RC1-amd64/egg/setuptools/command/easy_install.py", line 211, in run File "build/bdist.freebsd-9.0-RC1-amd64/egg/setuptools/command/easy_install.py", line 446, in easy_install File "build/bdist.freebsd-9.0-RC1-amd64/egg/setuptools/command/easy_install.py", line 476, in install_item File "build/bdist.freebsd-9.0-RC1-amd64/egg/setuptools/command/easy_install.py", line 655, in install_eggs File "build/bdist.freebsd-9.0-RC1-amd64/egg/setuptools/command/easy_install.py", line 930, in build_and_install File "build/bdist.freebsd-9.0-RC1-amd64/egg/setuptools/command/easy_install.py", line 919, in run_setup File "build/bdist.freebsd-9.0-RC1-amd64/egg/setuptools/sandbox.py", line 62, in run_setup File "build/bdist.freebsd-9.0-RC1-amd64/egg/setuptools/sandbox.py", line 105, in run File "build/bdist.freebsd-9.0-RC1-amd64/egg/setuptools/sandbox.py", line 64, in <lambda> File "setup.py", line 54, in <module> File "/tmp/easy_install-4FA3NZ/ipython-0.11/IPython/__init__.py", line 46, in <module> File "/tmp/easy_install-4FA3NZ/ipython-0.11/IPython/frontend/terminal/embed.py", line 32, in <module> File "/tmp/easy_install-4FA3NZ/ipython-0.11/IPython/frontend/terminal/interactiveshell.py", line 26, in <module> File "/tmp/easy_install-4FA3NZ/ipython-0.11/IPython/core/interactiveshell.py", line 36, in <module> File "/tmp/easy_install-4FA3NZ/ipython-0.11/IPython/core/history.py", line 20, in <module> File "/usr/local/lib/python2.7/sqlite3/__init__.py", line 24, in <module> from dbapi2 import * File "/usr/local/lib/python2.7/sqlite3/dbapi2.py", line 85, in <module> register_adapters_and_converters() File "/usr/local/lib/python2.7/sqlite3/dbapi2.py", line 80, in register_adapters_and_converters register_adapter(datetime.date, adapt_date) NameError: global name 'register_adapter' is not defined **update:** importing sqlite3 from python console gives this error: >>> import sqlite3 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/sqlite3/__init__.py", line 24, in <module> from dbapi2 import * File "/usr/local/lib/python2.7/sqlite3/dbapi2.py", line 85, in <module> register_adapters_and_converters() File "/usr/local/lib/python2.7/sqlite3/dbapi2.py", line 80, in register_adapters_and_converters register_adapter(datetime.date, adapt_date) NameError: global name 'register_adapter' is not defined Answer: Judging from your error message and our exchange in the comments, I think the big problem is you might just be missing sqlite3 support for python. From your error messages I take it you're running FreeBSD, so you should install the `databases/py-sqlite3` package from ports. I don't know much about FreeBSD's ports system, but after you install the py- sqlite3 package, your problem should hopefully be cleared up. I'm going to assume, from brief reading, you do something like this, assuming you have the ports tree on your system: cd /usr/ports/databases/py-sqlite3 make && make install
Why does python keep buffering stdout even when flushing and using -u? Question: $ cat script.py import sys for line in sys.stdin: sys.stdout.write(line) sys.stdout.flush() $ cat script.py - | python -u script.py The output is right but it only starts printing once I hit Ctrl-D whereas the following starts printing right away : $ cat script.py - | cat which led me to think that the buffering does not come from cat. I managed to get it working by doing : for line in iter(sys.stdin.readline, ""): as explained here : [Streaming pipes in Python](http://stackoverflow.com/questions/4187785/streaming-pipes-in-python), but I don't understand why the former solution doesn't work as expected. Answer: Python manpage reveals the answer to your question: -u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xreadlines(), readlines() and file-object iterators ("for line in sys.stdin") which is not influenced by this option. To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop. That is: file-object iterators' internal buffering is to blame (and it doesn't go away with -u).
How to only print certain text using BeautifulSoup Question: I am trying to pull some financial data for city governments using BeautifulSoup (had to convert the files from pdf). I just want to get the data as a csv file and then I'll analyze it in Excel or SAS. My problem is that I do not want to print the "& nbsp;" that is in the original HTML, just the numbers and the row heading. Any suggestions on how I can do this without using regex? Below is a sample of the html I am looking at. Next is my code (currently just in proof of concept mode, need to prove I can get clean data before moving on). New to Python and programming so any help is appreciated. <TD class="td1629">Investments (Note 2)</TD> <TD class="td1605">&nbsp;</TD> <TD class="td479">&nbsp;</TD> <TD class="td1639">-</TD> <TD class="td386">&nbsp;</TD> <TD class="td116">&nbsp;</TD> <TD class="td1634">2,207,592</TD> <TD class="td479">&nbsp;</TD> <TD class="td1605">&nbsp;</TD> <TD class="td1580">2,207,592</TD> <TD class="td301">&nbsp;</TD> <TD class="td388">&nbsp;</TD> <TD class="td1637">2,882,018</TD> CODE import htmllib import urllib import urllib2 import re from BeautifulSoup import BeautifulSoup CAFR = open("C:/Users/snown/Documents/CAFR2004 BFS Statement of Net Assets.html", "r") soup = BeautifulSoup(CAFR) assets_table = soup.find(True, id="page_27").find(True, id="id_1").find('table') rows = assets_table.findAll('tr') for tr in rows: cols = tr.findAll('td') for td in cols: text = ''.join(td.find(text=True)) print text+"|", print Answer: soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES) It converts `&nbsp;` and other html entities to appropriate characters. To write it to a csv file: >>> import csv >>> import sys >>> csv_file = sys.stdout >>> writer = csv.writer(csv_file, delimiter="|") >>> soup = BeautifulSoup("<tr><td>1<td>&nbsp;<td>3", ... convertEntities=BeautifulSoup.HTML_ENTITIES) >>> writer.writerows([''.join(t.encode('utf-8') for t in td(text=True)) ... for td in tr('td')] for tr in soup('tr')) 1| |3 I've used `t.encode('utf-8')` due to `&nbsp;` is translated to non-ascii `U+00A0` (no-break space) character.
Why I already installed pywin32 lib, but still got "ImportError: No module named win32com.client" Question: I already installed the "Python for Windows extensions" library from here: <http://sourceforge.net/projects/pywin32/files/pywin32/> but when I import the "win32com.client" in my program, I still got the error message of "ImportError: No module named win32com.client"?? My Python version is 3.2. Thx in advance :-) Answer: I faced the same problem while using Visual Studio. The following fixed the issue: 1\. Right Click Project Properties (in the Solution Explorer window) 2\. Select Properties 3\. In the General Tab set the appropriate Interpreter (Python2.7 in this case) ![enter image description here](http://i.stack.imgur.com/fJATy.jpg)
How to make an if loop of a file existence, in python? Question: I'm trying to run a series of commands for two input files, but I want to avoid doing the same thing if it has already been done. To make it more clear, these are my commands: from subprocess import call import os.path pathway = raw_input("Please give the pathway of your Genome Folder ( .fa files): ") genome= raw_input("Please type your genome name (e.g. chick_build2.1):" ) #Building a genome (.stidx for stampy) cmd = "python /space/tierzucht/mgholami/stampy-1.0.13/stampy.py -G %s %s/*.fa" %(genome, pathway) #Building a genome (.fa for BWA) cmd = "cat %s/*.fa > %s.fa" %(pathway, genome) #Building an index (for BWA) cmd = "bwa index %s.fa " %(genome) call(cmd, shell=True) and what I want to do is to add an if loop before each command that if the file already exists do not run this command. I tried this but it doesn't work: if os.path.isfile("%s.stidx") %genome == False: cmd = "python /space/tierzucht/mgholami/stampy-1.0.13/stampy.py -G %s %s/*.fa" %(genome, pathway) what I'm trying to do is to check if the **stidx** format of the chosen file name already exists! And I want to do it with **fa** format and several others too. Answer: Try: if not os.path.isfile("%s.stidx"%genome): cmd = "python /space/tierzucht/mgholami/stampy-1.0.13/stampy.py -G %s %s/*.fa" %(genome, pathway) In your original code, the paretheses were misplaced (the `%` was getting interpreted as the remainder operator, so the interpreter did not complain about a syntax error).
how to remove an element in lxml Question: I need to completely remove elements, based on the contents of an attribute, using python's lxml. Example: import lxml.etree as et xml=""" <groceries> <fruit state="rotten">apple</fruit> <fruit state="fresh">pear</fruit> <fruit state="fresh">starfruit</fruit> <fruit state="rotten">mango</fruit> <fruit state="fresh">peach</fruit> </groceries> """ tree=et.fromstring(xml) for bad in tree.xpath("//fruit[@state=\'rotten\']"): #remove this element from the tree print et.tostring(tree, pretty_print=True) I would like this to print: <groceries> <fruit state="fresh">pear</fruit> <fruit state="fresh">starfruit</fruit> <fruit state="fresh">peach</fruit> </groceries> Is there a way to do this without storing a temporary variable and printing to it manually, as: newxml="<groceries>\n" for elt in tree.xpath('//fruit[@state=\'fresh\']'): newxml+=et.tostring(elt) newxml+="</groceries>" Answer: Use the [`remove`](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.remove) method of an xmlElement : tree=et.fromstring(xml) for bad in tree.xpath("//fruit[@state=\'rotten\']"): bad.getparent().remove(bad) # here I grab the parent of the element to call the remove directly on it print et.tostring(tree, pretty_print=True, xml_declaration=True) If I had to compare with the @Acorn version, mine will work even if the elements to remove are not directly under the root node of your xml.
What would be the most efficient/clean way to deeply sort a multidimensional list in Python? Question: Example: From this list: list = [[10, 9, 1], [2, 1, 1,], [4, 11, 16]] I'd like to have: print list [[1, 1, 1], [2, 4, 9], [10, 11, 16]] Is it possible with the _list.sort()_ function or do I have to write a custom loop ? Answer: Here's an example of flattening, sorting, then rebuilding the nested lists, as @Inerdia suggested in the comments above. I've tried to use generators and iterators where possible, but I'm sure there are cleverer, more efficient ways of getting the result! from itertools import izip l = [[10, 9, 1], [2, 1, 1,], [4, 11, 16]] # flatten the list and sort it f = sorted(inner for outer in l for inner in outer) # group it into 3s again using izip new_list = [list(l) for l in izip(*[iter(f)]*3)]
Can I find the path to the python executable from inside python? Question: > **Possible Duplicate:** > [How to get current python interpreter path from inside a Python > script?](http://stackoverflow.com/questions/5927633/how-to-get-current- > python-interpreter-path-from-inside-a-python-script) The title pretty much says it. I'd like to know which python executable is being used from inside python. Something like Python 2.7.2 (default, Nov 1 2011, 03:31:17) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print <insert the code I'm after here> /usr/local/bin/python2.7 >>> Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print <insert the code I'm after here> /usr/bin/python2.6 >>> You get the picture Thanks Answer: You can do this: >>> import sys >>> print sys.executable /usr/bin/python as described here: [How to get the python.exe location programmatically?](http://stackoverflow.com/questions/749711/how-to-get-the- python-exe-location-programmatically)
Running Scrapy tasks in Python Question: My Scrapy script seems to work just fine when I run it in 'one off' scenarios from the command line, but if I try running the code twice in the same python session I get this error: "ReactorNotRestartable" Why? The offending code (last line throws the error): crawler = CrawlerProcess(settings) crawler.install() crawler.configure() # schedule spider #crawler.crawl(MySpider()) spider = MySpider() crawler.queue.append_spider(spider) # start engine scrapy/twisted crawler.start() Answer: Close to Joël's answer, but I want to elaborate a bit more than is possible in the comments. If you look at the [Crawler source code](http://dev.scrapy.org/browser/scrapy/crawler.py), you see that the `CrawlerProcess` class has a `start`, but also a `stop` function. This `stop` function takes care of cleaning up the internals of the crawling so that the system ends up in a state from which it can start again. So, if you want to restart the crawling without leaving your process, call `crawler.stop()` at the appropriate time. Later on, simply call `crawler.start()` again to resume operations. **Edit:** in retrospect, this is not possible (due to the Twisted reactor, as mentioned in a different answer); the `stop` just takes care of a clean termination. Looking back at my code, I happened to have a wrapper for the Crawler processes. Below you can find some (redacted) code to make it work using Python's multiprocessing module. In this way you can more easily restart crawlers. (Note: I found the code online last month, but I didn't include the source... so if someone knows where it came from, I'll update the credits for the source.) from scrapy import project, signals from scrapy.conf import settings from scrapy.crawler import CrawlerProcess from scrapy.xlib.pydispatch import dispatcher from multiprocessing.queues import Queue from multiprocessing import Process class CrawlerWorker(Process): def __init__(self, spider, results): Process.__init__(self) self.results = results self.crawler = CrawlerProcess(settings) if not hasattr(project, 'crawler'): self.crawler.install() self.crawler.configure() self.items = [] self.spider = spider dispatcher.connect(self._item_passed, signals.item_passed) def _item_passed(self, item): self.items.append(item) def run(self): self.crawler.crawl(self.spider) self.crawler.start() self.crawler.stop() self.results.put(self.items) # The part below can be called as often as you want results = Queue() crawler = CrawlerWorker(MySpider(myArgs), results) crawler.start() for item in results.get(): pass # Do something with item
Numpy Cimport error using cython Question: I am trying to Cimport Numpy into a Python 2.7 shell from a `.pyx` file, but it keeps giving me the same error: I made a `.pyx` file called `numpyx` just to see if it was part of the bigger code I was running, the file contains: cimport numpy as np a = np.arange(0,10) print 'a= ',a I get the following error every time: Traceback (most recent call last): File "<pyshell#82>", line 1, in <module> import numpyx File "C:\Users\Scott\AppData\Roaming\Python\Python27\site-packages\pyximport \pyximport.py", line 335, in load_module self.pyxbuild_dir) File "C:\Users\Scott\AppData\Roaming\Python\Python27\site-packages\pyximport\pyximport.py", line 183, in load_module so_path = build_module(name, pyxfilename, pyxbuild_dir) File "C:\Users\Scott\AppData\Roaming\Python\Python27\site-packages\pyximport\pyximport.py", line 167, in build_module reload_support=pyxargs.reload_support) File "C:\Users\Scott\AppData\Roaming\Python\Python27\site-packages\pyximport\pyxbuild.py", line 85, in pyx_to_dll dist.run_commands() File "C:\Python27\lib\distutils\dist.py", line 953, in run_commands self.run_command(cmd) File "C:\Python27\lib\distutils\dist.py", line 972, in run_command cmd_obj.run() File "C:\Users\Scott\AppData\Roaming\Python\Python27\site-packages\Cython\Distutils\build_ext.py", line 135, in run _ build_ext.build_ext.run(self) File "C:\Python27\lib\distutils\command\build_ext.py", line 340, in run self.build_extensions() File "C:\Users\Scott\AppData\Roaming\Python\Python27\site-packages\Cython\Distutils\build_ext.py", line 143, in build_extensions self.build_extension(ext) File "C:\Python27\lib\distutils\command\build_ext.py", line 499, in build_extension depends=ext.depends) File "C:\Python27\lib\distutils\ccompiler.py", line 624, in compile self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) File "C:\Python27\lib\distutils\cygwinccompiler.py", line 166, in _compile raise CompileError, msg ImportError: Building module failed: ["CompileError: command 'gcc' failed with exit status 1\n"] I don't understand why it won't work, since it compiles `.pyx` files fine as long as `cimport` isn't in them. If anyone could shed some light on this it would be great! Answer: Well the function your looking for is available in the python package. (I find no reference to linspace in numpy.pxd) I usually do something along these lines: import numpy as np cimport numpy as cnp def foo(double x): cdef cnp.ndarray[cnp.float64_t, ndim=1] y = np.linspace(0, 10, 11) # do whatever return y
What is the best way to sort list with custom sorting parameters in Python? Question: I have a series of lists that looks like this: li1 = ['a.1', 'b.9', 'c.8', 'd.1', 'e.2'] li2 = ['a.4', 'b.1', 'c.2', 'd.2', 'e.4'] How can I rearrange the items in each list so that the first item is 'b.something'? For the example above: li1 = ['b.9', 'a.1', 'c.8', 'd.1', 'e.2'] li2 = ['b.1', 'a.4', 'c.2', 'd.2', 'e.4'] Maintaining the order after the first item isn't important. Thanks for the help. Answer: Python's sorting is stable, so you will maintain the order after the first item regardless. li1.sort(key=lambda x: not x.startswith('b.'))
Jython random module produces different results to cpython Question: I'm generating some test data using a known random seed. I want to use this data from cpython and from jython. I've found that the data is different if I use jython (2.5.2) vs cpython. Boiling it down to a simple test, I can see that the PRNG is giving different results in the two implementations: In Jython: Jython 2.5.2 (Release_2_5_2:7206, Mar 2 2011, 23:12:06) [Java HotSpot(TM) Server VM (Sun Microsystems Inc.)] on java1.6.0_26 Type "help", "copyright", "credits" or "license" for more information. >>> import random >>> random.seed(1) >>> random.random() 0.7308781974052877 In CPython: Python 2.7.2+ (default, Oct 4 2011, 20:03:08) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import random >>> random.seed(1) >>> random.random() 0.13436424411240122 The test data I'm generating is reproducible within each python implementation. Is there a way around this? Maybe I need to code my own PRNG? Answer: There is a way around this. Both implementations include the pure-python "WichmannHill" PRNG. It's slower but it gives the same results in both Jython and CPython. In my code I replaced random.seed(1) uuid += random.choice(hexdigits) with rand = random.WichmannHill(1) uuid += rand.choice(hexdigits)
How to add data to mongoDB in python Question: I am a python noob (working with it for less than a few hours). I'm trying to read in twitter data and store it in a mongo database, but I am getting the following error: Traceback (most recent call last): File "twit_test.py", line 8, in on_receive db.posts.insert(data) File "/Library/Python/2.6/site-packages/pymongo-2.0.1-py2.6-macosx-10.6-universal.egg/pymongo/collection.py", line 274, in insert File "/Library/Python/2.6/site-packages/pymongo-2.0.1-py2.6-macosx-10.6-universal.egg/pymongo/database.py", line 249, in _fix_incoming File "/Library/Python/2.6/site-packages/pymongo-2.0.1-py2.6-macosx-10.6-universal.egg/pymongo/son_manipulator.py", line 73, in transform_incoming TypeError: 'str' object does not support item assignment Traceback (most recent call last): File "twit_test.py", line 17, in <module> conn.perform() My code is very simple: import pycurl, json import pymongo STREAM_URL = "https://stream.twitter.com/1/statuses/sample.json" USER = "XXXXXXXX" PASS = "XXXXXXXX" def on_tweet(data): tweet = json.loads(data) db.posts.insert(tweet) from pymongo import Connection connection = Connection() db = connection.test conn = pycurl.Curl() conn.setopt(pycurl.USERPWD, "%s:%s" % (USER, PASS)) conn.setopt(pycurl.URL, STREAM_URL) conn.setopt(pycurl.WRITEFUNCTION, on_tweet) conn.perform() I'm sure this is a VERY simple fix, hope you guys can help. Thanks! Answer: PyMongo's `insert` method takes a dictionary, not a string. The error you're seeing is where PyMongo attempts to assign an `ObjectId` for the new record (since it doesn't yet have one) before sending to the database. I think the error is in your `on_receive` function. Unless pycurl is converting the JSON for you automatically, it's very likely just giving you a raw string result from twitter's API. You should use the json module to decode the string, then handle the resulting type appropriately -- that is, if it's an array, iterate each item, determine whether it needs to be saved (i.e. whether you already have it in your database), and if not, then issue `insert` just on those elements which are new. **EDIT:** You should also add the `safe=True` keyword argument to `insert`. If there is an error that is caught on the server side, you will then get an exception from PyMongo which will help diagnose the problem.
Opening a java JAR file from python Question: I am trying to open a JAR file from python and running into problems. I am using.. import os os.system(r"X:\file.jar") it appears to open the window then it shuts right away, I know I am missing a simple command but not sure what it is, thanks for the help Answer: Do you want to execute code from .jar, or open it? If open, then `.jar` file is the same format as `.zip` files and you can use `zipfile` module to manipulate it. Example: def show_jar_classes(jar_file): """prints out .class files from jar_file""" zf = zipfile.ZipFile(jar_file, 'r') try: lst = zf.infolist() for zi in lst: fn = zi.filename if fn.endswith('.class'): print(fn) finally: zf.close() If you want to execute it then I prefer creating simple batch/shell script which execute `java` with some parameters like `-Xmx` and with environment settings required by application.
python regex re.compile() match string Question: Gents, I am trying to grab the version number from a string via python regex... Given filename: facter-1.6.2.tar.gz When, inside the loop: import re version = re.split('(.*\d\.\d\.\d)',sfile) print version How do i get the 1.6.2 bit into version Thanks! Answer: match = re.search(r'\d\.\d\.\d', sfile) if match: version = match.group()
Python check for valid email address? Question: Is there a good way to check a form input using regex to make sure it is a proper style email address? Been searching since last night and everybody that has answered peoples questions regarding this topic also seems to have problems with it if it is a subdomained email address. Answer: There is no point. Even if you can verify that the email address is syntactically valid, you'll still need to check that it was not mistyped, and that it actually goes to the person you think it does. The only way to do that is to send them an email and have them click a link to verify. Therefore, a most basic check (e.g. that they didn't accidentally entered their street address) is usually enough. Something like: it has exactly one `@` sign, and at least one `.` in the part after the `@`: [^@]+@[^@]+\.[^@]+ You'd probably also want to disallow whitespace -- there are probably valid email addresses with whitespace in them, but I've never seen one, so the odds of this being a user error are on your side. If you want the full check, have a look at [this question](http://stackoverflow.com/questions/201323/using-a-regular- expression-to-validate-an-email-address). * * * Update: Here's how you could use any such regex: import re if not re.match(r"... regex here ...", email): # whatever Note the `r` in front of the string; this way, you won't need to escape things twice. If you have a large number of regexes to check, it might be faster to compile the regex first: import re EMAIL_REGEX = re.compile(r"... regex here ...") if not EMAIL_REGEX.match(email): # whatever
Subprocess completes but still doesn't terminate, causing deadlock Question: Ok, since there are currently no answer's I don't feel too bad doing this. While I'm still interested in what is actually happening behind the scenes to cause this problem, my most urgent questions are those specified in update 2. Those being, What are the differences between a `JoinableQueue` and a `Manager().Queue()` (and when should you use one over the other?). And importantly, is it safe to replace one for the other, in this example? * * * In the following code, I have a simple process pool. Each process is passed the process queue (`pq`) to pull data to be processed from, and a return-value queue (`rq`) to pass the returned values of the processing back to the main thread. If I don't append to the return-value queue it works, but as soon as I do, for some reason the processes are blocked from stopping. In both cases the processes `run` methods return, so it's not `put` on the return-queue blocking, but in the second case the processes themselves do not terminate, so the program deadlocks when I `join` on the processes. Why would this be? **Updates:** 1. **It seems to have something to with the number of items in the queue.** On my machine at least, I can have up to 6570 items in the queue and it actually works, but any more than this and it deadlocks. 2. **It seems to work with`Manager().Queue()`.** Whether it's a limitation of `JoinableQueue` or just me misunderstanding the differences between the two objects, I've found that if I replace the return queue with a `Manager().Queue()`, it works as expected. What are the differences between them, and when should you use one over the other? 3. **The error does not occur if I'm consuming from`rq`** Oop. There was an answer here for a moment, and as I was commenting on it, it disappeared. Anyway one of the things it said was questioning whether, if I add a consumer this error still occurs. I have tried this, and the answer is, no it doesn't. The other thing it mentioned was this quote from [the multiprocessing docs](http://docs.python.org/py3k/library/multiprocessing.html#pipes-and- queues) as a possible key to the problem. Referring to `JoinableQueue`'s, it says: > ... the semaphore used to count the number of unfinished tasks may > eventually overflow raising an exception. * * * import multiprocessing class _ProcSTOP: pass class Proc(multiprocessing.Process): def __init__(self, pq, rq): self._pq = pq self._rq = rq super().__init__() print('++', self.name) def run(self): dat = self._pq.get() while not dat is _ProcSTOP: # self._rq.put(dat) # uncomment me for deadlock self._pq.task_done() dat = self._pq.get() self._pq.task_done() print('==', self.name) def __del__(self): print('--', self.name) if __name__ == '__main__': pq = multiprocessing.JoinableQueue() rq = multiprocessing.JoinableQueue() pool = [] for i in range(4): p = Proc(pq, rq) p.start() pool.append(p) for i in range(10000): pq.put(i) pq.join() for i in range(4): pq.put(_ProcSTOP) pq.join() while len(pool) > 0: print('??', pool) pool.pop().join() # hangs here (if using rq) print('** complete') * * * Sample output, not using return-queue: ++ Proc-1 ++ Proc-2 ++ Proc-3 ++ Proc-4 == Proc-4 == Proc-3 == Proc-1 ?? [<Proc(Proc-1, started)>, <Proc(Proc-2, started)>, <Proc(Proc-3, started)>, <Proc(Proc-4, started)>] == Proc-2 ?? [<Proc(Proc-1, stopped)>, <Proc(Proc-2, started)>, <Proc(Proc-3, stopped)>] -- Proc-3 ?? [<Proc(Proc-1, stopped)>, <Proc(Proc-2, started)>] -- Proc-2 ?? [<Proc(Proc-1, stopped)>] -- Proc-1 ** complete -- Proc-4 * * * Sample output, using return queue: ++ Proc-1 ++ Proc-2 ++ Proc-3 ++ Proc-4 == Proc-2 == Proc-4 == Proc-1 ?? [<Proc(Proc-1, started)>, <Proc(Proc-2, started)>, <Proc(Proc-3, started)>, <Proc(Proc-4, started)>] == Proc-3 # here it hangs Answer: From the [documentation](http://docs.python.org/library/multiprocessing.html#pipes-and- queues): > Warning > > As mentioned above, if a child process has put items on a queue (and it has > not used JoinableQueue.cancel_join_thread()), then that process will not > terminate until all buffered items have been flushed to the pipe. > > This means that if you try joining that process you may get a deadlock > unless you are sure that all items which have been put on the queue have > been consumed. Similarly, if the child process is non-daemonic then the > parent process may hang on exit when it tries to join all its non-daemonic > children. > > Note that a queue created using a manager does not have this issue. See > Programming guidelines. So the JoinableQueue() uses a pipe and will wait until it can flush all data before closing. On the other hand a Manager.Queue() object uses a completely different approach. Managers are running a separate process that receive all data immediately (and store it in its memory). > Managers provide a way to create data which can be shared between different > processes. A manager object controls a server process which manages shared > objects. Other processes can access the shared objects by using proxies. > > ... > > Queue([maxsize]) Create a shared Queue.Queue object and return a proxy for > it.
Cannot create Python Object in .NET with IronPython Question: Newly I started working with IronPython in .NET but as I saw some few examples they're making engine with `Python.CreateEngine()` But the `Python` object isn't loaded for me however I imported these references. using IronPython.Hosting; using IronPython.Runtime; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; I searched around this topic but I couldn't find anything. Peace Out! Answer: Bit of a tangent, but by far the quickest way of getting going with IronPython is to download a copy of [SharpDevelop](http://www.icsharpcode.net/opensource/sd/) and use a project template to start you off. You'll sidestep a lot of these initial environment issues.
FFT filter vs lfilter in python Question: I have some troubles when applying bandpass filter to signal in Python. Have tried the following to things: * Do the box window "by hand", i.e. do the FFT on the signal, apply the filter with a box window and the do the IFFT to get back to the time domain. * Use the scipy.signal module where I use firwin2 to construct the filter and then lfilter to to the filtering. Futhermore I have done the same filtering in the audio program Cool Edit and compared the result from the above two tests. As can be seen (I am a new user so I can not post my png fig), the results from the FFT and scipy.signal are very different. When compare to the result from Cool edit, the FFT is close, however not identical. Code as below: # imports from pylab import * import os import scipy.signal as signal # load data tr=loadtxt('tr6516.txt',skiprows=1) sr = 500 # [samples/s] nf = sr/2.0 # Nyquist frequence W = 512 # Window widht for filtering N=float(8192) # Fourier settings Ns = len(tr[:,0]) # Total number of samples # Create inpulse responce from the filter fv=12.25 w =0.5 r =0.5*w Hz=[0, fv-w-r, fv-w, fv+w, fv+w+r, nf] ff=[0, 0, 1, 1, 0, 0] b = signal.firwin2(W,Hz,ff,nfreqs=N+1,nyq=nf) SigFilter = signal.lfilter(b, 1, tr[:,1]) # Fourier transform X1 = fft(tr[:,1],n=int(N)) X1 = fftshift(X1) F1 = arange(-N/2.0,N/2.0)/N*sr # Filter data ff=[0,1,1,0] fv=12.25 w =0.5 r =0.5*w Hz=[fv-w-r,fv-w,fv+w,fv+w+r] k1=interp(-F1,Hz,ff)+interp(F1,Hz,ff) X1_f=X1*k1 X1_f=ifftshift(X1_f) x1_f=ifft(X1_f,n=int(N)) Can anyone explain to me why this difference? The filtering in Cool edit has been done using the same settings as in scipy.signal (hanning window, window width 512). Or have I got this all totaly wrong. Best regards, Anders Above code: ![enter image description here](http://i.stack.imgur.com/afeDZ.png) Compared with Cool Edit: ![enter image description here](http://i.stack.imgur.com/943hz.png) ![enter image description here](http://i.stack.imgur.com/sWdYd.png) Answer: Small differences can be explained by the libraries using different algorithms that accumulate error slightly differently. For example, if you compute the DFT using a radix-2 FFT, a split-radix FFT and an ordinary DFT, the results will all be slightly different. In fact the ordinary DFT has worse accuracy than all decent implementations of an FFT because it uses many more floating point operations, and thus it accumulates more error. Could this explain the close (but not identical) results you are seeing?
python- construction of lattice which traps molecules - doesn't work right Question: I have this problem : > Create a program which constructs a lattice of one (1) dimension and 100000 > sites. In this lattice put at random positions a number of trap molecules, > which will have concentration c. Put 1 particle in a random position on the > lattice and let it perform a random walk. In this walk you will not place a > time restriction, namely you will not declare a specific number of steps. > The walk will stop when the particle falls on a > trap.............................. ...Beware of boundary conditions. When > the particle reaches the borders of the lattice it shouldn’t be allowed to > escape from it but to remain in the lattice, either by returning on it > former position or by being placed in the opposite site of the > lattice........ My approach is shown in the code i created (i have comments in it). def steps1d(self,pos,c): #pos: number of positions #c: concentration of trap-particles # array full of traps (zeros) myzeros = sc.zeros(self.c*self.pos) # grid full of available positions(ones) grid = sc.ones(self.pos) # distribute c*pos zeros(traps) in random positions (number of positions is pos) traps = sc.random.permutation(pos)[:c*pos] # the grid in which the particle is moving which has traps inside it grid[traps] = myzeros steps_count = [] # list which holds the number of steps free = 0 for i in range(pos): # the step of the particle can be 0 or 1 step=sc.random.random_integers(0,1) for step in grid[:]: if step == 1: free += 1 steps_count.append(free) else: break return steps_count I have 3 problems : 1) The results i am taking for example for pos=10 are sth like: > [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, > 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35...] I would expect 10 numbers each for 1 run (variable pos). 2) I am not sure how to handle the boundary conditions. I am thinking something like: if free > grid.size: free = free - 1 But I can't test it. Also,i am not sure if this applies for both borders of the grid. 3) If i want the first step to begin from the middle of the grid, how can I do it? If someone has a hint on that, I'll be grateful. Answer: On a smaller lattice, to see what is happening: import numpy # Populate the lattice lattice = numpy.concatenate([numpy.ones(90), numpy.zeros(10)]) numpy.random.shuffle(lattice) # Intialize problem in_trap = False steps = 0 pos = int(numpy.random.randint(0,len(lattice),1)) history = [] while in_trap == False: # Step of -1 is backward, 1 is forward step = numpy.random.permutation([-1,1])[0] # Check position for edges and fix if required if pos + step > len(lattice) - 1: pos = 0 elif pos + step < 0: pos = len(lattice) - 1 else: pos += step # Keep track of random walk history.append(pos) # Check if it's a trap if lattice[pos] == 0: in_trap = True # If not, continue steps += 1 print steps print history print lattice I would encourage you to thrown in print statements throughout to see what values each variable is holding. Trying it out on smaller lattices will help you understand how this works. EDIT: I'm going to let you figure out the specifics, but I would wrap this in a function like follows. It sets up the function, then prepares empty steps and histories lists to hold the results of each run. We run the function, then append the results to those lists. def lattice(): code return steps, history steps = [] histories = [] for i in range(0,10): num_steps, history = lattice() steps.append(num_steps) histories.append(history)
Compute the average of the same index in the list, python Question: I have a list as follows: A= [('1', 3), ('2', 7), ('3', 5), ('1', 7), ('2', 5), ('3', 1)] From the list `A`, I would like to generate the output list like this: Average = [('1', 5), ('2', 6), ('3', 2)] Any tips would be really grateful! =) Answer: from collections import defaultdict a = [('1', 3), ('2', 7), ('3', 5), ('1', 7), ('2', 5), ('3', 1)] d = defaultdict(list) for k, v in a: d[k].append(v) avg = [(k, sum(v) // len(v)) for k, v in d.iteritems()] print avg prints [('1', 5), ('3', 3), ('2', 6)] Note that this uses integer division to compute the averages. You might want to use floating point division instead.
SWIG interfacing C library to Python (SWIG generated classes are cumbersome to use) Question: I am using SWIG to generate Python language bindings to my C library. I have managed to build the bindings and exported data structures, but I'm having to jump through some hoops when using the library. For example the C header has data types and function prototypes as follows: struct MyStruct { /* fields */ } struct MyStruct * MYSTRUCT_Alloc(void); void MYSTRUCT_Free(struct MyStruct *); struct MyStruct * MYSTRUCT_Clone(const struct MyStruct *); int MYSTRUCT_Func1(const struct MyStruct *, const int); /* and so on */ In my SWIG interface file, I am exporting both the functions and the MyStruct data type. Assuming my python extension module is called foobar, I can then write Python script like this: #import foobar as fb # The line below creates a Python class which is a wrapper to MyStruct. HOWEVER I cannot pass this class to a function like MYSTRUCT_Func1 until I have initialized it by calling MYSTRUCT_Alloc ... ms = fb.MyStruct # This will fail (throws a Python exception) # ret = fb.MYSTRUCT_Func1(ms, 123) # However this works ms = fb.MYSTRUCT_Alloc() ret = fb.MYSTRUCT_Func1(ms, 123) It is very cumbersome (and error prone) to declare an object and then assign a pointer to it before using it. Is there a better way of using the SWIG generated classes?. I was thinking of wrapping higher level classes (or subclassing the SWIG generated classes) to automagically take care of object creation and destruction (as well as providing some OBVIOUS member functions like MYSTRUCT_Func1(). HOWEVER, if I do wrap/subclass the SWIG generated classes, then I am not sure that I can pass the new classes to the C API functions that expect a pointer to a C struct. I can't modify the SWIG generated classes directly (or atleast I shouldn't) - for OBVIOUS reasons. What is the best way to solve this problem? A more pythonic way of creating/destroying objects, whilst at the same time being able to pass pointers directly to the exposed C functions? Answer: Writing a wrapper on the Python side seems like a good idea to me, not sure why you think that is not going to work. class MyStructWrapper: def __init__(self): self.ms = fb.MYSTRUCT_Alloc() def __del__(self): fb.MYSTRUCT_Free(self.ms) def func1(self, arg): return fb.MYSTRUCT_Func1(self.ms, arg) And if you need to access the members of the struct, then you can do so with `self.ms.member` or by writing getters and setters. You can also fit your `clone` function into this design. **Edit** : Regarding your comment, let's say you have a global function that takes a pointer to `MyStruct`: int gFunc(MyStruct* ms); In the Python side, you can write a wrapper as follows: def gFuncWrapper(mystruct): return fb.gFunc(mystruct.ms) I hope this helps.
Alternatives to php for in-line web programming? Question: I first learned web programming with php a while back. It has some features that I find very helpful, but the overall language is not something I enjoy, just as a matter of personal preference. I am wondering what alternatives I could use to provide similar functionality using a different underlying programming language (Python? Ruby?). What I am looking for: * general purpose programming capability * in-line server-side code embedded in HTML (i.e. I want to be able to make my documents pure HTML if desired, rather than demanding special syntax even where I don't want dynamic content) * access to request parameters * ability to send headers, set cookies, etc Preferably: * does not require a separate server process * easy to connect with Apache Does anyone have any suggestions? One thing I tried to do was embedded Ruby (erb) through CGI. This looked like a good fit on paper. Unfortunately, I was not able to get it to work, because I was following a few different guides and the result of combining them did not work out. At any rate, it seems this would not allow me to set arbitrary headers (and more importantly, use sessions and cookies). Note: I'm not looking for a full web framework at the moment. Just relatively small amounts of dynamic content among otherwise HTML pages. Thanks! Answer: You've hit on the big reason why PHP is so popular - it has all of those pieces in a server-embeddable package. There aren't really many solutions with its ease of deployment; PHP is written specifically for what you want, which is both its strength and weakness. It's why it's such a weak general-purpose language, and why everyone and their dog knows it. It's everywhere, and the barrier to entry is near zero. PHP is a language plus templating plus a web framework all baked into one package. To get an equivalent, you're going to need a web framework, even if it's a small one. Something like [Sinatra](http://www.sinatrarb.com/) is a super lightweight way to do similar in Ruby, though it requires a separate server process. You could look at something like Perl with cgi.pm, but it may be a step in the wrong direction if you're wanting something cleaner than PHP. I don't know Python packages well enough to offer suggestions there, but Twisted makes it easy to bind a Python program to a web interface. That does end up running in its own server process, though. You'll need to do a little more work than your standard PHP deploy if you want to use something besides PHP, but that's often a choice that people consider to be a reasonable tradeoff for gains in productivity.
Yaml file addressing in GAE using Python Question: Here is the file structure : --src -----\app.yaml -----\bl -----\bl\calc.html -----\calc.py -----\Main.py I want to get to this address "localhost/bl/calc.html" and here is my yaml file: - url: /bl static_dir: bl - url: /bl/.* script: calc.py - url: /.* script: Main.py In the Main.py I have this : from calc import Calc application = webapp.WSGIApplication([ ('/', MainPage), ('/bl/calc', Calc) ], debug=True) But I got just "This webpage is not found" for both <http://localhost/bl/calc> and <http://localhost/bl/calc.html> I got really confused With this YAML file and GAE I Dont know how to fix it. Should I have same application config in Calc file ? Answer: Directives in app.yaml are evaluated in order, top to bottom. Because you have a `static_dir` directive for `/bl/` before the script handlers for `/bl/` and `.*`, any requests for that path will be satisfied by the static directory, not the script. Decide which you want - static or script - and add only that to app.yaml.
Web-scraping JavaScript page with Python Question: I'm trying to develop a simple web scraper. I want to extract text without the HTML code. In fact, I achieve this goal, but I have seen that in some pages where JavaScript is loaded I didn't obtain good results. For example, if some JavaScript code adds some text, I can't see it, because when I call response = urllib2.urlopen(request) I get the original text without the added one (because JavaScript is executed in the client). So, I'm looking for some ideas to solve this problem. Answer: You can also use Python library [dryscrape](https://github.com/niklasb/dryscrape) to scrape javascript driven websites. # Example To give an example, I created a sample page with following HTML code. ([link](http://avi.im/stuff/js-or-no-js.html)): <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Javascript scraping test</title> </head> <body> <p id='intro-text'>No javascript support</p> <script> document.getElementById('intro-text').innerHTML = 'Yay! Supports javascript'; </script> </body> </html> without javascript it says: `No javascript support` and with javascript: `Yay! Supports javascript` # Scraping without JS support: >>> import requests >>> from bs4 import BeautifulSoup >>> response = requests.get(my_url) >>> soup = BeautifulSoup(response.text) >>> soup.find(id="intro-text") <p id="intro-text">No javascript support</p> # Scraping with JS support: >>> import dryscrape >>> from bs4 import BeautifulSoup >>> session = dryscrape.Session() >>> session.visit(my_url) >>> response = session.body() >>> soup = BeautifulSoup(response) >>> soup.find(id="intro-text") <p id="intro-text">Yay! Supports javascript</p>
How to log everything that occurs in a Python interactive shell session? Question: I'd like to have real-time access to both interpreter input and error and standard output. Preferably this information would be written to a file, so that I can poll the file for changes after every interpreter command has been entered. For example, given an interpreter session: >>> 5 * 7 35 >>> print("Hello, world!") Hello, world! >>> "Hello, world!" 'Hello, world!' I'd like to see the following in a log file: > 5 * 7 35 > print("Hello, world!") Hello, world! > "Hello, world!" 'Hello, world!' The formatting is not important; what is important is that I can search the file for key words to trigger interactive events during the session. What I have learned so far trying to accomplish this: Python's `code` module allows me to create an `InteractiveConsole` object, the `raw_input` method of which I can redefine to log to a file, like so: import code class LoggedConsole(code.InteractiveConsole): def __init__(self, locals): super(LoggedConsole, self).__init__(locals) self.file = open('consolelog.dat', 'a') def __del__(self): self.file.close() def raw_input(self, prompt=""): data = input(prompt) self.file.write(data+'\n') return data Furthermore, `InteractiveConsole` uses a built-in `write` method to log errors, which I can redefine to: def write(self, data): sys.stderr.write(data) self.file.write(data+'\n') I've also learned that the following snippet will log all stdout: class Tee(object): def __init__(self): self.file = open('consolelog.dat', 'a') self.stdout = sys.stdout def __del__(self): sys.stdout = self.stdout self.file.close() def write(self, data): self.file.write(data) self.stdout.write(data) sys.stdout = Tee() My (broken) attempt to bring this all together was to then create a `LoggedConsole` object, and pass it `Tee` in locals. console = LoggedConsole(locals={sys.stdout:LoggedExec()}) console.interact() (I've not passed locals before, so perhaps I'm doing it incorrectly here, but I don't receive an error.) Anyways, this will open a new Interactive Console, and will log (after closing) all input and errors, but not output. I've been banging my head against this for a while, and I feel like I'm close, but maybe not even. Also, is there a way for all of this to occur _during_ the session? Currently all logging takes place once the session is closed. Thanks for your time, sorry for the wall of text. edit: I'd like to be able to accomplish this in the standard Python interpreter for portability purposes. edit2: Jaime's snippet works very well for logging everything I need. Any way, though, that I can have it do so in real time, instead of waiting for the session to close? edit3: **Figured it out :). The final, working snippet:** import code import sys class Tee(object): def __init__(self, log_fname, mode='a'): self.log = open(log_fname, mode) def __del__(self): # Restore sin, so, se sys.stdout = sys.__stdout__ sys.stdir = sys.__stdin__ sys.stderr = sys.__stderr__ self.log.close() def write(self, data): self.log.write(data) self.log.flush() sys.__stdout__.write(data) sys.__stdout__.flush() def readline(self): s = sys.__stdin__.readline() sys.__stdin__.flush() self.log.write(s) self.log.flush() return s def flush(foo): return sys.stdout = sys.stderr = sys.stdin = Tee('consolelog.dat', 'w') console = code.InteractiveConsole() console.interact() Answer: I've only tested this in python2.7. I don't have 3 handy. import code import sys class Tee(object): def __init__(self, log_fname, mode='a'): self.log = open(log_fname, mode) def __del__(self): # Restore sin, so, se sys.stdout = sys.__stdout__ sys.stdir = sys.__stdin__ sys.stderr = sys.__stderr__ self.log.close() def write(self, data): self.log.write(data) sys.__stdout__.write(data) def readline(self): s = sys.__stdin__.readline() self.log.write(s) return s # Tie the ins and outs to Tee. sys.stdout = sys.stderr = sys.stdin = Tee('consolelog.dat', 'w') console = code.InteractiveConsole() console.interact()
Python lxml the E-Factory Question: I've been using the lxml "E-Factory" (aka. ElementMaker) for creating xml documents. I'm trying to generate an xml document similar to this: <url> <date-added>2011-11-11</date-added> </url> However, using the E-factory, I'm not sure how to specify the dash in the 'data-added' element. It seems to be interpreting the dash as a minus sign. Here is the docs I've been referring to: <http://lxml.de/tutorial.html#the-e- factory> Here is how to reproduce the error: from lxml import etree from lxml.builder import ElementMaker E = ElementMaker() URL = E.url DATE_ADDED = E.date-added xml = URL(DATE_ADDED(myobject.created.strftime('%Y-%m-%dT%H:%M:%S')),) NameError global name 'added' is not defined Does anyone know a trick to get it do properly render the element with a dash? Thank you for reading this. Joe Answer: The `ElementMaker` maps a function to a tag name (by using e.g. `E.date_added`) to build up the XML tree. However, there is a discrepancy between the allowed characters in HTML/XML tags and Python functions. As stated in [PEP 8](http://www.python.org/dev/peps/pep-0008/): _"Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability"_. So, the `date_added` function includes an underscore, which isn't allowed to be present in a Python function: >>> def foo-bar(): File "<stdin>", line 1 def foo-bar(): ^ SyntaxError: invalid syntax To resolve it, just create the `date-added` tag a bit more verbosely by supplying the name as an argument instead: >>> etree.tostring(E.url(E('date-added', '2011-11-11'))) '<url><date-added>2011-11-11</date-added></url>'
How to Perform a HTTP Post "directly" in Python Question: I do not know much about the difference between a HTTP Get and a HTTP Post so I am hoping to get some information from those more knowledgeable then me. I have written the following code: <form action="https://na.leagueoflegends.com/user/login" method="post"> <input name="name" type="text" value="MYACCOUNTLOGINUSERNAME"> <input name="pass" type="password" value="PASSWORD"> <input name="form_id" id="edit-user-login" value="user_login"> <input class="login_button" value="Submit" type="submit" style="width:100px"> </form> When I pass my actual username and password to the form and click the submit button I will be properly logged into the website. However, when I change method from POST to GET it returns the following: [https://na.leagueoflegends.com/user/login?name=MYACCOUNTLOGINUSERNAME&pass=PASSWORD&form_id=user_login](https://na.leagueoflegends.com/user/login?name=MYACCOUNTLOGINUSERNAME&pass=PASSWORD&form_id=user_login) and when I click this link it does not log me in. My question is, is it possible to do a "direct" POST via Python where I do not have to create a form but instead I can just open a URL that contains the proper parameters to log me in and POST them to the server? Thank you in advance for your knowledge, suggestions, and/or answers. Answer: The most sophisticated library to use for this purpose is probably [requests](http://docs.python-requests.org/en/latest/index.html) >>> import requests >>> response = requests.post(... your args here ...) Cf. the documentation of [requests.post](http://docs.python- requests.org/en/latest/api/#requests.post).
Python one class per module and packages Question: I'm trying to structure my app in Python. Coming back from C#/Java background, I like the approach of one class per file. I'd like my project tree to look like this: [Service] [Database] DbClass1.py DbClass2.py [Model] DbModel1.py DbModel2.py TheService.py [ServiceTests] [Database] DbClass1Tests.py DbClass2Tests.py [Model] DbModel1Tests.py DbModel2Tests.py TheServiceTests.py 1. Is the one class per file approach OK in Python? 2. Is it possible to create packages/modules in such a way so that packages work like Java's packages or .NET's namespaces, i.e. in DbModel1Tests.py: import Service.Model def test(): m = DbModel1() Answer: Q1. You can use the 1 class per file style in Python, but this is unusual. Q2. you'd have to use `from Service.Model import *` and do some stuff in `Service/Model/__init__.py` which is generally frowned upon. Avoid `import *` in Python My personal advice on this: Python is _not_ C#/Java. Trying to bend it to make it look like $other_language will cause frustration and poor user experience. Keep in mind that: * you can have other stuff than classes in Python modules (functions, for instance) * you don't have to import a class from a module unless you need to instantiate that class. Especially, if your code only uses instances of DbModel1 which are passed as arguments to your functions / methods, there is no need for the import in that part of the code * from `Service.Model.DbModel1 import DbModel1` looks bad. Prefer `from service.model import DbModel1` : avoid uppercase letters in file names and directory names, and group classes / functions logically in files (rather than grouping them in directories as you would do with the 1 class per file system.)
Python threading module import failure Question: I'm trying to import the threading module, however, i just seem to get errors for no good reason. Here is my code: import threading class TheThread ( threading.Thread ): def run ( self ): print 'Insert some thread stuff here.' print 'I\'ll be executed...yeah....' print 'There\'s not much to it.' TheThread.Start() And the errors: Traceback (most recent call last): File "threading.py", line 1, in <module> import threading File "C:\Users\Trent\Documents\Scripting\Python\Threading\threading.py", line 3, in <module> class TheThread ( threading.Thread ): AttributeError: 'module' object has no attribute 'Thread' Press any key to continue . . . Python stats: > Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on > win 32 Answer: i think that all you need is just to rename the name of your working file, because your file name is the same as module name: > threading.py or you have wrong threading.py file in your working directory
Context manager for Python's MySQLdb Question: I am used to (spoiled by?) python's [SQLite](http://docs.python.org/library/sqlite3.html) interface to deal with SQL databases. One nice feature in python's SQLite's API the "context manager," i.e., python's `with` statement. I usually execute queries in the following way: import as sqlite with sqlite.connect(db_filename) as conn: query = "INSERT OR IGNORE INTO shapes VALUES (?,?);" results = conn.execute(query, ("ID1","triangle")) With the code above, if my query modifies the database and I forget to run `conn.commit()`,the context manager runs it for me automatically upon exiting the `with` statement. It also handles exceptions nicely: if an exception occurs before I commit anything, then the database is rolled back. I am now using the `MySQLdb` interface, which doesn't seem to support a similar context manager out of the box. How do I create my own? There is a related question [here](http://stackoverflow.com/questions/1107297/looking- for-a-more-pythonic-way-to-access-the-database), but it doesn't offer a complete solution. Answer: Note that MySQLdb connections are now context managers already. See [user2966041's answer](http://stackoverflow.com/a/22840557/190597). * * * You could use something like this: import config import MySQLdb import MySQLdb.cursors as mc import _mysql_exceptions DictCursor = mc.DictCursor SSCursor = mc.SSCursor SSDictCursor = mc.SSDictCursor Cursor = mc.Cursor class Cursor(object): def __init__(self, cursorclass=Cursor, host=config.HOST, user=config.USER, passwd=config.PASS, dbname=config.MYDB, driver=MySQLdb, ): self.cursorclass = cursorclass self.host = host self.user = user self.passwd = passwd self.dbname = dbname self.driver = driver self.connection = self.driver.connect( host=host, user=user, passwd=passwd, db=dbname, cursorclass=cursorclass) self.cursor = self.connection.cursor() def __iter__(self): for item in self.cursor: yield item def __enter__(self): return self.cursor def __exit__(self, ext_type, exc_value, traceback): self.cursor.close() if isinstance(exc_value, Exception): self.connection.rollback() else: self.connection.commit() self.connection.close() with Cursor() as cursor: print(cursor) connection = (cursor.connection) print(connection) To use it you would place `config.py` in your PYTHONPATH and define the HOST, USER, PASS, MYDB variables there. Note also that [oursql](http://packages.python.org/oursql/) is an alternative driver for MySQL that comes with the `with` construct built in: with some_connection as cursor: do_something_with(cursor) You might want to consider using oursql instead.
Resources for working with Machine Learning in F# Question: I have learned a Machine Learning course using Matlab as a prototyping tool. Since I got addicted to F#, I would like to continue my Machine Learning study in F#. I may want to use F# for both prototyping and production, so **a Machine Learning framework** would be a great start. Otherwise, I can start with a collection of libraries: * Highly-optimized linear algebra library * Statistics package * Visualization library (which allows to draw and interact with charts, diagrams...) * Parallel computing toolbox (similar to Matlab parallel computing toolbox) And the most important resources (to me) are **books** , blog posts and online courses regarding Machine Learning in a functional programming language (F#/OCaml/Haskell...). Can anyone suggest these kinds of resource? Thanks. * * * **EDIT:** This is a summary based on the answers below: Machine Learning frameworks: * [Infer.NET](http://research.microsoft.com/en-us/um/cambridge/projects/infernet/): an .NET framework for Bayesian inference in graphical models with good F# support. * [WekaSharper](http://wekasharp.codeplex.com/): a F# wrapper around the popular data mining framework Weka. * [Microsoft Sho](http://msdn.microsoft.com/en-us/library/hh304371.aspx): a continuous environment development for data analysis (including matrix operations, optimization and visualization) on .NET platform. Related libraries: * [Math.NET Numerics](http://mathnetnumerics.codeplex.com/): internally using Intel MKL and AMD ACML for matrix operations and supporting statistics functions too. * [Microsoft Solver Foundation](http://archive.msdn.microsoft.com/solverfoundation): a good framework for linear programming and optimization tasks. * [FSharpChart](http://code.msdn.microsoft.com/windowsdesktop/FSharpChart-b59073f5): a nice data visualization library in F#. Reading list: * [Numerical Computing](http://msdn.microsoft.com/en-us/library/hh273075.aspx): It is great for starting with Machine Learning in F# and introduces various tools and tips/tricks for working with these Math libraries in F#. * [F# and Data Mining blog](http://fdatamining.blogspot.com/): It is also from Yin Zhu, the author of Numerical Computing chapter, highly recommended. * [F# as a Octave/Matlab replacement for Machine Learning](http://blog.codebeside.org/blog/2011/10/27/f-as-a-octavematlab-replacement-for-machine-learning): Gustavo has just started a series of blog posts using F# as the development tool. It's great to see many libraries are plugged in together. * ["Machine Learning in Action" 's samples in F#](http://www.clear-lines.com/blog/?tag=/Machine%20Learning): Mathias has translated some samples from Python to F#. They are available in [Github](https://github.com/mathias-brandewinder/Machine-Learning-In-Action). * [Hal Daume's homepage](http://www.umiacs.umd.edu/~hal/software.html): Hal has written a number of Machine Learning libraries in OCaml. You would feel relieved if you were in doubt that functional programming was not suitable for Machine Learning. Any other pointers or suggestions are also welcome. Answer: There isn't a single place to look for resources on F# and machine learning, but here are a couple of links that may be quite useful: * [Numerical Computing](http://msdn.microsoft.com/en-us/library/hh273075.aspx) section on MSDN is a good resource on using various numerical libraries from F#. The most advanced library that implements linear algebra and other algorithsm useful in machine learning is [Math.NET Numerics](http://msdn.microsoft.com/en-us/library/hh304363.aspx). * [Visualizing Data](http://msdn.microsoft.com/en-us/library/hh273079.aspx) section on MSDN has some resources on charting in F#. The FSharpChart library is now maintained by Carl Nolan who regularly posts [updates to his blog](http://blogs.msdn.com/b/carlnol/). There are also a few personal pages of people who are working on relevant topics: * Jurgen van Gael (who did PhD in machine learning) contributed to the Math.NET library and you can read about [his experience here](http://mlg.eng.cam.ac.uk/jurgen/fsharp.html). * Yin Zhu who wrote the Numerical Computing chapter on MSDN (and is a PhD student interested in machine learning) has quite a few [excellent articles on his blog](http://fdatamining.blogspot.com/).
Number of seconds since the beginning of the day UTC timezone Question: How do I find "number of seconds since the beginning of the day UTC timezone" in Python? I looked at the docs and didn't understand how to get this using `datetime.timedelta`. Answer: Here's one way to do it. from datetime import datetime, time utcnow = datetime.utcnow() midnight_utc = datetime.combine(utcnow.date(), time(0)) delta = utcnow - midnight_utc print delta.seconds # <-- careful **EDIT** As suggested, if you want microsecond precision, or potentially crossing a 24-hour period (i.e. delta.days > 0), use `total_seconds()` or the formula given by @unutbu. print delta.total_seconds() # 2.7 print delta.days * 24 * 60 * 60 + delta.seconds + delta.microseconds / 1e6 # < 2.7
How to get filename when running mapreduce job on EC2? Question: I am learning elastic mapreduce and started off with the Word Splitter example provided in the Amazon Tutorial Section(code shown below). The example produces word count for all the words in all the input documents provided. But I want to get output for Word Counts by file names i.e the count of a word in just one particular document. Since the python code for word count takes input from stdin, how do I tell which input line came from which document ? Thanks. #!/usr/bin/python import sys import re def main(argv): line = sys.stdin.readline() pattern = re.compile("[a-zA-Z][a-zA-Z0-9]*") try: while line: for word in pattern.findall(line): print "LongValueSum:" + word.lower() + "\t" + "1" line = sys.stdin.readline() except "end of file": return None if __name__ == "__main__": main(sys.argv) Answer: In the typical WordCount example, the file name which the map file is processing is ignored, since the the job output contains the consolidated word count for all the input files and not at a file level. But to get the word count at a file level, the input file name has to be used. Mappers using Python can get the file name using the `os.environ["map.input.file"]` command. The list of task execution environment variables is [here](http://hadoop.apache.org/common/docs/current/mapred_tutorial.html#Configured+Parameters). The mapper instead of just emitting the key/value pair as `<Hello, 1>`, should also contain the input file name being processed. The following can be the emitted by the map `<input.txt, <Hello, 1>>`, where input.txt is the key and `<Hello, 1>` is the value. Now, all the word counts for a particular file will be processed by a single reducer. The reducer must then aggregate the word count for that particular file. As usual, a Combiner would help to decrease the network chatter between the mapper and the reducer and also to complete the job faster. Check [Data-Intensive Text Processing with MapReduce](http://www.umiacs.umd.edu/~jimmylin/MapReduce-book-final.pdf) for more algorithms on text processing.
sys.exc_info or sys.last_*? Question: Should I prefer [`sys.exc_info()`](http://docs.python.org/py3k/library/sys.html#sys.exc_info) over [`sys.last_value`](http://docs.python.org/py3k/library/sys.html#sys.last_type) and friends (`sys.last_type`, `sys.last_traceback`)? Answer: Looking at the documentation of `sys.last_value` and friends: > Their intended use is to allow an interactive user to import a debugger > module and engage in post-mortem debugging without having to re-execute the > command that caused the error. So, if you are in an interpreter doing debugging I suggest using `sys.last_value`, but in a script I suggest you to use `sys.exc_info()`.
PyQt4 names showing as undefined in eclipse, but it runs fine Question: I am using Eclipse 3.7.1 with the latest PyDev add-in for Python coding. I am using PyQt4. At the top of my file I have: from PyQt4.QtCore import * from PyQt4.QtGui import * In addition, I have the PyQt4 tree included in the Project Explorer listing. However, eclipse still thinks the names like QMainWindow are undefined. The code runs fine. How may I get eclipse to recognize those names. Thanks Answer: PyQt is actually a wrapping of C++ Qt libraries. So they are not `.py` files and PyDev can't analyze them to get what is in them. You need to add `PyQt4` in the [Forced Builtins](http://pydev.org/manual_101_interpreter.html#id1) tab, so that PyDev can use a Python shell to "look into" those libraries and know what is in them. That will also give you code-completion for PyQt. Apart from that, it is usually not a good practice to use `from foo import *`. You'll be importing everything inside your namespace and you wouldn't know which is coming from where. Moreover you might have name clashes that mask each other. Though it is unlikely with PyQt, still I'd suggest you get used to `from PyQt4 import QtGui, QtCore` and reference classes like `QtGui.QMainWindow`.
Generating pdf-latex with python script Question: I'm a college guy, and in my college, to present any kind of homework, it has to have a standard coverpage (with the college logo, course name, professor's name, my name and bla bla bla). So, I have a .tex document, which generate my standard coverpages pdfs. It goes something like: ... \begin{document} %% College logo \vspace{5cm} \begin{center} \textbf{\huge "School and Program Name" \\} \vspace{1cm} \textbf{\Large "Homework Title" \\} \vspace{1cm} \textbf{\Large "Course Name" \\} \end{center} \vspace{2.5cm} \begin{flushright} {\large "My name" } \end{flushright} ... So, I was wondering if there's a way to make a Python script that asks me for the title of my homework, the course name and the rest of the strings and use them to generate the coverpage. After that, it should compile the .tex and generate the pdf with the information given. Any opinions, advice, snippet, library, is accepted. Answer: You can start by defining the template tex file as a string: content = r'''\documentclass{article} \begin{document} ... \textbf{\huge %(school)s \\} \vspace{1cm} \textbf{\Large %(title)s \\} ... \end{document} ''' Next, use `argparse` to accept values for the course, title, name and school: parser = argparse.ArgumentParser() parser.add_argument('-c', '--course') parser.add_argument('-t', '--title') parser.add_argument('-n', '--name',) parser.add_argument('-s', '--school', default='My U') A bit of string formatting is all it takes to stick the args into `content`: args = parser.parse_args() content%args.__dict__ After writing the content out to a file, cover.tex, with open('cover.tex','w') as f: f.write(content%args.__dict__) you could use `subprocess` to call `pdflatex cover.tex`. proc = subprocess.Popen(['pdflatex', 'cover.tex']) proc.communicate() You could add an `lpr` command here too to add printing to the workflow. Remove unneeded files: os.unlink('cover.tex') os.unlink('cover.log') The script could then be called like this: make_cover.py -c "Hardest Class Ever" -t "Theoretical Theory" -n Me * * * Putting it all together, import argparse import os import subprocess content = r'''\documentclass{article} \begin{document} ... P \& B \textbf{\huge %(school)s \\} \vspace{1cm} \textbf{\Large %(title)s \\} ... \end{document} ''' parser = argparse.ArgumentParser() parser.add_argument('-c', '--course') parser.add_argument('-t', '--title') parser.add_argument('-n', '--name',) parser.add_argument('-s', '--school', default='My U') args = parser.parse_args() with open('cover.tex','w') as f: f.write(content%args.__dict__) cmd = ['pdflatex', '-interaction', 'nonstopmode', 'cover.tex'] proc = subprocess.Popen(cmd) proc.communicate() retcode = proc.returncode if not retcode == 0: os.unlink('cover.pdf') raise ValueError('Error {} executing command: {}'.format(retcode, ' '.join(cmd))) os.unlink('cover.tex') os.unlink('cover.log')
Matplotlib - Grid arrangement subplots spacing Question: I am trying to arrange a bunch of subplots in a grid like fashion. The problem is that the number of subplots varies with user selection of what data to plot. Right now I am trying to add plots this way: l = len(clicked) self.p=wx.Panel(self) self.dpi=100 self.fig = Figure() self.canvas = FigCanvas(self.p, -1, self.fig) if l == 1: self.splt = self.fig.add_subplot(1,1,1) self.plt=self.splt.plot(np.arange(5),np.arange(5)) else: for i in np.arange(l): self.splt=self.fig.add_subplot(l+1,2,i+1) self.fig.subplots_adjust(left=0.7, bottom=0.6, right=0.75, top=0.75) self.plt=self.splt.plot(np.arange(5),np.arange(5)) I am just using fake data for debugging purposes. Anyhow, I am using wxPython to draw this inside a frame. `clicked` here provides the number of selections the user made. I already tried using `subplots_adjust()`, with quite the opposite result than I wanted. The plots are being shrunk something indiscernable. Is there a way to arrange teh plots in some sort of grid. I saw there is an option `subplot2grid`, but I havent gotten it to work with the variable number of subplots. Answer: Hopefully this helps: from __future__ import division import numpy as np import pylab as plt def divideSquare(N): if N<1: return 1,1 minX = max(1,int(np.floor(np.sqrt(N)))) maxX = max(minX+1, int(np.ceil(np.sqrt(5.0/3*N)))) Nx = range(minX, maxX+1) Ny = [np.ceil(N/y) for y in Nx] err = [np.uint8(y*x - N) for y in Nx for x in Ny] ind = np.argmin(err) y = Nx[int(ind/len(Ny))] x = Ny[ind%len(Nx)] return min(y,x), max(y,x) Nlist = np.arange(0,101) empty = np.zeros_like(Nlist) ratio = np.zeros_like(Nlist, dtype = float) for k, N in enumerate(Nlist): y,x = divideSquare(N) empty[k] = y*x - N ratio[k] = 1.0 * x/y print y,x,y/x plt.figure(1) plt.clf() y,x = divideSquare(2) plt.subplot(y,x,1) plt.plot(Nlist, empty, 'k') plt.xlabel('Number of plots') plt.ylabel('Empty squares left') plt.subplot(y,x,2) plt.plot(Nlist, ratio, 'r') plt.xlabel('Number of plots') plt.ylabel('Ratio') def divide2or3(N): if N<1: return 1,1 if N%2==0: return int(np.ceil(N/2)), 2 return int(np.ceil(N/3)), 3 Nlist = np.arange(0,101) empty = np.zeros_like(Nlist) ratio = np.zeros_like(Nlist, dtype = float) for k, N in enumerate(Nlist): y,x = divide2or3(N) empty[k] = y*x - N ratio[k] = 1.0 * x/y print y,x,y/x plt.figure(2) plt.clf() y,x = divide2or3(2) plt.subplot(y,x,1) plt.plot(Nlist, empty, 'k') plt.xlabel('Number of plots') plt.ylabel('Empty squares left') plt.subplot(y,x,2) plt.plot(Nlist, ratio, 'r') plt.xlabel('Number of plots') plt.ylabel('Ratio') plt.show() divideSquare(N) attempts to get a ratio close to 1 but with a minimal number of empty positions. divide2or3(N) gives you a grid of 2 or 3 columns (or rows if you invert x and y), but I'm not sure if this is what you want for 90 plots.
An issue with the soaplib hello world program Question: I am trying to get this server to run however I keep getting an error: server: import soaplib from soaplib.core.service import rpc, DefinitionBase from soaplib.core.model.primitive import String, Integer from soaplib.core.server import wsgi from soaplib.core.model.clazz import Array class HelloWorldService(DefinitionBase): @soap(String,Integer,_returns=Array(String)) def say_hello(self,name,times): results = [] for i in range(0,times): results.append('Hello, %s'%name) return results if __name__=='__main__': try: from wsgiref.simple_server import make_server soap_application = soaplib.core.Application([HelloWorldService], 'tns') wsgi_application = wsgi.Application(soap_application) server = make_server('localhost', 7789, wsgi_application) server.serve_forever() except ImportError: print "Error: example server code requires Python >= 2.5" error: Traceback (most recent call last): File "C:/Users/User/Desktop/wsdlHelloWorld.py", line 8, in <module> class HelloWorldService(DefinitionBase): File "C:/Users/User/Desktop/wsdlHelloWorld.py", line 9, in HelloWorldService @soap(String,Integer,_returns=Array(String)) NameError: name 'soap' is not defined [This](http://soaplib.github.com/soaplib/2_0/pages/helloworld.html) is where I found it so I would assume something is wrong on my end, I had tried to install soaplib a few times before and botched them up because of lxml relying on vcvarsall.bat, however I shouldn't think that would matter... **Update** well I got the example to work by adding `soap` to my `soaplib.core.service` imports (duh). So... from soaplib.core.service import rpc, DefinitionBase, soap however now when I try and use the suds client example they provide I get this error. File "C:\Python27\lib\urllib2.py", line 1174, in do_open raise URLError(err) URLError: <urlopen error [Errno 10061] No connection could be made because the target machine actively refused it> **Update** A nmap scan reveals that there is no service running on port 7789, which will cause urllib2 to throw a 10061 error. Answer: Add the following line to your imports from soaplib.core.service import soap And it should work fine ;-) securedome
sort eigenvalues and associated eigenvectors after using numpy.linalg.eig in python Question: I'm using numpy.linalg.eig to obtain a list of eigenvalues and eigenvectors: A = someMatrixArray from numpy.linalg import eig as eigenValuesAndVectors solution = eigenValuesAndVectors(A) eigenValues = solution[0] eigenVectors = solution[1] I would like to sort my eigenvalues (e.g. from lowest to highest), in a way I know what is the associated eigenvector after the sorting. I'm not finding any way of doing that with python functions. Is there any simple way or do I have to code my sort version? Answer: Use [numpy.argsort](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html#numpy.argsort). It returns the indices one would use to sort the array. import numpy as np import numpy.linalg as linalg A = np.random.random((3,3)) eigenValues,eigenVectors = linalg.eig(A) idx = eigenValues.argsort()[::-1] eigenValues = eigenValues[idx] eigenVectors = eigenVectors[:,idx]
Using Celery with SQLAlchemy and Pyramid Question: I'm creating the web app using Pyramid-1.2.1 with SQLAlchemy as database backend. Now I need to do some periodic tasks along with this app and I want to use Celery as a task processor and SQLAlchemy as the message queue and the result backend. 1) I've installed Celery-2.1.4 but I can not figure out how to make it work. Here is my `celeryconfig.py` file: # List of modules to import when celery starts. CELERY_IMPORTS = ("my_app.tasks", ) ## Result store settings. CELERY_RESULT_BACKEND = "database" CELERY_RESULT_DBURI = "sqlite:///MyDataBase.db" CELERY_RESULT_SERIALIZER = "json" ## Broker settings. BROKER_TRANSPORT = "sqlakombu.transport.Transport" BROKER_HOST = "sqlite:///MyDataBase.db" The `my_app.tasks` contain a simple addition task from the celery examples. Now when I run $ celeryd -l info I see the following: [2011-11-11 20:22:50,750: WARNING/MainProcess] [email protected] v2.1.4 is starting. [2011-11-11 20:22:50,765: WARNING/MainProcess] Configuration -> . broker -> sqlakombu.transport.Transport://guest@sqlite:///MyDataBase.db/ . queues -> . celery -> exchange:celery (direct) binding:celery . concurrency -> 4 . loader -> celery.loaders.default.Loader . logfile -> [stderr]@INFO . events -> OFF . beat -> OFF . tasks -> . chatrooms.task.add [2011-11-11 20:22:50,787: INFO/PoolWorker-1] child process calling self.run() [2011-11-11 20:22:50,789: INFO/PoolWorker-2] child process calling self.run() [2011-11-11 20:22:50,791: INFO/PoolWorker-3] child process calling self.run() [2011-11-11 20:22:50,796: INFO/PoolWorker-4] child process calling self.run() [2011-11-11 20:22:50,802: WARNING/MainProcess] [email protected] has started. [2011-11-11 20:22:50,804: WARNING/MainProcess] Traceback (most recent call last): [2011-11-11 20:22:50,805: WARNING/MainProcess] File "/Users/shashkin/python_v_env/bin/celeryd", line 8, in <module> [2011-11-11 20:22:50,805: WARNING/MainProcess] load_entry_point('celery==2.1.4', 'console_scripts', 'celeryd')() [2011-11-11 20:22:50,805: WARNING/MainProcess] File "/Users/shashkin/python_v_env/lib/python2.7/site-packages/celery-2.1.4-py2.7.egg/celery/bin/celeryd.py", line 166, in main [2011-11-11 20:22:50,805: WARNING/MainProcess] worker.execute_from_commandline() [2011-11-11 20:22:50,806: WARNING/MainProcess] File "/Users/shashkin/python_v_env/lib/python2.7/site-packages/celery-2.1.4-py2.7.egg/celery/bin/base.py", line 40, in execute_from_commandline [2011-11-11 20:22:50,806: WARNING/MainProcess] return self.run(*args, **vars(options)) [2011-11-11 20:22:50,806: WARNING/MainProcess] File "/Users/shashkin/python_v_env/lib/python2.7/site-packages/celery-2.1.4-py2.7.egg/celery/bin/celeryd.py", line 85, in run [2011-11-11 20:22:50,806: WARNING/MainProcess] return Worker(**kwargs).run() [2011-11-11 20:22:50,806: WARNING/MainProcess] File "/Users/shashkin/python_v_env/lib/python2.7/site-packages/celery-2.1.4-py2.7.egg/celery/apps/worker.py", line 121, in run [2011-11-11 20:22:50,807: WARNING/MainProcess] self.run_worker() [2011-11-11 20:22:50,807: WARNING/MainProcess] File "/Users/shashkin/python_v_env/lib/python2.7/site-packages/celery-2.1.4-py2.7.egg/celery/apps/worker.py", line 219, in run_worker [2011-11-11 20:22:50,807: WARNING/MainProcess] worker.start() [2011-11-11 20:22:50,807: WARNING/MainProcess] File "/Users/shashkin/python_v_env/lib/python2.7/site-packages/celery-2.1.4-py2.7.egg/celery/worker/__init__.py", line 217, in start [2011-11-11 20:22:50,808: WARNING/MainProcess] component.start() [2011-11-11 20:22:50,808: WARNING/MainProcess] File "/Users/shashkin/python_v_env/lib/python2.7/site-packages/celery-2.1.4-py2.7.egg/celery/worker/listener.py", line 238, in start [2011-11-11 20:22:50,808: WARNING/MainProcess] self.reset_connection() [2011-11-11 20:22:50,808: WARNING/MainProcess] File "/Users/shashkin/python_v_env/lib/python2.7/site-packages/celery-2.1.4-py2.7.egg/celery/worker/listener.py", line 416, in reset_connection [2011-11-11 20:22:50,808: WARNING/MainProcess] self.connection = self._open_connection() [2011-11-11 20:22:50,808: WARNING/MainProcess] File "/Users/shashkin/python_v_env/lib/python2.7/site-packages/celery-2.1.4-py2.7.egg/celery/worker/listener.py", line 480, in _open_connection [2011-11-11 20:22:50,809: WARNING/MainProcess] max_retries=conf.BROKER_CONNECTION_MAX_RETRIES) [2011-11-11 20:22:50,809: WARNING/MainProcess] File "/Users/shashkin/python_v_env/lib/python2.7/site-packages/celery-2.1.4-py2.7.egg/celery/utils/__init__.py", line 276, in retry_over_time [2011-11-11 20:22:50,809: WARNING/MainProcess] retval = fun(*args, **kwargs) [2011-11-11 20:22:50,809: WARNING/MainProcess] File "/Users/shashkin/python_v_env/lib/python2.7/site-packages/celery-2.1.4-py2.7.egg/celery/worker/listener.py", line 472, in _establish_connection [2011-11-11 20:22:50,809: WARNING/MainProcess] conn.connect() # evaluate connection [2011-11-11 20:22:50,809: WARNING/MainProcess] File "/Users/shashkin/python_v_env/lib/python2.7/site-packages/carrot-0.10.7-py2.7.egg/carrot/connection.py", line 170, in connect [2011-11-11 20:22:50,810: WARNING/MainProcess] return self.connection [2011-11-11 20:22:50,810: WARNING/MainProcess] File "/Users/shashkin/python_v_env/lib/python2.7/site-packages/carrot-0.10.7-py2.7.egg/carrot/connection.py", line 135, in connection [2011-11-11 20:22:50,810: WARNING/MainProcess] self._connection = self._establish_connection() [2011-11-11 20:22:50,810: WARNING/MainProcess] File "/Users/shashkin/python_v_env/lib/python2.7/site-packages/carrot-0.10.7-py2.7.egg/carrot/connection.py", line 148, in _establish_connection [2011-11-11 20:22:50,810: WARNING/MainProcess] return self.create_backend().establish_connection() [2011-11-11 20:22:50,810: WARNING/MainProcess] File "/Users/shashkin/python_v_env/lib/python2.7/site-packages/carrot-0.10.7-py2.7.egg/carrot/connection.py", line 161, in create_backend [2011-11-11 20:22:50,810: WARNING/MainProcess] return backend_cls(connection=self) [2011-11-11 20:22:50,811: WARNING/MainProcess] TypeError [2011-11-11 20:22:50,811: WARNING/MainProcess] : [2011-11-11 20:22:50,811: WARNING/MainProcess] __init__() takes exactly 2 arguments (1 given) [2011-11-11 20:22:50,811: INFO/MainProcess] process shutting down What am I missing? 2) Later I want to start Celery inside my app. What should I do after celery- pylons package installation? Should I put celery's settings in app's `.ini` file? Could someone provide me any example, because those I found in the net did not help me much. Thanks. Answer: This looks like an issue with version compatibility between `celery` packages and its dependencies. With the latest version of celery, 2.4.5 your example just works. With 2.1.4 I get the same error. If for any reason you need 2.1.4 version of celery only, you have to find out which dependencies you need to downgrade in order to make it work. By looking at the traceback, most likely, it'll be the carrot `dependency` but you may get into a dependency hell if other dependencies need certain version of `carrot`. I strongly suggest to use virtualenv with pip to be able to experiment with the versions of the packages easily. Trying to develop something using Python packages from Linux repositories can be very painful. [buildout versions](http://packages.python.org/buildout-versions/use.html) or [pip requirements](http://www.pip-installer.org/en/latest/requirements.html) address this kind of problems but AFAIK there is no set of pinned dependency versions for celery.
:: in strings in Python Question: I've been learning Python and I must say I loved it. But as a new learners I am having some other problems as well: Could you guys tell me whether it is a feature of Python or the library of itself. I am checking how to connect to sqllite database and I came up with this article and there is a code sample over there as such below: >>> from pysqlite2 import dbapi2 as sqlite >>> connection = sqlite.connect('test.db') >>> memoryConnection = sqlite.connect(':memory:') >>> cursor = connection.cursor() When he wrote memory as string, he put two `:` (colon) as well and I am wondering whether it is peculiar to library instead of Python itself. Answer: The `':memory:'` string is entirely database dependent. As explained in the [documentation for `sqlite`](http://docs.python.org/library/sqlite3.html#sqlite3.connect): > You can use `":memory:"` to open a database connection to a database that > resides in RAM instead of on disk. As far as the Python language is concerned, `':memory:'` is just a string like any other.
Simple way to query connected USB devices info in Python? Question: How can we query connected USB devices info in Python? I want to get UID Device Name (ex: SonyEricsson W660), path to device (ex: /dev/ttyACM0) And also what would be the best Parameter out of above info to be used as identifying the device whenever it's connected again? (UID?) I am working on Ubuntu 11.04. ATM I have this code (using pyUSB) busses = usb.busses() for bus in busses: devices = bus.devices for dev in devices: print repr(dev) print "Device:", dev.filename print " idVendor: %d (0x%04x)" % (dev.idVendor, dev.idVendor) print " idProduct: %d (0x%04x)" % (dev.idProduct, dev.idProduct) print "Manufacturer:", dev.iManufacturer print "Serial:", dev.iSerialNumber print "Product:", dev.iProduct The problem is I don't get desired output, will paste one example: <usb.legacy.Device object at 0x1653990> Device: idVendor: 4046 (0x0fce) idProduct: 53411 (0xd0a3) Manufacturer: 1 Serial: 3 Product: 2 First I don't get filename, it's most important to me. I am assuming it is the /dev/ttyACM0 etc part. Second, I guess there was some UID of every USB device, or I should use both Vendor or Product id? **EDIT: Apparently I have some setup issues, I think I am using wrong USB Library. (using libusb0.1) ATM. That's why I get Device (dev.filename) string empty. If someone can please just tell that on what operating system he is using what USB Library and what version of PyUSB I think it will solve my problems.** Answer: I can think of a quick code like this. Since all USB ports can be accessed via /dev/bus/usb/< bus >/< device > For the ID generated, even if you unplug the device and reattach it [ could be some other port ]. It will be the same. import re import subprocess device_re = re.compile("Bus\s+(?P<bus>\d+)\s+Device\s+(?P<device>\d+).+ID\s(?P<id>\w+:\w+)\s(?P<tag>.+)$", re.I) df = subprocess.check_output("lsusb") devices = [] for i in df.split('\n'): if i: info = device_re.match(i) if info: dinfo = info.groupdict() dinfo['device'] = '/dev/bus/usb/%s/%s' % (dinfo.pop('bus'), dinfo.pop('device')) devices.append(dinfo) print devices Sample output here will be: [ {'device': '/dev/bus/usb/001/009', 'tag': 'Apple, Inc. Optical USB Mouse [Mitsumi]', 'id': '05ac:0304'}, {'device': '/dev/bus/usb/001/001', 'tag': 'Linux Foundation 2.0 root hub', 'id': '1d6b:0002'}, {'device': '/dev/bus/usb/001/002', 'tag': 'Intel Corp. Integrated Rate Matching Hub', 'id': '8087:0020'}, {'device': '/dev/bus/usb/001/004', 'tag': 'Microdia ', 'id': '0c45:641d'} ]
can't create django project using Windows command prompt Question: if i run django-admin.py startproject mysite django-admin.py (which is located in `C:\python27\scripts/django-admin.py`) will open in a file editor (now it opens in python ide, but in the past i had pype so it would open in pype) so the file opens: #!C:\Python27\python.exe from django.core import management if __name__ == "__main__": management.execute_from_command_line() i see no output in the command prompt at all, so lets say i typed C:\abc:>django-admin.py startproject mysite when I hit enter i see `C:\abc>` and the project will not be created using the command prompt this issue is not new for me, i'm creating my python projects using pydev, i would love to fix this issue with the command prompt though :) **@slugonamission** when I run pyhon django-admin.py startproject mysite the output of the command prompt is python: can't open 'django-admin.py' file : [Errno 2] No such file or directory Answer: I don't think Windows supports the shebang line. Try invoking it with `python django-admin.py ...`
SWIG/python array inside structure Question: I've got a structure defined inside header.h that looks like : typedef struct { .... int icntl[40]; double cntl[15]; int *irn, *jcn; .... When I init an object with this structure, I have access to integers/doubles but not arrays. >> st.icntl <Swig Object of type 'int *' at 0x103ce37e0> >> st.icntl[0] Traceback (most recent call last): File "test_mumps.py", line 19, in <module> print s.icntl[0] TypeError: 'SwigPyObject' object is not subscriptable How to have access to the values in read/write? Answer: The easiest way to do this is to wrap your arrays inside a `struct`, which can then provide [extra methods to meet the "subscriptable" requirements](http://stackoverflow.com/questions/216972/in-python-what-does- it-mean-if-an-object-is-subscriptable-or-not). I've put together a small example. It assumes you're using C++, but the equivalent C version is fairly trivial to construct from this, it just requires a bit of repetition. First up, the C++ header that has the `struct` we want to wrap and a template that we use for wrapping fixed size arrays: template <typename Type, size_t N> struct wrapped_array { Type data[N]; }; typedef struct { wrapped_array<int, 40> icntl; wrapped_array<double, 15> cntl; int *irn, *jcn; } Test; Our corresponding SWIG interface then looks something like: %module test %{ #include "test.h" #include <exception> %} %include "test.h" %include "std_except.i" %extend wrapped_array { inline size_t __len__() const { return N; } inline const Type& __getitem__(size_t i) const throw(std::out_of_range) { if (i >= N || i < 0) throw std::out_of_range("out of bounds access"); return self->data[i]; } inline void __setitem__(size_t i, const Type& v) throw(std::out_of_range) { if (i >= N || i < 0) throw std::out_of_range("out of bounds access"); self->data[i] = v; } } %template (intArray40) wrapped_array<int, 40>; %template (doubleArray15) wrapped_array<double, 15>; The trick there is that we've used `%extend` to supply [`__getitem__`](http://docs.python.org/reference/datamodel.html#object.__getitem__) which is what Python uses for subscript reads and [`__setitem__`](http://docs.python.org/reference/datamodel.html#object.__setitem__) for the writes. (We could also have supplied a `__iter__` to make the type iteratable). We also gave the specific `wraped_array`s we want to use unique names to make SWIG wrap them in the output. With the supplied interface we can now do: >>> import test >>> foo = test.Test() >>> foo.icntl[30] = -654321 >>> print foo.icntl[30] -654321 >>> print foo.icntl[40] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "test.py", line 108, in __getitem__ def __getitem__(self, *args): return _test.intArray40___getitem__(self, *args) IndexError: out of bounds access You might also find [this approach](http://www.swig.org/Doc1.3/Python.html#Python_nn63) useful/interesting as an alternative.
Getting authenticationerror.login_cookie_required error while using Google adwords API with Python Question: I am trying to use python to consume some adwords soap API, I am able to get the auth token but when I try to make a get request I got the authenticationerror.login_cookie_required error. Any ideas? from suds.client import Client auth_data = {'accountType':'GOOGLE', 'Email':'[email protected]', 'Passwd':'xxxxxxxx', 'service':'adwords', 'source':'xxxxxxxxxx'} auth_data = urllib.urlencode(auth_data) auth_request = urllib2.Request('https://www.google.com/accounts/ClientLogin', auth_data) auth_response = urllib2.urlopen(auth_request) auth_response = auth_response.read() split = auth_response.split('=') auth_token = split[len(split)-1] url = 'https://adwords-sandbox.google.com/api/adwords/cm/v201109/CampaignService?wsdl' client = Client(url) authToken = auth_token developerToken = '[email protected]++NZD' userAgent = 'jameslin-python' client.set_options(soapheaders=(authToken,developerToken,userAgent)) client.service.get() Answer: Have you tried using the Python client library for the AdWords API? <http://code.google.com/p/google-api-ads-python/>
ImportError: No module named bz2 for Python 2.7.2 Question: I'm using Python 2.7.2 on Ubuntu 11.10. I got this error when importing the bz2 module: `ImportError: No module named bz2` I thought the bz2 module is supposed to come with Python 2.7. How can I fix this problem? EDIT: I think I previously installed Python 2.7.2 by compiling from source. Probably at that point I didn't have libbz2-dev and so the bz2 module is not installed. Now, I'm hoping to install Python2.7 through sudo apt-get install python2.7 But it will say it's already installed. Is there a way to uninstall the previous Python2.7 installation and reinstall? Answer: I meet the same problem, here's my solution. The reason of import error is while you are building python, system couldn't find the bz2 headers and skipped building bz2 module. Install them on Ubuntu/Debian: sudo apt-get install libbz2-dev Fedora: sudo yum install bzip2-devel and then rebuild python comes from [another answer](http://stackoverflow.com/questions/12806122/missing-python-bz2-module) @birryree's answer helps to back to the system's original python.
Why wont Web.py let me run a server on port 80? Question: Im trying to create a website with Web.py but its not letting me open a create a socket on port 80 but it works on every other port. I have port forwarded and all that so that's not the problem. python main.py 80 but when I do this I get the error: http://0.0.0.0:80/ Traceback (most recent call last): File "main.py", line 43, in <module> app.run() File "/usr/local/lib/python2.7/dist-packages/web/application.py", line 311, in run return wsgi.runwsgi(self.wsgifunc(*middleware)) File "/usr/local/lib/python2.7/dist-packages/web/wsgi.py", line 54, in runwsgi return httpserver.runsimple(func, validip(listget(sys.argv, 1, ''))) File "/usr/local/lib/python2.7/dist-packages/web/httpserver.py", line 148, in runsimple server.start() File "/usr/local/lib/python2.7/dist-packages/web/wsgiserver/__init__.py", line 1753, in start raise socket.error(msg) socket.error: No socket could be created my code so far is: import MySQLdb import web import hashlib as h urls = ( '/', "index", "/register/?", "register", "/login/?", "login", "/thankyou/?", "thankyou" ) app = web.application(urls, globals()) render = web.template.render("templates/") db = web.database (dbn="mysql", user="root", pw="461408", db="realmd") class index(): def GET(self): return render.index() class register(): def GET(self): return render.register() def POST(self): i = web.input() user = h.sha1(i.username).hexdigest() pw = h.sha1(i.password).hexdigest() n = db.insert("account", username=user, password=pw) if __name__ == '__main__': app.run() Can someone help please? Answer: You possibly have something else working on port 80. Try the command `netstat -ln | grep 80` to check that. Alternatively, you can try `telnet localhost 80`, and if the connection is refused then that port should be clear to use.
couchDB-Python storing Date Value Question: I was following the CouchDb tutorial from <http://packages.python.org/CouchDB/mapping.html>. This seems to be outdated since the modules dont work as per the program. So I just re wrote the CouchDB python script to store few values and here is my script. But when I lookup the CouchDb database I can find the name and age but the **date value is not stored**. Can someone tell me how to go about doing this? Also is there an updated python CouchDB tutorial? from couchdb import Server, Document from couchdb.mapping import TextField, IntegerField, DateTimeField import datetime class Person(Document): name = TextField() age = IntegerField() added = DateTimeField(default=datetime.datetime.now()) if __name__ == '__main__': server = Server('http://localhost:5984') try: db = server.create('person') except Exception: db = server['person'] person = Person(name='John Doe', age=42) db.save(person) Answer: The Couchdb example refers to a default value of `datetime.now` but you are using `datetime.datetime.now()`. The extra `datetime` is not an issue but you might want to consider using `from datetime import datetime` for readability. The issue is that you are calling a function and returning its value, while the example passes a function object which the Couchdb can call anytime it needs a default value. Get rid of the two parentheses and you should be OK.
Python. Doing some work on background with Gtk GUI Question: * **python 3.2.2** * **gtk3 3.2.2** * **python-gobject 3.0.2** I'm trying to display a GUI and do some work in the background. As I understand it should look something like this: #!/usr/bin/env python3 # -*- coding: utf-8 -*- import time from threading import Thread from gi.repository import Gtk, Gdk class Gui(): def run(self): self.Window = Gtk.Window() self.Window.set_border_width(8) self.Window.set_title("Некий GUI") self.Window.connect('destroy', lambda x: self.stop()) self.outBut = Gtk.Button.new_from_stock(Gtk.STOCK_OK) self.outBut.set_size_request(150, 35) self.outBut.connect('clicked', lambda x: self.passfun) self.Window.add(self.outBut) self.Window.show_all() def stop(self): Gtk.main_quit() def passfun(self): pass class LoopSleep(Thread): def run(self): i = 1 while True: print(i) i = i + 1 #time.sleep(1) gui = Gui() gui.run() loopSleep = LoopSleep() loopSleep.start() Gdk.threads_init() Gdk.threads_enter() Gtk.main() Gdk.threads_leave() But it does not work. Several cycles occurs when you press the button. And the cycle runs after the window is closed. But not together. What I do wrong? Answer: Can't claim to be any expert on python threading nor gtk3 but after playing around a little with your example I found something that appears to work the way you want it. Instead of sub classing Thread i use threading.start(target=loop_sleep), and placed that inside Gui. Glib.threads_init() also seem to be needed. #!/usr/bin/env python3 from gi.repository import Gtk,Gdk, GLib import threading import time class Gui(Gtk.Window): def __init__(self): self.Window = Gtk.Window() self.Window.set_border_width(8) self.Window.set_title("Некий GUI") self.Window.connect('destroy', lambda x: self.stop()) self.outBut = Gtk.Button.new_from_stock(Gtk.STOCK_OK) self.outBut.set_size_request(150, 35) self.Window.connect('destroy', lambda x: self.stop()) self.Window.add(self.outBut) self.Window.show_all() threading.Thread(target=loop_sleep).start() def stop(self): Gtk.main_quit() def passfun(self): pass def loop_sleep(): i = 1 while True: print(i) i = i + 1 #time.sleep(1) app = Gui() GLib.threads_init() Gdk.threads_init() Gdk.threads_enter() Gtk.main() Gdk.threads_leave()
How to find form.has_errors OR form.errors and enable the error in the first place Question: I have several related questions and post under one topic for clarity's sake. # Django/django_bookmarks/urls.py urlpatterns = patterns('', (r'^$', main_page), (r'^user/(\w+)/$', user_page), (r'^login/$', 'django.contrib.auth.views.login'), ) # login.html <html> <head> <title>Django Bookmarks - User Login</title> </head> <body> <h1>User Login</h1> {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <form method="post" action="."> {% csrf_token %} <p><label for="id_username">Username:</label> {{ form.username }}</p> <p><label for="id_password">Password:</label> {{ form.password }}</p> <input type="hidden" name="next" value="/" /> <input type="submit" value="login" /> </form> </body> </html> Based on the [book](http://rads.stackoverflow.com/amzn/click/1847196780), the **login.html** uses `form.has_errors` instead of `form.errors`. However, the `form.has_errors` doesn't print any warning message even if I enter a wrong user/password. After some investigation, I change it to `form.errors` and it works for me. Question 1> Which one should be used `form.errors` or `form.has_errors`? Question 2> If `form.has_errors` doesn't work, why django doesn't complain in the first place. The book was written for Django 1.0 and I am using Django 1.3. Is that the reason? Question 3> How to check which attributes the form has? I have tried the following and it doesn't give the information I needed. python manage.py shell Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> import django.contrib.auth.views >>> dir(django.contrib.auth.views) ['AuthenticationForm', 'HttpResponseRedirect', 'PasswordChangeForm', 'PasswordResetForm', 'QueryDict', 'REDIRECT_FIELD_NAME', 'RequestContext', 'SetPasswordForm', 'User', '_', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'auth_login', 'auth_logout', 'base36_to_int', 'csrf_protect', 'default_token_generator', 'get_current_site', 'login', 'login_required', 'logout', 'logout_then_login', 'never_cache', 'password_change', 'password_change_done', 'password_reset', 'password_reset_complete', 'password_reset_confirm', 'password_reset_done', 'redirect_to_login', 'render_to_response', 'reverse', 'settings', 'urlparse'] >>> >>> dir(django.contrib.auth.views.login) ['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] Question 4> When the following statement is needed? {% csrf_token %} Thank you Answer: `form.has_errors` is not documented in the [forms api](https://docs.djangoproject.com/en/dev/ref/forms/api/). I did a quick grep of the source code, and I could not find it in either Django 1.3 or my svn checkout of the 1.0.X branch. It seems that it's a mistake in the book you are using. Checking [`form.errors`](https://docs.djangoproject.com/en/1.3/ref/forms/api/#django.forms.Form.errors) in your template is fine. Another option would be to use the [`is_valid`](https://docs.djangoproject.com/en/1.3/ref/forms/api/#django.forms.Form.is_valid) method. {% if not form.is_valid %} If you tried to access `form.has_errors` in the view, you would get an `AttributeError`. However Django does not complain when try to access an variable that does not exist in the template, so `{{ form.has_errors }}` fails silently. See the docs on [template variables](https://docs.djangoproject.com/en/1.7/topics/templates/#variables) for more info. To introspect the attributes on the form, use `dir` on the form object, not the view. >>> from django.contrib.auth.views import AuthenticationForm >>> dir(AuthenticationForm) However I recommend you explore the [form api](https://docs.djangoproject.com/en/dev/ref/forms/api/) docs instead. The csrf token is required when you are using Django's [cross site request forgery protection](https://docs.djangoproject.com/en/dev/ref/contrib/csrf/).
String operations on xml nodes in Python Question: I am reading an xml file and want to perform string operations on the node's content. import os import elementtree.ElementTree as ET from xml.etree.ElementTree import ElementTree from xml.etree.ElementTree import tostring xml_file = os.path.abspath(__file__) xml_file = os.path.dirname(xml_file) xml_file = os.path.join(xml_file, "Small1Review.xml") print xml_file root = ET.parse(xml_file).getroot() text = tostring(root) #print text for a in text: #print a, "-->", a.text text = tostring(a) print text But the code gives the following error, Traceback (most recent call last): File "myEtXML.py", line 33, in <module> text = tostring(a) File "C:\Python26\lib\xml\etree\ElementTree.py", line 1009, in tostring ElementTree(element).write(file, encoding) File "C:\Python26\lib\xml\etree\ElementTree.py", line 543, in __init__ assert element is None or iselement(element) AssertionError How can I parse each node and perform some string operations on each of them.? Answer: You've written `for a in text`, but `text` is a string and you're treating it like an XML node. The `tostring` method takes an `etree.Element`, but in this case `a` is a character of your string `text`. If you want to iterate over the tree, just treat it as a list root = ET.parse(xml_file).getroot() for child in root: print tostring(child) Also, your comment `#print a, "-->", a.text` seems to indicate that you want the `text` attribute of your nodes. This is not what's returned by the `tostring` method. The `tostring` method takes a node and makes an XML style string out of it. If you want the text attribute, just use `a.text`.
Django with wsgi sporadically fails with "Premature end of script headers:" Question: I have a site that is running for months now on Apache2 and periodically it will just hiccup with the following: [Sat Nov 12 06:18:34 2011] [error] [client X.Y.Z.158] Premature end of script headers: sleepsoundly_wsgi.py [Sat Nov 12 06:18:49 2011] [error] [client X.Y.Z.158] Premature end of script headers: sleepsoundly_wsgi.py It has run 1000s of requests without a problem, but periodically it will do this a couple of times and then everything will be ok. This is happening while uploading about 300 files (.5 MB each). Each file is upload separately, 3 files at a time, 225 files upload fine, 226 and 227 failed, and then 228 -> end all worked normally. It doesn't do this every time, just occasionally and it isn't always these files that fail. Another time file #291 failed and all the rest worked. I've got nothing in the log to go on other than this cryptic message. I've checked and the only version of python on the machine is 2.7.1. I don't get an email from django, I don't get any of the normal clues as to what might be happening. I'm curious how to start troubleshooting this one. It recovers on its own, the automated program uploading the files keeps moving. How do I figure out what is going on in this case? Server version: Apache/2.2.17 (Ubuntu) Server built: Sep 1 2011 09:25:26 mod_wsgi: Version: 3.3-2ubuntu2 Server MPM: Prefork threaded: no forked: yes (variable process count) wsgi.conf has no lines in it that are not commented out. VirtualHost setup: WSGIDaemonProcess myemr user=mjones processes=1 maximum-requests=500 threads=15 WSGIProcessGroup myemr WSGIScriptAlias / /var/www/Python/myemr/myemr/deploy/myemr_wsgi.py myemr_wsgi.py from os.path import abspath, dirname, join import sys # For packages that don't play well with mod_wsgi sys.stdout = sys.stderr sys.path.insert(0, abspath(join(dirname(__file__), "../.."))) sys.path.insert(0, abspath(join(dirname(__file__), "../../myemr"))) sys.path.insert(0, abspath(join(dirname(__file__), "../../myemr/apps"))) sys.path.insert(0, abspath(join(dirname(__file__), "../../lib/python2.7/site-packages/"))) # We have to add both of these because they are installed with git? sys.path.insert(0, abspath(join(dirname(__file__), "../../src/pinax/"))) from django.core.handlers.wsgi import WSGIHandler import pinax.env # setup the environment for Django and Pinax pinax.env.setup_environ(project_path='myemr') # set application for WSGI processing application = WSGIHandler() Answer: The problem is likely because you have 'maximum-requests' set to 500. This will cause the mod_wsgi daemon processes to be restarted periodically. Since the mod_wsgi daemon processes are running in multithreaded configuration, if there was a stuck request, or long running request which doesn't finish before the forced shutdown timeout when the restart is being done, then it will be aborted by virtue of the process restart. The Apache child worker process will then see that as a request terminated without returning headers with the message you are seeing. Moral of the story, DO NOT use 'maximum-requests' options in production systems unless you have a very good reason such as out of control memory growth. Version 4.0 of mod_wsgi will have an optional but slightly more graceful restart option which can be applied for this case, but it still can't wait forever and a stuck request will still have to be aborted at some point and you will still see the message. BTW, don't specify 'processes=1' as it defaults to one process anyway and any use of the 'processes' option, even with value '1', causes 'wsgi.multiprocess' to be set True. Use of 'processes=1' should only be done where have a single process AND you have many Apache instances which you are load balancing across, also with a single process.
Can't load jinja2 with webapp2/Google App Engine Question: I'm going through the GAE webapp2 tutorial (runtime 2.7) using GoogleAppEngineLauncher on my Mac, and though I'm following everything exactly, I keep on getting an error at the point where we import the Jinja2 module: [Using Templates - Google App Engine](http://code.google.com/appengine/docs/python/gettingstartedpython27/templates.html) **Error:** > Traceback (most recent call last): File > "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine- > default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", > line 168, in Handle handler = > _config_handle.add_wsgi_middleware(self._LoadHandler()) File > "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine- > default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", > line 206, in _LoadHandler handler = import(path[0]) File > "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine- > default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", > line 640, in Decorate return func(self, *args, **kwargs) File > "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine- > default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", > line 1756, in load_module return self.FindAndLoadModule(submodule, fullname, > search_path) File > "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine- > default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", > line 640, in Decorate return func(self, *args, **kwargs) File > "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine- > default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", > line 1628, in FindAndLoadModule description) File > "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine- > default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", > line 640, in Decorate return func(self, *args, **kwargs) File > "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine- > default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", > line 1571, in LoadModuleRestricted description) File > "/Users/ykessler/Dropbox/appgrinders/gae_apps/helloworld2.7/helloworld.py", > line 9, in import jinja2 ImportError: No module named jinja2 So it for some reason can't find the module, even though it's supposed to be packaged as part of webapp2's extras. When I do a search on my file system it looks like it's there: /Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2/webapp2_extras/jinja2.py And if I deploy the app to GAE, it works fine. Why would it be failing locally? Answer: webapp2 packages its own jinja2 'glue' module, which is what you're importing, but it doesn't package jinja2 itself. If you want to use it, you'll need to install it in your system Python using easy_install, or put it in your app's directory.
python socket argument Question: I have some problem in python's socket. I would like to write a class about sync_file,and these are what I wrote. import socket class sync: def send_file(path,Socket): #I would like to income two argument. First one is the file's path, and the second one is the socket object. f = open(path,"rb"); line = f.read() f.close() s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) a = sync() a.sendfile(file,s) I thought I could send socket object as a argument, but it shows a error message.It said that expecting number of argument is two, but I send three. I wonder why it happened. Answer: You forgot the `self` argument for the method: class sync: def send_file(self, path, socket): # ... For method calls, Python automatically passes the object as first argument, so your function gets three arguments but only expects two. Hence the error.
how do I tell cutplace about this check class Question: I am trying to use the API in cutplace to build a custom check <http://cutplace.sourceforge.net/api.html#writing-checks> Using the included demo data and code I have tried to follow the manual, at least until it ends abruptly. useCutplace.py: # Validate a test CSV file. import os.path from cutplace import interface from cutplace import checks from cutplace import ranges class FullNameLengthIsInRangeCheck(checks.AbstractCheck): """Check that total length of customer name is within the specified range.""" def __init__(self, description, rule, availableFieldNames, location=None): super(FullNameLengthIsInRangeCheck, self).__init__(description, rule, availableFieldNames, location) self._fullNameRange = ranges.Range(rule) self.reset() def checkRow(self, rowMap, location): fullName = rowMap["last_name"] + ", " + rowMap["first_name"] fullNameLength = len(fullName) try: self._fullNameRange.validate("full name", fullNameLength) except ranges.RangeValueError, error: raise CheckError("full name length is %d but must be in range %s: %r" \ % (fullNameLength, self._fullNameRange, fullName)) icdPath = os.path.join("icd_customers_field_names_only.csv") dataPath = os.path.join("customers.csv") icd = interface.InterfaceControlDocument() icd.read(icdPath) for row in interface.validatedRows(icd, dataPath): print row The interface control document with custom check: ,Interface: customers, ,, ,Data format, D,Format,CSV D,Header,1 ,, ,Fields, ,Name, F,branch_id, F,customer_id, F,first_name, F,surname, F,gender, F,date_of_birth, C,"full name must have at most 100 characters",FullNameLengthIsInRange,:100 customers.csv Branch id,Customer id,First name,Surname,Gender,Date of birth 38000,16,Daisy,Mason,female,27.02.1946 38000,42,Wendy,Davis,female,30.12.1971 38000,57,Keith,Parker,male,02.06.1984 38000,76,Kenneth,Tucker,male,15.11.1908 38053,11,Carlos,Barrett,male,09.02.1929 38053,20,Terrance,Hart,male,11.03.1961 38053,34,Lori,Dunn,female,26.09.1996 38053,73,Mary,Sutton,female,09.12.1982 38053,83,Lorraine,Castro,female,15.08.1978 38111,16,Esther,Newman,female,23.03.1932 38111,79,Tyler,Rose,male,17.12.1920 38111,127,Andrew,Dixon,male,02.10.1913 The error >python useCutplace.py Traceback (most recent call last): File "useCutplace.py", line 29, in <module> icd.read(icdPath) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/cutplace-0.6.7-py2.6.egg/cutplace/interface.py", line 406, in read self._processRow(icdRowToProcess) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/cutplace-0.6.7-py2.6.egg/cutplace/interface.py", line 363, in _processRow self.addCheck(icdRowToProcess[1:]) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/cutplace-0.6.7-py2.6.egg/cutplace/interface.py", line 339, in addCheck checkClass = self._createCheckClass(checkType) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/cutplace-0.6.7-py2.6.egg/cutplace/interface.py", line 171, in _createCheckClass return self._createClass("checks", checkType, "Check", "check") File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/cutplace-0.6.7-py2.6.egg/cutplace/interface.py", line 162, in _createClass raise fields.FieldSyntaxError("cannot find %s: %s" % (typeName, str(type)), self._location) cutplace.fields.FieldSyntaxError: icd_customers_field_names_only.csv (R16C1): cannot find check: FullNameLengthIsInRange Answer: As of version 0.7.0, cutplace supports plugins. Simply store your own checks in a separate Python module and use the command line option `--plugins` to specify the folder where your modules are located. Cutplace will then import and initialize any Python module found in the plugins folder. The API chapter of the documenten contains a detailed example on how to do this.
Convert values in CSV column to individual columns Question: I have a CSV file with the following format: ID | STUFF | Custom | Custom Value 1 | string1 | name1 | val1 1 | string1 | name2 | val2 1 | string1 | name3 | val3 2 | string2 | name1 | val4 2 | string2 | name3 | val5 3 | string3 | name2 | val6 etc... The import part about the CSV is that the current Custom Column has various "Fields" in it that I need moved out to it's own column and paired with it's value in the next column. The Custom column contains somewhat unknown values. each ID, for example, may have a different subset of Custom "names". I do, however, know the complete set of possible "Custom" names available. Desired output: (NOTE: I realized I goofed on what I needed for the output, so now it's corrected) ID | STUFF | name1 | name2 | name3 1 | SomeText | name1_Value | name2_Value| name3_Value 2 | SomeText | name1_Value | name2_Value| name3_Value I am relatively new at Python and am having trouble seeing an elegant way of doing this without a serious amt of iterations/looping. I figured that using the CSV module and DictReader with tuples will probably end up being the right way of going about this, but I'm strugging with it at the moment. I have roughly 1200 rows in this file, and it only needs to work once, but I'd like to learn the best way to do things in python. Answer: The csv module is definitely a good start. I would build a dict for each ID, mapping field names to values. E.g. for ID 1: {'STUFF':'String 1', 'name1':'val1', 'name2':'val2', 'name3':'val3'} You can store these in a list (if your IDs are consecutive integers), or in another dict. Keep a set of all the field names you've seen. Then use a csv DictWriter to dump out the result in the format you want. Iterate over your list (using `enumerate`) or dict (using `d.iteritems()`), add the IDs back in to each dict, and send it to writerow.
Python: How do I redirect output of os.system to python shell? Question: I want to make a simple batch script using python using os.system. I am able to run the commands just fine, but the output for those commands dont print to the python shell. Is there some way to redirect the output to the python shell? Answer: You can use [`subprocess`](http://docs.python.org/library/subprocess.html#module- subprocess). from subprocess import Popen, PIPE p1 = Popen(['ls'], stdout=PIPE) print p1.communicate()[0] This will print the directory listing for the current directory. The `communicate()` method returns a tuple `(stdoutdata, stderrdata)`. If you don't include `stdout=PIPE` or `stderr=PIPE` in the `Popen` call, you'll just get `None` back. (So in the above, `p1.communicate[1]` is `None`.) In one line, print Popen([command], stdout=PIPE).communicate()[0] prints the output of `command` to the console. You should read more [here.](http://docs.python.org/library/subprocess.html#replacing-bin-sh-shell- backquote) There's lots more you can do with `Popen` and `PIPE`.
Gstreamer+python: adding and removing audio sources while pipeline is running Question: I'm working on a sample **python** script, originally found here: [Adding and removing audio sources to/from GStreamer pipeline on-the- go](http://stackoverflow.com/questions/3899666/adding-and-removing-audio- sources-to-from-gstreamer-pipeline-on-the-go). The aim is to make a script such as the one above, able to **insert and remove audio sources while the pipeline is running** but with an **audioconvert** element between the source and the adder. This is because in a more general case **Adder** wants the incoming streams to be of the same format. So here's the code; we create 2 generators (buzzers). The first emits a 1000Hz tone and waits for a return key. The second is a 500Hz tone, which is summed to the first one after the key press. Again, by pressing the return key, only the second generator is heard. #!/usr/bin/python import gobject; gobject.threads_init() import gst # THE FOLLOWING FUNCTION IS A REWORK OF THE ORIGINAL, STILL DOING THE JOB def create_raw_audiotest_signal(pipe, freq, adder): # create buzzer of a given freq buzzer = gst.element_factory_make("audiotestsrc","buzzer%d" % freq) buzzer.set_property("freq",freq) pipe.add(buzzer) buzzersrc=buzzer.get_pad("src") # Gather a request sink pad on the mixer sinkpad=adder.get_request_pad("sink%d") # .. and connect it to the buzzer buzzersrc.link(sinkpad) return buzzer, buzzersrc, sinkpad # THIS IS A MODIFIED VERSION, NOT WORKING, THAT JUST PUTS AN AUDIOCONVERT # ELEMENT BETWEEN THE GENERATOR AND THE ADDER. def create_audiotest_signal_with_converter(pipe, freq, adder): # create buzzer of a given freq buzzer = gst.element_factory_make("audiotestsrc","buzzer%d" % freq) buzzer.set_property("freq",freq) # add a converter because adder wants inputs with the same format. ac = gst.element_factory_make("audioconvert", "ac%d" % freq) pipe.add(buzzer, ac) # link the buzzer with the converter ... buzzer.link(ac) buzzersrc=buzzer.get_pad("src") # Gather a request sink pad on the mixer sinkpad=adder.get_request_pad("sink%d") # and then the converter to the adder ac.get_pad('src').link(sinkpad) return buzzer, buzzersrc, sinkpad if __name__ == "__main__": # First create our pipeline pipe = gst.Pipeline("mypipe") # Create a software mixer with "Adder" adder = gst.element_factory_make("adder","audiomixer") pipe.add(adder) # Create the first buzzer.. #buzzer1, buzzersrc1, sinkpad1 = create_raw_audiotest_signal(pipe, 1000, adder) buzzer1, buzzersrc1, sinkpad1 = create_audiotest_signal_with_converter(pipe, 1000, adder) # Add some output output = gst.element_factory_make("autoaudiosink", "audio_out") pipe.add(output) adder.link(output) # Start the playback pipe.set_state(gst.STATE_PLAYING) raw_input("1kHz test sound. Press <ENTER> to continue.") # Get another generator #buzzer2, buzzersrc2, sinkpad2 = create_raw_audiotest_signal(pipe, 500, adder) buzzer2, buzzersrc2, sinkpad2 = create_audiotest_signal_with_converter(pipe, 500, adder) # Start the second buzzer (other ways streaming stops because of starvation) buzzer2.set_state(gst.STATE_PLAYING) raw_input("1kHz + 500Hz test sound playing simoultenously. Press <ENTER> to continue.") # Before removing a source, we must use pad blocking to prevent state changes buzzersrc1.set_blocked(True) # Stop the first buzzer buzzer1.set_state(gst.STATE_NULL) # Unlink from the mixer buzzersrc1.unlink(sinkpad2) # Release the mixers first sink pad adder.release_request_pad(sinkpad1) # Because here none of the Adder's sink pads block, streaming continues raw_input("Only 500Hz test sound. Press <ENTER> to stop.") If you use **create_raw_audiotest_signal** in place of **create_audiotest_signal_with_converter** in both the calls of course it works. If you use a mixture of the two, it works, but with an unwanted extra delay inbetween. The most interesting case is when you use the audioconvert in both the calls, but gtk blocks at the first return key. Does anybody have any suggestion? What am I doing wrong? Thank you in advance. Answer: I found the answer myself, it was simple indeed... I added other components, but they live in the pipeline and keep having an independent play status. So the solution is set all the pipeline to playing, which in turn sets the status to all the children. **pipe.set_state(gst.STATE_PLAYING)** instead of: **buzzer2.set_state(gst.STATE_PLAYING)** and it works again.
import python module when using mod_python Question: i have been using imdbpy for some time. I was interested in making a very basic webservice to return json data. I have a basic system working earlier today however after a reboot i now get the following error AssertionError: Import cycle in /home/prog/www/imdb/imdb.py. the code is being ran using mod_python. which 100% works. the following lines seem to be the problem #!/usr/bin/env python import imdb from mod_python import apache def handler(req): req.content_type = "text/plain" req.write("test") return apache.OK if i comment the import imdb test is printed. Any help would be great Answer: I guess this could be the problem: You named your file "imdb.py". Rename it and the problem could be solved. Explication: When importing imdb, python finds your module before finding the imdb-package that you initially wanted to import (because current folder is listed in PYTHONPATH before the the standard python library). So basically you import yourself.
Modeling a linear system with Python Question: I would like to simulate/model a closed-loop, linear, time-invariant system (specifically a locked PLL approximation) with python. Each sub-block within the model has a known transfer function which is given in terms of complex frequency `H(s) = K / ( s * tau + 1 )`. Using the model, I would like to see how the system response as well as the noise response is affected as parameters (e.g. the VCO gain) are changed. This would involve using Bode plots and root-locus plots. What Python modules should I seek out to get the job done? Answer: I know this is a bit old, but a search brought me to this question. I put this together when I couldn't find a good module for it. It's not much, but it's a good start if somebody else finds themselves here. import matplotlib.pylab as plt import numpy as np import scipy.signal def bode(G,f=np.arange(.01,100,.01)): plt.figure() jw = 2*np.pi*f*1j y = np.polyval(G.num, jw) / np.polyval(G.den, jw) mag = 20.0*np.log10(abs(y)) phase = np.arctan2(y.imag, y.real)*180.0/np.pi % 360 plt.subplot(211) #plt.semilogx(jw.imag, mag) plt.semilogx(f,mag) plt.grid() plt.gca().xaxis.grid(True, which='minor') plt.ylabel(r'Magnitude (db)') plt.subplot(212) #plt.semilogx(jw.imag, phase) plt.semilogx(f,phase) plt.grid() plt.gca().xaxis.grid(True, which='minor') plt.ylabel(r'Phase (deg)') plt.yticks(np.arange(0, phase.min()-30, -30)) return mag, phase f=scipy.signal.lti([1],[1,1]) bode(f) Edit: I am back here because somebody upvoted this answer, you should try [Control Systems Library](http://www.cds.caltech.edu/~murray/wiki/index.php/Control_Systems_Library_for_Python). They have implemented the bulk of the Matlab control systems toolbox with matching syntax and everything.
Ignore case in glob() on Linux Question: I'm writing a script which will have to work on directories which are modified by hand by Windows and Linux users alike. The Windows users tend to not care at all about case in assigning filenames. Is there a way to handle this on the Linux side in Python, i.e. can I get a case-insensitive, glob-like behaviour? Answer: You can replace each alphabetic character c with [cC], via import glob def insensitive_glob(pattern): def either(c): return '[%s%s]'%(c.lower(),c.upper()) if c.isalpha() else c return glob.glob(''.join(map(either,pattern)))
Reading lines from a file Question: I am writing a program to read lines of text from 5 files and compile the text from these 5 files into respective lists. However I am having a great deal of trouble getting the program to actually read the text to a list, here is my code so far: from random import random from dice import choose b = open ('E:\Videos, TV etc\Python\ca2\beginning.txt', 'r'). readlines () stripped_b = [item.strip() for item in b] a = open ('E:\Videos, TV etc\Python\ca2\adjective.txt', 'r'). readlines () stripped_a = [item.strip() for item in a] i = open ('E:\Videos, TV etc\Python\ca2\inflate.txt', 'r'). readlines () stripped_i = [item.strip() for item in i] n = open ('E:\Videos, TV etc\Python\ca2\noun.txt', 'r'). readlines () stripped_n = [item.strip() for item in n] phrase = [] turn = 0 def business_phrase(x): x = raw_input("\n\nInsert a number of business phrases to generate: ") while turn <= x: turn += 1 for item in stripped_b: random_word = choose(item) phrase.append(random_word) for item in stripped_a: random_word = choose(item) phrase.append(random_word) for item in stripped_i: random_word = choose(item) phrase.append(random_word) for item in stripped_n: random_word = choose(item) phrase.append(random_word) print random_list business_phrase(x) where beginning, adjective, inflate and noun are the text files and dice is a python file containing the function for choose. I run this program to try and generate a phrase and I get the following error message: IOError: [Errno 22] invalid mode ('r') or filename 'E:\\Videos, Tv etc\\Python\\ca2\\x08eginning.txt' I have no idea why it won't read the text files as they are in the same directory as stated (in fact in the same directory as the program containing the function). Does anyone have any ideas I am completely stumped. Answer: when handling Windows pathnames, always use raw string literals: r'E:\Videos, TV etc\Python\ca2\beginning.txt' because otherwise the backslashes may be interpreted as starting an escape sequence. Also, watch out with backslashes at the end of a string: `r'C:\'` is not what you think it is.
Moving specific files in subdirectories into a directory - python Question: Im rather new to python but I have been attemping to learn the basics to help in my research within geology. Anyways I have several files that once i have extracted from their zip files (painfully slow process btw) produce several hundred subdirectories with 2-3 files in each. Now what I want to do is extract all those files ending with 'dem.tif' and place them in a seperate file (move not copy). I may have attempted to jump into the deep end here but the code i've written runs without error so it must not be finding the files (that do exist!) as it gives me the else statement. Here is the code i've created import os src = 'O:\DATA\ASTER GDEM\Original\North America\UTM Zone 14\USA\Extracted' # input dst = 'O:\DATA\ASTER GDEM\Original\North America\UTM Zone 14\USA\Analyses' # desired location def move(): for (dirpath, dirs, files) in os.walk(src): if files.endswith('dem.tif'): shutil.move(os.path.join(src,files),dst) print ('Moving ', + files, + ' to ', + dst) else: print 'No Such File Exists' Any help would be most appreciated and I thank you in advance for your time. Sincerely, Bjorn Answer: First, welcome to the community, and python! You might want to change your user name, especially if you frequent here. :) I suggest the following (stolen from [Mr. Beazley](http://www.dabeaz.com/generators-uk/index.html)): # genfind.py # # A function that generates files that match a given filename pattern import os import shutil import fnmatch def gen_find(filepat,top): for path, dirlist, filelist in os.walk(top): for name in fnmatch.filter(filelist,filepat): yield os.path.join(path,name) # Example use if __name__ == '__main__': src = 'O:\DATA\ASTER GDEM\Original\North America\UTM Zone 14\USA\Extracted' # input dst = 'O:\DATA\ASTER GDEM\Original\North America\UTM Zone 14\USA\Analyses' # desired location filesToMove = gen_find("*dem.tif",src) for name in filesToMove: shutil.move(name, dst)
Printing issue in Python Question: I feel like an idiot for even asking this but does anyone have any idea why my code is printing the list after every shuffle? def shuffle(L, nswaps): n = 0 for item in L: while n < nswaps: card_one = choose(L) card_two = choose(L) if card_two == card_one: card_two = choose(L) n += 1 L[card_one], L[card_two] = L[card_two], L[card_one] print L NB I haven't pasted the import/ calling the function stuff as it's not relevant to the question. Answer: Your print statement is inside the for loop, so it's going to print L for each element in L. Try un-indenting it to the same level as the for loop, to put it outside the loop
Python: Files stop being opened at a certain point Question: I've written the following program in Python: import re import os import string folder = 'C:\Users\Jodie\Documents\Uni\Final Year Project\All Data' folderlisting = os.listdir(folder) for eachfolder in folderlisting: print eachfolder if os.path.isdir(folder + '\\' + eachfolder): filelisting = os.listdir('C:\Users\Jodie\Documents\Uni\Final Year Project\All Data\\' + eachfolder) print filelisting for eachfile in filelisting: if re.search('.genbank.txt$', eachfile): genbankfile = open(eachfile, 'r') print genbankfile if re.search('.alleles.txt$', eachfile): allelesfile = open(eachfile, 'r') print allelesfile It looks through a lot of folders, and prints the following: 1. The name of each folder, without the path 2. A list of all files in each folder 3. Two specific files in each folder (Any files containing ".genbank.txt" and ".alleles.txt"). The code works until it reaches a certain directory, and then fails with the following error: Traceback (most recent call last): File "C:\Users\Jodie\Documents\Uni\Final Year Project\Altering Frequency Practice\Change_freq_data.py", line 16, in <module> genbankfile = open(eachfile, 'r') IOError: [Errno 2] No such file or directory: 'ABP1.genbank.txt' The problem is: 1. That file most definitely exists, since the program lists it before it tries to open the file. 2. Even if I take that directory out of the original group of directories, the program throws up the same error for the next folder it iterates to. And the next, if that one is removed. And so on. This makes me think that it's not the folder or any files in it, but some limitation of Python? I have no idea. It has stumped me. Any help would be appreciated. Answer: You should use os.walk() <http://docs.python.org/library/os.html#os.walk> Also, you need to read the contents of the file, you don't want to print the file object. And you need to close the file when you're done or use a context manager to close it for you. would look something like: for root, dirs, files in os.walk(folder): for file_name in files: if re.search('.genbank.txt$', file_name) or \ re.search('.alleles.txt$', file_name): with open(os.path.join(root, f), 'r') as f: print f.read() Keep in mind this is not 'exactly' what you're doing, this will walk the entire tree, you may just want to walk a single level like you are already doing.
Python3 - runpy.run_path not working on Ubuntu 10.10 Question: I have code like this: import runpy runpy.run_path('other.py', globals()) It works on my Windows Box with Python 3.2 but fails on the default Python3 installation (from the Repository) on my Ubuntu 10.10 machine with this message: Traceback (most recent call last): File "/home/markus/Documents/projects/BlenderSerialize/generate.py", line 2, in <module> runpy.run_path('other.py', globals()) AttributeError: 'module' object has no attribute 'run_path' I checked the documentation and it says that run_path was introduced in Python 2.7. What do I have to do to make this work? Answer: It was introduced in Python 2.7 and 3.2. Hence it will not work with Python 3.0 or 3.1. To make it work, use Python 2.7 or 3.2.
Running Fabric with Python script together Question: I see most of the Fabric API are use together with function. Example of file (sample.py): from fabric.api import * print "Hello" def deploy(): with settings(hosts_string="Remote", user = "ubuntu", key_filename="/home/ubuntu/key.pem"): put('/home/localuser/sample.sh', '/home/ubuntu/') run('bash /home/ubuntu/sample.sh') I run the command to execute fab deploy Is it possible to running Fabric in Main Method. So when I run it as a python script, the fabric will be executed. python ./sample.py Thanks! Answer: To answer your question directly, you can add this snippet to your file: from fabric.api import * print "Hello" def deploy(): with settings(host_string="Remote", user = "ubuntu", key_filename="/home/ubuntu/key.pem"): put('/home/localuser/sample.sh', '/home/ubuntu/') run('bash /home/ubuntu/sample.sh') if __name__ == '__main__': deploy() Now when you run `python ./sample.py`, it will do the same thing as `fab deploy` However, the `fab` allows you to do much more other than your simple example. See the [fab documentation](http://docs.fabfile.org/en/1.3.2/usage/fab.html) for more information on the flexibility of the `fab` command.
Why does installing a python package break setuptools and causes pkg_resources to not be found? Question: This is partly a question, partly my own findings on what I found to be the issue when I encountered this error: (cdbak)USER-MBP-2:.virtualenvs <YOUR_USER_NAME>$ pip Traceback (most recent call last): File "/Users/<YOUR_USER_NAME>/.virtualenvs/cdbak/bin/pip", line 6, in <module> from pkg_resources import load_entry_point ImportError: No module named pkg_resources This issue arose when I tried to install pypsum via pip in my virtual environment for use with django. (cdbak)USER-MBP-2:.virtualenvs <YOUR_USER_NAME>$ pip install pypsum I have been working in virtual environments, so I was fortunate that after it broke, I could just reset my virtual environment with the script I had written. I copied the output from the installation process and started looking closer into it and it seems like there is something that goes wrong in setuptools. The installation process tries to build the package but it does not find build_py in the setuptools which causes it to 'patch' the setuptools installation by renaming the currently installed setuptools. This is the part where I think funky stuff starts to happen: Setuptools installation detected at /Users/<YOUR_USER_NAME>/.virtualenvs/cdbak/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg Egg installation Patching... Renaming /Users/<YOUR_USER_NAME>/.virtualenvs/cdbak/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg into /Users/<YOUR_USER_NAME>/.virtualenvs/cdbak/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg.OLD.1321360113.04 And then it goes on to try and install another version of setuptools or so it seems: After install bootstrap. Creating /Users/<YOUR_USER_NAME>/.virtualenvs/cdbak/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg-info Creating /Users/<YOUR_USER_NAME>/.virtualenvs/cdbak/lib/python2.7/site-packages/setuptools.pth But it does not seem to install the setuptools package correctly in its current location and then results in a missing pkg_resources module (In fact, it is missing a lot of other things too) **[Setup]** > OS: Mac OS X Lion > Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) > virtualenv v1.6.1 Fresh virtual environment using virtualenvwrapper using requirements file to install these packages: > mercurial==1.9.3 > Django>=1.3.1 > MySQL-python>=1.2.3 > Sphinx > wsgiref > pylint > yolk > dbgp > django-debug-toolbar > south I was able to use pip to install other packages just fine but for some reason it seems to break with this installation. **[Question]** \- Do people think this is a mistake with the installation process of this package? \- Or, is it a mistake with setuptools? \- Or, am I just installing it incorrectly? **[Extra Note]** I can attach the file with the entire output but its a long file and I decided to only extract the segments I felt were relevant. If you would like to view the full file, I can upload that too. Answer: I'm not sure about _all_ of your problems but there is at least one problem caused by the `loremipsum` package that is a dependency for the `pypsum` package. For some reason, in the `setup.py` file of `loremipsum`, the author includes specific requirements for the `distribute` package: egg = { 'name': name, 'version': module.__version__, 'author': author, 'author_email': email.strip('<>'), 'url': url, 'description': "A Lorem Ipsum text generator", 'long_description': long_description, 'classifiers': module.__classifiers__, 'keywords': ['lorem', 'ipsum', 'text', 'generator'], 'setup_requires': ['distribute'], 'install_requires': ['distribute'], 'packages': [name], # 'package_dir': {'': '.'}, # 'package_data': {'': 'default/*.txt'}, # 'data_files': [(name, ('default/dictionary.txt', 'default/sample.txt'))], 'include_package_data': True, 'test_suite': 'tests.suite' } `distribute`, as you may know, is a fork of the `setuptools` package; there's a long history behind this. Since `distribute` is supposed to be an _almost_ plug-compatible replacement for `setuptools`, it will try to masquerade as `setuptools` and disable any existing `setuptools` already installed in that Python instance. Thus, putting `distribute` in a `setup.py` file as a requirement is usually not a good idea. By default, `virtualenv` will install a version of `setuptools` but it does have an option to use `distribute` instead. The Apple-supplied system Pythons in OS X 10.6 and 10.7 already come with versions of `setuptools` pre-installed and, because they are in non- standard system directories, cannot be so easily patched around. A simple workaround when using `virtualenv` on OS X seems to be to also use its `no- site-packages` option which will prevent the `setuptools` version from the system Python interfering with the required `distribute` in the `virtualenv`. No doubt the confusion between `distribute` and `setuptools` is causing the problems seen with `pkg_resources` since it is also supplied by both of them. So try re-creating your `virtualenv` this way: virtualenv --distribute --no-site-packages /path/to/ve That will also have the side-effect of not including the third-party packages that Apple ships with the system Python. You can add them back in with `PYTHONPATH` if you really need them but it's probably better to install separate versions.
How do I instrument my python code? Question: I'm developing some web apps with the grok framework, and I want to know what the framework is doing when serving a simple page. So, what tools are out there to grab such data, and maybe, graph it? Answer: Python has plenty of built-in reflectivity that could be used for instrumentation. For example: def hax_all_the_things(): for x in list(globals()): func = globals()[x] if callable(func) and not hasattr(func, 'instrumented'): globals()[x] = lambda func = func, *args, **kwargs: ( __import__('sys').stdout.write("HAX\n"), func(*args, **kwargs) )[1] globals()[x].instrumented = True
Why is an empty function call in python around 15% slower for dynamically compiled python code Question: This is pretty bad micro-optimizing, but I'm just curious. It usually doesn't make a difference in the "real" world. So I'm compiling a function (that does nothing) using `compile()` then calling `exec` on that code and getting a reference to the function I compiled. Then I'm executing it a couple million times and timing it. Then repeating it with a local function. Why is the dynamically compiled function around 15% slower (on python 2.7.2) for just the call? import datetime def getCompiledFunc(): cc = compile("def aa():pass", '<string>', 'exec') dd = {} exec cc in dd return dd.get('aa') compiledFunc = getCompiledFunc() def localFunc():pass def testCall(f): st = datetime.datetime.now() for x in xrange(10000000): f() et = datetime.datetime.now() return (et-st).total_seconds() for x in xrange(10): lt = testCall(localFunc) ct = testCall(compiledFunc) print "%s %s %s%% slower" % (lt, ct, int(100.0*(ct-lt)/lt)) The output I'm getting is something like: 1.139 1.319 15% slower Answer: The _[dis.dis()](http://docs.python.org/library/dis.html#module-dis)_ function shows that the code object for each version is identical: aa 1 0 LOAD_CONST 0 (None) 3 RETURN_VALUE localFunc 10 0 LOAD_CONST 0 (None) 3 RETURN_VALUE So the difference is in the function object. I compared each of the fields (func_doc, func_closure, etc) and the one that is different is func_globals. In other words, `localFunc.func_globals != compiledFunc.func_globals`. There is a cost for supplying your own dictionary instead of the built-in globals (the former has to be looked up when a stack frame is created on each call and the latter can be referenced directly by the C code which already knows about the default builtin globals dictionary). This is easy verified by changing the _exec_ line in your code to: exec cc in globals(), dd With **that** change, the timing difference goes away. Mystery solved!
How I create a web server that can interact with mobile applications? Question: Ok first of all I want to create a web server that can interact with php, Mysql or mango db and mobile applications. What do you think is better to use Java or Python? I would like some good articles about web servers and how to interact with php ... For example I managed to create an simple web server but I don't know how to run php on it , and how can I make a mobile app to connect on it... I would really appreciate some tips about these sort of things and some good tutorials ... Answer: You can use <http://pear.php.net/package/HTTP_Server> as webserver base. Executing PHP within that is as simple as running a CGI interpreter. You need the `php-cgi` binary and pass some [environment variables](http://en.wikipedia.org/wiki/Common_Gateway_Interface) and possibly the POST body. It's just important to [invoke the php- cgi](http://stackoverflow.com/questions/7047426/call-php-from-virtual-custom- web-server/7047581#7047581) binary with the right environment parameters. Also have a look at [Nanoweb](http://nanoweb.si.kz/), an existing webserver in PHP. It comes with a [`mod_cgi`](http://nanoweb.sourcearchive.com/documentation/2.2.9/mod__cgi_8php- source.html) implementation.
boost::python and set::erase -> weird behaviour Question: I'm trying to store objects in a std::set. Those objects are boost::shared_ptr<>, coming from the python environment. adding values to the set won't cause any troubles. But when I try to erase a value, even though I'm passing the very same reference, it won't work. Here is an example : #include <set> #include <iostream> #include <boost/shared_ptr.hpp> #include <boost/python.hpp> using namespace std; using namespace boost; using namespace boost::python; struct Bar { Bar() {} }; struct Foo { set< shared_ptr<Bar> > v_set; shared_ptr<Bar> v_ptr; Foo() {} void add( shared_ptr<Bar> v_param ) { cout << "storing " << v_param << "in v_set and v_ptr" << endl; v_set.insert(v_param); v_ptr = v_param; } void del( shared_ptr<Bar> v_param ) { cout << "deleting " << v_param << endl; if (v_param == v_ptr) { cout << "v_param == v_ptr" << endl; } else { cout << "v_param != v_ptr" << endl; } cout << "erasing from v_set using v_param" << endl; if (v_set.erase(v_param) == 0) { cout << "didn't erase anything" << endl; } else { cout << "erased !" << endl; } cout << "erasing from v_set using v_ptr" << endl; if (v_set.erase(v_ptr) == 0) { cout << "didn't erase anything" << endl; } else { cout << "erased !" << endl; } } }; BOOST_PYTHON_MODULE (test) { class_< Foo, shared_ptr<Foo> >("Foo") .def("add",&Foo::add) .def("remove",&Foo::del); class_< Bar, shared_ptr<Bar> >("Bar"); } compiling : %> gcc -pthread -fno-strict-aliasing -march=i686 -mtune=generic -O2 -pipe -DNDEBUG -march=i686 -mtune=generic -O2 -pipe -fPIC -I/usr/include/python2.7 -c test.cpp -o test.o %> g++ -pthread -shared -Wl,--hash-style=gnu -Wl,--as-needed build/temp.linux-i686-2.7/test.o -L/usr/lib -lboost_python -lpython2.7 -o test.so and now, a small python script : from test import * f = Foo() b = Bar() f.add(b) f.remove(b) Here is the result : storing 0x8c8bc58in v_set and v_ptr deleting 0x8c8bc58 v_param == v_ptr erasing from v_set using v_param didn't erase anything erasing from v_set using v_ptr erased ! * I store 0x8e89c58 inside the set and outside, just in case * I'm passing the same reference to both calls (0x8e89c58) * just to make sure i check if v == val * I try to erase by using v -- it doesn't work * I try to erase by using val -- it works ! I'm completely lost there - can't see what is causing this. Any input ? Answer: I ran your example then added some assertions that I thought should hold in `del()`: assert(!(v_param < v_ptr)); assert(!(v_ptr < v_param)); One of them failed! I dug into the implementation of `operator<` for `boost::shared_ptr` and found something strange: it compares the reference counts rather than the internal pointers! A little digging found a [mailing list post](http://lists.boost.org/Archives/boost/2008/10/143222.php) about this issue with some helpful links to two C++ documents: N1590 which explains why people thought this was a good idea, and N2637 which explains why it wasn't. It seems that the Boost people have not (yet?) adopted the N2637 recommendation, but C++11 has. So I built your test again using C++11 (`g++ -std=c++0x`), having removed `using namespace boost;` so as to use `std::shared_ptr`. This resulted in a horrible template-ridden error message which was solved by adding this at the top (easily derived from `boost/smart_ptr/shared_ptr.hpp`): template<class T> inline T * get_pointer(std::shared_ptr<T> const & p) { return p.get(); } And it works! If you can't use C++11, just implement your own custom comparator for your set which compares the pointers sanely: template <typename T> struct SmartComparator { bool operator()(shared_ptr<T> const& lhs, shared_ptr<T> const& rhs) { return lhs.get() < rhs.get(); } }; Then this will work: set< shared_ptr<Bar>, SmartComparator<Bar> > v_set;
getting sin curve values using python Question: I am looking to create a sin curve using python. I want a code to generate the values in the form of a sine curve. Such that if i plot those values i should get this curve. Can someone help me with this ? I should be able to differ the number of values it takes to reach the peak (basically varying the frequency). Thank you Answer: Have you got Matplotlib and NumPy installed? >>> import matplotlib.pyplot as plt >>> import numpy as np >>> x = np.linspace(-10, 10, 1000) >>> y = np.sin(x) >>> plt.plot(x, y) [<matplotlib.lines.Line2D object at 0x25d1ed0>] >>> plt.show() Skip the last few steps if you don't need the plot.
Python : Singleton class object to persist list between imports ? (Like django admin register) Question: I want to have `dict / list` to which I can add values, just like models can be added to the admin register in django ! My attempt : (`package -> __init__.py`) # Singleton object # __init__.py (Package: pack) class remember: a = [] def add(data): a.append[data] def get(): return a obj = remember() # models1.py import pack pack.obj.add("data") # models2.py import pack pack.obj.add("data2") print pack.obj.get() # We should get: ["data", "data2"] # We get : ["data2"] How to achieve the desired functionality ? Some say that methods can do this if you don't need sub-classing, how to do this with methods ? **Update:** To be more clear : > Just like `django admin register` any one can import and register itself > with admin, so that register is persisted between imports. Answer: If it's a singleton you're after, have a look at [this](http://www.garyrobinson.net/2004/03/python_singleto.html) old blog post. It contains a link to a well documented implementation ([here](http://www.garyrobinson.net/singletonmixin.py)).
word compression function using regular expressions in python Question: Can someone tell me why it seems I am not getting the right results using this regular expression in this python code? I would have thought, for example, that the initial vowel in the word "about" should not disappear. Thanks. >>> sentence = "But the third reason Americans should care about Europe is more important even than the risk of a renewed financial crisis." >>> regexp = r'^[AEIOUaeiou]+|[AEIOUaeiou]+$|[^AEIOUaeiou]' >>> def compress(word): ... pieces = re.findall(regexp, word) ... return ''.join(pieces) >>> compress(sentence) 'Bt th thrd rsn mrcns shld cr bt rp s mr mprtnt vn thn th rsk f rnwd fnncl crss.' Answer: ^ and $ anchor to the ends of the entire string, so you're not anchoring to the beginning and end of each word, but to the beginning and end of the entire sentence. When the sentence is only the word "about," it works as you expect. I think you want to anchor to word boundaries (\b) instead. <http://www.regular-expressions.info/wordboundaries.html> This might do what you want it to: regexp = r'\b[AEIOUaeiou]+|[AEIOUaeiou]+\b|[^AEIOUaeiou]'
xlrd "year is out of range" error, xldate_as_tuple Question: I am trying to use the `xldate_as_tuple`function to covert a datetime and a time value from two seperate cells in a spreadsheet into python datetime and time. I intend to combine the currently seperate values into one python datetime value for use later in my code. I can get the date row values to convert but having trouble with the time fields. I think its down to the format of the time cell in excel. In my situation the time fields in the spreadsheet are in the following format: 00/01/1900 16:47, or 00/01/1900 17:06. All I am interested in is the time (i.e. not the 00/01/1900 bit). Thinking about it, the '00' bit of the date is not a valid day of the month so I think thats what is calusing my problems. Thoughts appreciated as how best to get the time value. If the`xldate_as_tuple`will just not work for my situation then should I consider somehow getting the value in the cell as text and parsing it... Cheers Answer: `xldate_as_tuple` works as advertised, producing a (year, month, day, hour, minute, second) tuple. The problem is with what you are doing with that tuple, which in your case will have 0 for each of year, month, and day. Short answer: If you want a time value, call `datetime.time`, not `datetime.datetime`. Long answer: Open Excel. Into cell A1, type `16:47:00`. Copy that into B1 and C1. Format B1 with custom format `yyyy-mm-dd hh:mm:ss`. You should see `1900-01-00 16:47:00`. Into cell D1 type `=(16+47/60)/24`, then format C1 and D1 as number with 8 decimal places. You should see `0.699305556` in both C1 and D1. Fire up `xlrd` and try out `xlrd.xldate_as_tuple`: >>> import xlrd >>> b = xlrd.open_workbook('xlrd_time.xls') >>> s = b.sheet_by_index(0) >>> s.row_values(0) [0.6993055555555556, 0.6993055555555556, 0.6993055555555556, 0.6993055555555556] >>> [xlrd.xldate_as_tuple(t, 0) for t in s.row_values(0)] [(0, 0, 0, 16, 47, 0), (0, 0, 0, 16, 47, 0), (0, 0, 0, 16, 47, 0), (0, 0, 0, 16, 47, 0)] >>> Getting your fraction-of-a-day into `datetime` module territory: Your data is either a time-of-day or a duration ("timedelta"), so: >>> import datetime >>> t = (16 + 47/60.) / 24 >>> t 0.6993055555555556 >>> datetime.timedelta(days=t) datetime.timedelta(0, 60420) >>> x = xlrd.xldate_as_tuple(t, 0) >>> x (0, 0, 0, 16, 47, 0) >>> datetime.time(*x[3:]) datetime.time(16, 47) Your data is not a "datetime"; attempting to make a datetime will fail as you have found out: >>> datetime.datetime(*x) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: year is out of range
wx.ListBox.HitTest not working on Mac Question: The following code sample works under linux (ubuntu) and Windows XP, but not under OSX. import wx class frame(wx.Frame): def __init__(self,p=None): wx.Frame.__init__(self,p) self.box = wx.ListBox(self) self.box.AppendItems( ["Zero","One","Two","Three","Four","Five","Six"]) self.box.Bind(wx.EVT_MOUSE_EVENTS,self.onMouse) def onMouse(self,evt): pos = evt.GetPosition() print self.box.HitTest(pos) evt.Skip() class guiApp(wx.App): def __init__(self,redirect=False): wx.App.__init__(self,redirect) def OnInit(self): f = frame() f.Show() self.SetTopWindow(f) return True if __name__=="__main__": app = guiApp() app.MainLoop() On Linux and Windows, the correct items are identified when moused over. On OSX hittest always returns -1 (wx.NOT_FOUND) I'm running 32-bit wxPython, 2.8.12.1 (mac-unicode) which uses the Carbon API in 32bit python 2.7.2. I can't find this listed as a known bug in wxWidgets and I'm hesitant to submit as it seems this should work. The listbox control is deeply integrated into out GUI and I really don't want to swap it out for ListCtrl or something similar as we have all other functionality working now. Does anyone know a workaround? Answer: There is no work around if the listbox is scrolling. The scroll is handled be the underlying Carbon library and scroll position is not accurately reported back through wx. I found the bug in the wxWidgets source code and opened a ticket on the wxWidgets trac, <http://trac.wxwidgets.org/ticket/13699>, with a patch. The root of the bug is a call to the Mac's underlying DataBrowser with an incorrect rowId argument. wxWidgets was passing row position offsets, assuming this would be the rowId's (and maybe at some point apple used these internally when true Id's weren't specified.) Adding a call to another function translates a row's position (offset) into it's real id. With a patched version of wxWidgets the above script works as expected.
pymysql callproc() appears to affect subsequent selects Question: I'm attempting to transition a code base from using MySQLdb to pymysql. I'm encountering the following problem and wonder if anyone has seen something similar. In a nutshell, if I call a stored procedure through the pymysql cursor callproc() method a subsequent 'select' call through the execute() method using the same or a different cursor returns incorrect results. I see the same results for Python 2.7.2 and Python 3.2.2 Is the callproc() method locking up the server somehow? Code is shown below: conn = pymysql.connect(host='localhost', user='me', passwd='pwd',db='mydb') curr = conn.cursor() rargs = curr.callproc("getInputVar", (args,)) resultSet = curr.fetchone() print("Result set : {0}".format(resultSet)) # curr.close() # # curr = conn.cursor() curr.execute('select * from my_table') resultSet = curr.fetchall() print("Result set len : {0}".format(len(resultSet))) curr.close() conn.close() I can uncomment the close() and cursor creation calls above but this doesn't change the result. If I comment out the callproc() invocation the select statement works just fine. Answer: I have a similar problem with (committed) INSERT statements not appearing in the database. PyMySQL 0.5 für Python 3.2 and MySQL Community Server 5.5.19. I found the solution for me: instead of using the execute() method, I used the executemany method, explained in the module reference on <http://code.google.com/p/pymssql/wiki/PymssqlModuleReference> There is also a link to examples. **Update** A little later, today, I found out that this is not yet the full solution. A too fast exit() at the end of the python script makes the data getting lost in the database. So, I added a time.sleep() before closing the connection and before exit()ing the script, and finally all the data appeared! (I also switched to using a myisam table) import pymysql conn = pymysql.connect(host='localhost', user='root', passwd='', db='mydb', charset='utf8') conn.autocommit(True) cur = conn.cursor() # CREATE tables (SQL statements generated by MySQL workbench, and exported with Menu -> Database -> Forward Engineer) cur.execute(""" SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL'; DROP SCHEMA IF EXISTS `mydb` ; CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ; USE `mydb` ; # […] SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; """) # Fill lookup tables: cur.executemany("insert into mydb.number(tagname,name,shortform) values (%s, %s, %s)", [('ЕД','singular','sg'), ('МН','plural','p')] ) cur.executemany("insert into mydb.person(tagname,name,shortform) values (%s, %s, %s)", [('1-Л','first','1st'), ('2-Л','second','2nd'), ('3-Л','third','3rd')] ) cur.executemany("insert into mydb.pos(tagname,name,shortform) values (%s, %s, %s)", [('S','noun','s'), ('A','adjective','a'), ('ADV','adverb','adv'), ('NUM','numeral','num'), ('PR','preposition','pr'), ('COM','composite','com'), ('CONJ','conjunction','conj'), ('PART','particle','part'), ('P','word-clause','p'), ('INTJ','interjection','intj'), ('NID','foreign-named-entity','nid'), ('V','verb','v')] ) #[…] import time time.sleep(3) cur.close() conn.close() time.sleep(3) exit() I suggest the forum/group <https://groups.google.com/forum/#!forum/pymysql- users> for further discussion with the developer.
Python Crawler - AttributeError: Crawler instance has no attribute 'url' Question: I'm trying to learn the classes in python: #!/usr/bin/env python # *-* coding: utf-8 *-* import urllib2 from BeautifulSoup import BeautifulSoup as bs class Crawler: def visit(self, url): self.request = urllib2.Request(self.url) self.response = urllib2.urlopen(self.request) return self.response.read() if __name__ == "__main__": x = Crawler() print x.visit("http://google.com/") When I try to start getting the error: sigo@sarch ~/sources $ python test.py Traceback (most recent call last): File "test.py", line 16, in <module> print x.visit("http://google.com/") File "test.py", line 10, in visit self.request = urllib2.Request(self.url) AttributeError: Crawler instance has no attribute 'url' What am I doing wrong? Answer: You're saying `self.url` which is referring to the Crawler class's `url` attribute, which does not exist. You need to use just `url` since that's the name of the variable from your `visit()` function arguments.
Convert ASCII armored output to binary data Question: How can I convert the following PGP message to binary data using Python 2.6? -----BEGIN PGP MESSAGE----- Version: GnuPG v1.0.7 (MingW32) hQIOA68nz9GqU7SREAgAxWfwvpziO4N6KquxmeuYD/txfTceyXRZGVqAGFUGmOdE +K9PCLp/+p3cFC8OcOZg8WReI4wlpYzgS3/XsB4LL9MegSHwjjI9jNsnQOr9EeLA IgDEb1NeXZ499qnSY1ZvCy/VCF1O7H71y77VQTckpfyHgWvzkaaaheMC0r+JGLZO 0w3NCTERFJ8XaXKz/+qw4gA7xxbpT9nXVXMwEwYgiAviJBJhdYw63oTlRYGgGzPh H2YVNv2TWnpWp816xi+sbM1ZsJJERnAZSADKFYZzYw4E73VhUlrX5YBY4WN7UmQw= -----END PGP MESSAGE----- Answer: **ORIGINAL ANSWER:** Is this what you are after? >>> import binascii >>> message = '''hQIOA68nz9GqU7SREAgAxWfwvpziO4N6KquxmeuYD/txfTceyXRZGVqAGFUGmOdE ... +K9PCLp/+p3cFC8OcOZg8WReI4wlpYzgS3/XsB4LL9MegSHwjjI9jNsnQOr9EeLA ... IgDEb1NeXZ499qnSY1ZvCy/VCF1O7H71y77VQTckpfyHgWvzkaaaheMC0r+JGLZO ... 0w3NCTERFJ8XaXKz/+qw4gA7xxbpT9nXVXMwEwYgiAviJBJhdYw63oTlRYGgGzPh ... H2YVNv2TWnpWp816xi+sbM1ZsJJERnAZSADKFYZzYw4E73VhUlrX5YBY4WN7UmQw= ... ''' >>> binascii.a2b_base64(message) '\x85\x02\x0e\x03\xaf\'\xcf\xd1\xaaS\xb4\x91\x10\x08\x00\xc5g\xf0\xbe\x9c\xe2;\x83z*\xab\xb1\x99\xeb\x98\x0f\xfbq}7\x1e\xc9tY\x19Z\x80\x18U\x06\x98\xe7D\xf8\xafO\x08\xba\x7f\xfa\x9d\xdc\x14/\x0ep\xe6`\xf1d^#\x8c%\xa5\x8c\xe0K\x7f\xd7\xb0\x1e\x0b/\xd3\x1e\x81!\xf0\x8e2=\x8c\xdb\'@\xea\xfd\x11\xe2\xc0"\x00\xc4oS^]\x9e=\xf6\xa9\xd2cVo\x0b/\xd5\x08]N\xec~\xf5\xcb\xbe\xd5A7$\xa5\xfc\x87\x81k\xf3\x91\xa6\x9a\x85\xe3\x02\xd2\xbf\x89\x18\xb6N\xd3\r\xcd\t1\x11\x14\x9f\x17ir\xb3\xff\xea\xb0\xe2\x00;\xc7\x16\xe9O\xd9\xd7Us0\x13\x06 \x88\x0b\xe2$\x12au\x8c:\xde\x84\xe5E\x81\xa0\x1b3\xe1\x1ff\x156\xfd\x93ZzV\xa7\xcdz\xc6/\xacl\xcdY\xb0\x92DFp\x19H\x00\xca\x15\x86sc\x0e\x04\xefuaRZ\xd7\xe5\x80X\xe1c{Rd0' **EDIT 2016** : The original answer was from 2011. As pointed out in the comment section, the curren recommended API for this is `base64` as in: >>> message = ''' ... hQIOA68nz9GqU7SREAgAxWfwvpziO4N6KquxmeuYD/txfTceyXRZGVqAGFUGmOdE ... +K9PCLp/+p3cFC8OcOZg8WReI4wlpYzgS3/XsB4LL9MegSHwjjI9jNsnQOr9EeLA ... IgDEb1NeXZ499qnSY1ZvCy/VCF1O7H71y77VQTckpfyHgWvzkaaaheMC0r+JGLZO ... 0w3NCTERFJ8XaXKz/+qw4gA7xxbpT9nXVXMwEwYgiAviJBJhdYw63oTlRYGgGzPh ... H2YVNv2TWnpWp816xi+sbM1ZsJJERnAZSADKFYZzYw4E73VhUlrX5YBY4WN7UmQw= ... ''' >>> import base64 >>> base64.b64decode(message) b'\x85\x02\x0e\x03\xaf\'\xcf\xd1\xaaS\xb4\x91\x10\x08\x00\xc5g\xf0\xbe\x9c\xe2;\x83z*\xab\xb1\x99\xeb\x98\x0f\xfbq}7\x1e\xc9tY\x19Z\x80\x18U\x06\x98\xe7D\xf8\xafO\x08\xba\x7f\xfa\x9d\xdc\x14/\x0ep\xe6`\xf1d^#\x8c%\xa5\x8c\xe0K\x7f\xd7\xb0\x1e\x0b/\xd3\x1e\x81!\xf0\x8e2=\x8c\xdb\'@\xea\xfd\x11\xe2\xc0"\x00\xc4oS^]\x9e=\xf6\xa9\xd2cVo\x0b/\xd5\x08]N\xec~\xf5\xcb\xbe\xd5A7$\xa5\xfc\x87\x81k\xf3\x91\xa6\x9a\x85\xe3\x02\xd2\xbf\x89\x18\xb6N\xd3\r\xcd\t1\x11\x14\x9f\x17ir\xb3\xff\xea\xb0\xe2\x00;\xc7\x16\xe9O\xd9\xd7Us0\x13\x06 \x88\x0b\xe2$\x12au\x8c:\xde\x84\xe5E\x81\xa0\x1b3\xe1\x1ff\x156\xfd\x93ZzV\xa7\xcdz\xc6/\xacl\xcdY\xb0\x92DFp\x19H\x00\xca\x15\x86sc\x0e\x04\xefuaRZ\xd7\xe5\x80X\xe1c{Rd0'