text
stringlengths
226
34.5k
Window Icon of Exe in PyQt4 Question: I have a small program in PyQt4 and I want to compile the program into an Exe. I am using py2exe to do that. I can successfully set icon in the windows title bar using the following code, but when i compile it into exe the icon is lost and i see the default windows application. here is my program: import sys from PyQt4 import QtGui class Icon(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setGeometry(300, 300, 250, 150) self.setWindowTitle('Icon') self.setWindowIcon(QtGui.QIcon('c:/python26_/repy26/icons/iqor1.ico')) app = QtGui.QApplication(sys.argv) icon = Icon() icon.show() sys.exit(app.exec_()) _**_Here is the setup.py for py2exe**** from distutils.core import setup import py2exe setup(windows=[{"script":"iconqt.py" ,"icon_resources": [(1, "Iqor1.ico")]}] ,options={"py2exe":{"includes":["sip", "PyQt4.QtCore"]}}) Answer: The problem is that py2exe doesn't include the qt icon reader plugin. You need to tell it to include it with the data_files parameter. Something along these lines: setup(windows=[{"script":script_path, "icon_resources":[(1, icon_path)]}], data_files = [ ('imageformats', [ r'C:\Python26\Lib\site-packages\PyQt4\plugins\imageformats\qico4.dll' ])], options={"py2exe":{"packages":["gzip"], "includes":["sip"]}})
Controlling VirtualBox from commandline with python Question: We are using python virtualbox API for controlling the virtualbox. For that we are using the "pyvb" package(as given in python API documentation). al=pyvb.vb.VB() m=pyvb.vm.vbVM() al.startVM(m) we have executed using the python interpreter. No error is shown but the virtualbox doesnt start. Could you please tell us what could be wrong(all necessary modules and packages have been imported) Answer: I found that I can use the following functions to find if a VM is running, restore a VM to a specific snapshot, and start a VM by name. from subprocess import Popen, PIPE def running_vms(): """ Return list of running vms """ f = Popen(r'vboxmanage --nologo list runningvms', stdout=PIPE).stdout data = [ eachLine.strip() for eachLine in f ] return data def restore_vm(name='', snapshot=''): """ Restore VM to specific snapshot uuid name = VM Name snapshot = uuid of snapshot (uuid can be found in the xml file of your machines folder) """ command = r'vboxmanage --nologo snapshot %s restore %s' % (name,snapshot) f = Popen(command, stdout=PIPE).stdout data = [ eachLine.strip() for eachLine in f ] return data def launch_vm(name=''): """ Launch VM name = VM Name """ command = r'vboxmanage --nologo startvm %s ' % name f = Popen(command, stdout=PIPE).stdout data = [ eachLine.strip() for eachLine in f ] return data
Haskell equivalent of C's __LINE__ Question: Is there a way to get line-number/traceback information in Haskell? (like C's `__LINE__` macro or Python's `traceback.extract_stack()`) That would be of use for me for writing Haskell program that generates C++ code, which would be notated with comments telling which Haskell line is responsible for which C++ line. Haskell example: LINE "#include <foo.h>" -- this is line 12 : INDENT "void Foo::bar() {" "}" [ LINE $ "blah(m_" ++ x ++ ", \"" ++ x ++ "\");" | x <- ["Potato", "Avocado"] ] will generate this C++ code: #include <foo.h> // gen.hs:12 void Foo::bar() { // gen.hs:13 blah(m_Potato, "Potato"); // gen.hs:14 blah(m_Avocado, "Avocado"); // gen.hs:14 } // gen.hs:13 Answer: You can actually use the CPP `__LINE__` pragma in Haskell. {-# LANGUAGE CPP #-} main = do print "one" print __LINE__ $ runhaskell A.hs "one" 5 Also, the `Control.Exception.assert` function will emit a line number if its condition fails. import Control.Exception main = do print "one" assert False $ print "two" $ runhaskell A.hs "one" A.hs: A.hs:5:5-10: Assertion failed
Django: show/log ORM sql calls from python shell Question: Using the excellent [Django-Devserver](http://github.com/dcramer/django- devserver) I'm finding all kinds of interesting and unexpected SQL calls in my code. I wanted to find where the calls are coming from, and so I'm looking for a way to get a log or print-out of all SQL calls generated by the Django ORM in the Python shell. That is, when I do a Django ORM call via the Python shell, I'd like to see the resulting SQL printed out or logged. I noticed several solutions that add log info to the html page. Is there an easy way to dump to the command line instead? Answer: If you're using Django 1.3: import logging l = logging.getLogger('django.db.backends') l.setLevel(logging.DEBUG) l.addHandler(logging.StreamHandler())
clicking "cancel" in tkColorChooser dialog leads to Error Question: I use python 2.6 under linux (SUSE Linux Enterprise Desktop 11 (x86_64)). I tested some very simple code : import tkColorChooser tkColorChooser.askcolor() then if I click on cancel, I always get error like: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/lib-tk/tkColorChooser.py", line 62, in askcolor return Chooser(**options).show() File "/usr/lib64/python2.6/lib-tk/tkCommonDialog.py", line 50, in show s = self._fixresult(w, s) File "/usr/lib64/python2.6/lib-tk/tkColorChooser.py", line 48, in _fixresult r, g, b = widget.winfo_rgb(result) File "/usr/lib64/python2.6/lib-tk/Tkinter.py", line 786, in winfo_rgb self.tk.call('winfo', 'rgb', self._w, color)) _tkinter.TclError: unknown color name "" I have more complicated code using tkColorChooser, which gives same error if I click on cancel in the color chooser dialog. I think I can catch the error. But is tkColorChooser designed to be like this? Is there any other neater way to cope with this problem? Thanks! Answer: Looking at the version of tkColorChooser.py I have (Python 2.6.4, Win32), it should support the user pressing `cancel` (as do and should the other predefined dialogs): it is indeed supposed to return None when the results evals to `False` in a boolean context. Therefore, something strange is happening. edit: as I noted in the comments, it is indeed a bug that has been fixed in version 2.6.2.
How can I disable the webbrowser message in python? Question: In my python program, when I send the user to create a gmail account by use of the webbrowser module, python displays: "Please enter your Gmail username: Created new window in existing browser session." Is there any way to get rid of "created new window in existing browser session", as it takes up the space where the user types in their Gmail account. The code for this is: webbrowser.open('https://www.google.com/accounts/NewAccount?service=mail') gmail_user = raw_input('Please enter your Gmail username: ') **EDIT:** After trying out both of Alex Martelli's suggestions, the code is: <http://pastebin.com/3uu9QS4A> **EDIT 2:** I have decided just to tell users to go to the gmail registration page instead of actually sending them there, as that is much simpler to do and results in no (currently-unsolvable-by-me) errors. Answer: As S.Lott hints in a comment, you should probably do the `raw_input` first; however, that, per se, doesn't suppress the message from `webbrowser`, as you ask -- it just postpones it. To actually _suppress_ the message, you can temporarily redirect standard- output or standard-error -- whichever of the two your chosen browser uses to emit that message. It's probably no use to redirect them at Python level (via `sys.stdout` or `sys.stderr`), since your browser is going to be doing its output directly; rather, you can do it at the operating-system level, e.g., for standard output: import os gmail_user = raw_input('Please enter your Gmail username: ') savout = os.dup(1) os.close(1) os.open(os.devnull, os.O_RDWR) try: webbrowser.open(whatever) finally: os.dup2(savout, 1) (for standard error instead of standard output, use 2 instead of 1). This is pretty low-level programming, but since the webbrowser module does not give you "hooks" to control the way in which the browser gets opened, it's pretty much the only choice to (more or less) ensure suppression of that message.
Python drawing on screen Question: I'm coding an application that needs to select an area of the screen. I need to change the cursor to a cross and then draw a rectangle on the user selection. The first thing I searched for is how to manipulate the cursor and I came across wxPython. With wxPython I could easily do this on a Frame with a Panel, the thing is that I'd need the window to be transparent so the user can see his screen while is selecting the desired area, but if I make the Frame and the Panel objects transparent everything gets buggy. So, I'm open to any solution, either using wxPython or not using it because I don't really know if I'm using it right. I'm new to Python and I'm not a native english speaker, so I'm sorry if you can't understand something. This is what I coded import wx class SelectableFrame(wx.Frame): c1 = None c2 = None def __init__(self, parent=None, id=-1, title=""): wx.Frame.__init__(self, parent, id, title, size=wx.DisplaySize(), style=wx.TRANSPARENT_WINDOW) self.panel = wx.Panel(self, size=self.GetSize(), style=wx.TRANSPARENT_WINDOW) self.panel.Bind(wx.EVT_MOTION, self.OnMouseMove) self.panel.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown) self.panel.Bind(wx.EVT_LEFT_UP, self.OnMouseUp) self.panel.Bind(wx.EVT_PAINT, self.OnPaint) self.SetCursor(wx.StockCursor(wx.CURSOR_CROSS)) def OnMouseMove(self, event): if event.Dragging() and event.LeftIsDown(): self.c2 = event.GetPosition() self.Refresh() def OnMouseDown(self, event): self.c1 = event.GetPosition() def OnMouseUp(self, event): self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) def OnPaint(self, event): if self.c1 is None or self.c2 is None: return dc = wx.PaintDC(self.panel) dc.SetPen(wx.Pen('red', 1)) dc.SetBrush(wx.Brush(wx.Color(0, 0, 0), wx.TRANSPARENT)) dc.DrawRectangle(self.c1.x, self.c1.y, self.c2.x - self.c1.x, self.c2.y - self.c1.y) def PrintPosition(self, pos): return str(pos.x) + " " + str(pos.y) class MyApp(wx.App): def OnInit(self): frame = SelectableFrame() frame.Show(True) self.SetTopWindow(frame) return True app = MyApp(0) app.MainLoop() Answer: You shouldn't be using wx.TRANSPARENT in window creation, that is mostly used for wxDC paint commands. To make a window transparent just call win.SetTransparent(amount), where amount is from 0-255, 255 means opaque, 0 means totally transparent. see <http://www.wxpython.org/docs/api/wx.Window- class.html#SetTransparent> I have modified your code, it will work only if your platform supports transparent windows, you can check that by CanSetTransparent. I tested it on windows XP. import wx class SelectableFrame(wx.Frame): c1 = None c2 = None def __init__(self, parent=None, id=-1, title=""): wx.Frame.__init__(self, parent, id, title, size=wx.DisplaySize()) self.panel = wx.Panel(self, size=self.GetSize()) self.panel.Bind(wx.EVT_MOTION, self.OnMouseMove) self.panel.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown) self.panel.Bind(wx.EVT_LEFT_UP, self.OnMouseUp) self.panel.Bind(wx.EVT_PAINT, self.OnPaint) self.SetCursor(wx.StockCursor(wx.CURSOR_CROSS)) self.SetTransparent(50) def OnMouseMove(self, event): if event.Dragging() and event.LeftIsDown(): self.c2 = event.GetPosition() self.Refresh() def OnMouseDown(self, event): self.c1 = event.GetPosition() def OnMouseUp(self, event): self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) def OnPaint(self, event): if self.c1 is None or self.c2 is None: return dc = wx.PaintDC(self.panel) dc.SetPen(wx.Pen('red', 1)) dc.SetBrush(wx.Brush(wx.Color(0, 0, 0), wx.TRANSPARENT)) dc.DrawRectangle(self.c1.x, self.c1.y, self.c2.x - self.c1.x, self.c2.y - self.c1.y) def PrintPosition(self, pos): return str(pos.x) + " " + str(pos.y) class MyApp(wx.App): def OnInit(self): frame = SelectableFrame() frame.Show(True) self.SetTopWindow(frame) return True app = MyApp(0) app.MainLoop()
How to compute information entropy in a two-step decision? Question: I have a question which I think involves "conditional entropy" in the field of information theory. I am trying to wrap my head around it, but could use some help. Consider an example in which we have four houses. In the first house there are eight people, four people live in the second house, and there are two people in third house, and two people in the fourth house. So, four houses and sixteen people. If I simply choose one of these people at random, then that choice is a selection from among sixteen people, yielding an information entropy of 4 bits for that choice. But now consider a two-step selection in which first I choose one house at random, and then I choose one of the people in the selected house. So the first step, that of picking one house from the four houses available, generates two bits of information entropy. But now, in the 25% of the time that I pick the first house, the second step adds another three bits in the choosing of one person from among the eight people in the first house. In another 25% of the cases, I need only another two bits to select one person from the four that live in the second house. And finally, in fully half of the cases, I need only a single bit to pick one person from the pair that lives in either the third or the fourth house. Somehow, it seems to me, that the weighted average of bit-counts for the two- step approach should generate the same four bit total that the single-step method requires. But I can not get the figures to add up, so clearly there is more to the math than I am considering. I was expecting that you should simply be able to add up the probabilities like so: (picking a house) + (picking a person in that house) == log(4) + [(1/4)*log(8) + (1/4)*log(4) + (1/4)*log(2) + (1/4)*log(2)] But this produces a result of 3.75 bits, and not the 4 bits that I am expecting. Here is a bit of python that I used to evaluate this. from math import log def log2(x): return log(x,2) x = log2(4) + ((1.0/4)*log2(8) + (1.0/4)*log2(4) + (1.0/4)*log2(2) + (1.0/4)*log2(2)) print x So, something is missing from my figures. Can anyone point me in the right direction? Answer: If you choose a house at random (with uniform probability, UP for short), then choose a resident at random (UP), you're _not_ choosing one out of 16 UP -- you have a somewhat skewed distribution, which unsurprisingly yields lower entropy (UP maximizes entropy). Eight people are being selected with a probability of 1/32 each, four are being selected with a probability of 1/16 each, and the other four with a probability of 1/8 each. _This_ distribution has an entropy of 3.75 bits, just as you computed with your different approach.
Count warnings in Python 2.4 Question: I've got some tests that need to count the number of warnings raised by a function. In Python 2.6 this is simple, using with warnings.catch_warnings(record=True) as warn: ... self.assertEquals(len(warn), 2) Unfortunately, `with` is not available in Python 2.4, so what else could I use? I _can't_ simply check if there's been a single warning (using warning filter with `action='error'` and `try`/`catch`), because the number of warnings is significant. Answer: I was going to suggest the same workaround as Ignacio, a bit more complete example of testing code: import warnings def setup_warning_catcher(): """ Wrap warnings.showwarning with code that records warnings. """ caught_warnings = [] original_showwarning = warnings.showwarning def custom_showwarning(*args, **kwargs): caught_warnings.append(args[0]) return original_showwarning(*args, **kwargs) warnings.showwarning = custom_showwarning return caught_warnings caught_warnings_list = setup_warning_catcher() # trigger warning here assert len(caught_warnings_list) == 1
Output of python scripts displayed only at termination when using SSH? Question: I'm running a script to manage processes on a remote (SSH) machine. Let's call it **five.py** #!/usr/bin/python import time, subprocess subprocess.call('echo 0',shell=True) for i in range(1,5): time.sleep(1) print(i) If i now run ssh user@host five.py I would like to see the output 0 1 2 3 4 appear on my standard out second by second (as it does if execute locally).. What happens is: I get the 0 from "echo" right away and the rest only appears at once after the entire program finishes. (Doesn't help to nest 'five.py' into a bash script; to call it by 'python five.py'; or to use 'print >> sys.stdout, i'). This must be related to the way python writes to stdout, since other programs behave quite normal.. A functional workaround is import time, subprocess import sys subprocess.call('echo 0',shell=True) for i in range(1,5): time.sleep(1) sys.stdout.write(str(i)+'\n') sys.stdout.flush() But there must be a better solution than changing all my print statements! Answer: You can add the -u on the shebang line as interjay hinted #!/usr/bin/python -u You could also reopen stdout with buffering turned off or set to line buffering import os,sys sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # no buffering sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1) # line buffering Usually line buffering is a good choice
In SciPy, using ix_() with sparse matrices doesn't seem to work so what else can I use? Question: In Numpy, ix_() is used to grab rows and columns of a matrix, but it doesn't seem to work with sparse matrices. For instance, this code works because it uses a dense matrix: >>> import numpy as np >>> x = np.mat([[1,0,3],[0,4,5],[7,8,0]]) >>> print x [[1 0 3] [0 4 5] [7 8 0]] >>> print x[np.ix_([0,2],[0,2])] [[1 3] [7 0]] I used ix_() to index the elements corresponding with the 0th and 2nd rows and columns which gives the 4 corners of the matrix. The problem is that ix_ doesn't seem to work with sparse matrices. Continuing from the previous code, I try the following: >>> import scipy.sparse as sparse >>> xspar = sparse.csr_matrix(x) >>> print xspar (0, 0) 1 (0, 2) 3 (1, 1) 4 (1, 2) 5 (2, 0) 7 (2, 1) 8 >>> print xspar[np.ix_([0,2],[0,2])] and get a huge error message saying there is this exception: File "C:\Python26\lib\site-packages\scipy\sparse\compressed.py", line 138, in check_format raise ValueError('data, indices, and indptr should be rank 1') ValueError: data, indices, and indptr should be rank 1 I have tried this with the other sparse matrix formats provided by SciPy, but none of them seem to work with ix_() though they don't all raise the same exception. The example I gave used a matrix that wasn't very big or very sparse, but the ones I am dealing with are quite sparse and potentially very large so it doesn't seem prudent to just list off the elements one by one. Does anyone know a (hopefully easy) way to do this sort of indexing with sparse matrices in SciPy or is this feature just not built into these sparse matrices? Answer: Try this instead: >>> print xspar (0, 0) 1 (0, 2) 3 (1, 1) 4 (1, 2) 5 (2, 0) 7 (2, 1) 8 >>> print xspar[[[0],[2]],[0,2]] (0, 0) 1 (0, 2) 3 (2, 0) 7 Note the difference with this: >>> print xspar[[0,2],[0,2]] [[1 0]]
No module named csrf Question: I have: Python 2.6 Django 1.1.1 I downloaded Django-cms from git://github.com/digi604/django-cms-2.0.git I passed south off/on I stuck on this: After enabling south syncdb returns: Synced: > django.contrib.auth > django.contrib.contenttypes > django.contrib.sessions > django.contrib.admin > django.contrib.sites > publisher > mptt > reversion > example.categories > south > example.sampleapp Not synced (use migrations): - cms - cms.plugins.text - cms.plugins.picture - cms.plugins.file - cms.plugins.flash - cms.plugins.link - cms.plugins.snippet - cms.plugins.googlemap - cms.plugins.teaser - cms.plugins.video - cms.plugins.twitter - cms.plugins.inherit (use ./manage.py migrate to migrate these) startserver returns (when I open in browser 127.0.0.1:8000): Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/django/core/servers/basehttp.py", line 279, in run self.result = application(self.environ, self.start_response) File "/usr/lib/pymodules/python2.6/django/core/servers/basehttp.py", line 651, in __call__ return self.application(environ, start_response) File "/usr/lib/pymodules/python2.6/django/core/handlers/wsgi.py", line 230, in __call__ self.load_middleware() File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py", line 42, in load_middleware raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e) ImproperlyConfigured: Error importing middleware django.middleware.csrf: "No module named csrf" [25/Feb/2010 05:49:43] "GET / HTTP/1.1" 500 746 When I commented lines: #'django.middleware.csrf.CsrfViewMiddleware', - in MIDDLEWARE_CLASSES #'django.core.context_processors.csrf', - in TEMPLATE_CONTEXT_PROCESSORS i could run it now, but when I'm trying to add page i see: Template error In template /home/gennadich/Documents/django-cms-2.0/cms/templates/admin/cms/page/change_form.html, error at line 97 Invalid block tag: 'csrf_token' Answer: Now that you've disabled the CSRF modules, you no longer have any CSRF tags available. Either enable the CSRF modules or remove all CSRF tags.
PyGreSQL NULLs for integer field Question: I am trying to insert some rows into a table which has a field of integers, which can be NULL: cur.execute("INSERT INTO mytable (id, priority) VALUES (%(id)d, %(priority)d)", \ {'id': id, 'priority': priority}) The priority variable is either an integer or `None`. This works when priority has an integer value, however, when it is `None` I get the following error: internal error in 'BEGIN': int argument required I notice that for string formatting for Python in general you cannot use `None` as the value of an integer to be formatted - it throws the same error that pgdb is throwing. However, when I change the formatting string to `%(priority)s` the error changes to: internal error in 'BEGIN': unsupported format character 'W' (0x57) at index 60 I guess that's because I'm then trying to import a string into an integer field. How do I import the NULL values? Answer: Normally Postgresql performs automatic casting of string values to integer for integer columns. So it is generally safe to use a string formatter like %(priority)s for an integer column provided the string parameter contains an integer or is None. If the string is set to None then the column will be assigned NULL.
Writing to file doesn't flush content automatically and cause out of memory in Python Question: I made simple python program to generate big text file: import sys import random f = open('data.txt', 'w') for i in range(100000000): f.write(str(i) + "\t" + str(random.randint(0,1000)) + "\n") f.close() When I launch it using CPython it eat all available OS memory and write nothing to the file. When I launch it on Jython I get `OutOfMemoryException`. As far as I understand it stores everything in memory buffer and never did flush before `close()` call. My question is: how to limit the file buffer and trigger autoflush? I don't want to call`flush()` manually, I think it's wrong from performance point of view. I want `flush()` to be called automatically when file buffer is overloaded or so. Thanks! Answer: Buffering is not the problem. The problem is calling the `range()` function with a giant argument, which will attempt to allocate an array with lots of elements. You will get the same error if you just say r = range(100000000)
Why doesn't import prevent NameError in a python script run with execfile()? Question: I looked at a number of existing questions about NameError exceptions when scripts are run with exec statements or execfile() in Python, but haven't found a good explanation yet of the following behavior. I want to make a simple game that creates script objects at runtime with execfile(). Below are 4 modules that demonstrate the problem (please bear with me, this is as simple as I could make it!). The main program just loads a script using execfile() and then calls a script manager to run the script objects: # game.py import script_mgr import gamelib # must be imported here to prevent NameError, any place else has no effect def main(): execfile("script.py") script_mgr.run() main() The script file just creates an object that plays a sound and then adds the object to a list in the script manager: script.py import script_mgr #import gamelib # (has no effect here) class ScriptObject: def action(self): print("ScriptObject.action(): calling gamelib.play_sound()") gamelib.play_sound() obj = ScriptObject() script_mgr.add_script_object(obj) The script manager just calls the action() function of each script: # script_mgr.py #import gamelib # (has no effect here) script_objects = [] def add_script_object(obj): script_objects.append(obj) def run(): for obj in script_objects: obj.action() The gamelib function is defined in a fourth module, which is the troublesome one to be accessed: # gamelib.py def play_sound(): print("boom!") The above code works with the following output: mhack:exec $ python game.py ScriptObject.action(): calling gamelib.play_sound() boom! mhack:exec $ However, if I comment-out the 'import gamelib' statement in game.py and uncomment the 'import gamelib' in script.py, I get the following error: mhack:exec $ python game.py ScriptObject.action(): calling gamelib.play_sound() Traceback (most recent call last): File "game.py", line 10, in main() File "game.py", line 8, in main script_mgr.run() File "/Users/williamknight/proj/test/python/exec/script_mgr.py", line 12, in run obj.action() File "script.py", line 9, in action gamelib.play_sound() NameError: global name 'gamelib' is not defined My question is: 1) Why is the import needed in the 'game.py' module, the one that execs the script? 2) Why doesn't it work to import 'gamelib' from the module where it is referenced (script.py) or the module where it is called (script_mgr.py)? This happens on Python 2.5.1 Answer: From the [Python documentation](http://docs.python.org/library/functions.html#execfile) for execfile: _execfile(filename[, globals[, locals]])_ _If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where execfile() is called._ There are two optional arguments for execfile. Since you omit them both, your script is being executed in the environment where execfile is called. Hence the reason the import in game.py changes the behaviour. In addition, I concluded the following behaviour of import in game.py and script.py: * In game.py `import gamelib` imports the gamelib module into **both globals and locals**. This is the environment passed to script.py which is why gamelib is accessible in the ScriptObject action method (accessed from globals). * In script.py `import gamelib` imports the gamelib module into **locals only** (not sure of the reason). So when trying to access gamelib from the ScriptObject action method from globals you have the NameError. It will work if you move the import into the scope of the action method as follows (gamelib will be accessed from locals): class ScriptObject: def action(self): import gamelib print("ScriptObject.action(): calling gamelib.play_sound()") gamelib.play_sound()
Python: does the set class "leak" when items are removed, like a dict? Question: I know that Python `dict`s will "leak" when items are removed (because the item's slot will be overwritten with the magic "removed" value)… But will the `set` class behave the same way? Is it safe to keep a `set` around, adding and removing stuff from it over time? **Edit** : Alright, I've tried it out, and here's what I found: >>> import gc >>> gc.collect() 0 >>> nums = range(1000000) >>> gc.collect() 0 ### rsize: 20 megs ### A baseline measurement >>> s = set(nums) >>> gc.collect() 0 ### rsize: 36 megs >>> for n in nums: s.remove(n) >>> gc.collect() 0 ### rsize: 36 megs ### Memory usage doesn't drop after removing every item from the set… >>> s = None >>> gc.collect() 0 ### rsize: 20 megs ### … but nulling the reference to the set *does* free the memory. >>> s = set(nums) >>> for n in nums: s.remove(n) >>> for n in nums: s.add(n) >>> gc.collect() 0 ### rsize: 36 megs ### Removing then re-adding keys uses a constant amount of memory… >>> for n in nums: s.remove(n) >>> for n in nums: s.add(n+1000000) >>> gc.collect() 0 ### rsize: 47 megs ### … but adding new keys uses more memory. Answer: Yes, `set` is basically a hash table just like `dict` \-- the differences at the interface don't imply many differences "below" it. Once in a while, you should copy the set -- `myset = set(myset)` \-- just like you should for a dict on which many additions and removals are regularly made over time.
Building an interleaved buffer for pyopengl and numpy Question: I'm trying to batch up a bunch of vertices and texture coords in an interleaved array before sending it to pyOpengl's glInterleavedArrays/glDrawArrays. The only problem is that I'm unable to find a suitably fast enough way to append data into a numpy array. Is there a better way to do this? I would have thought it would be quicker to preallocate the array and then fill it with data but instead, generating a python list and converting it to a numpy array is "faster". Although 15ms for 4096 quads seems slow. I have included some example code and their timings. #!/usr/bin/python import timeit import numpy import ctypes import random USE_RANDOM=True USE_STATIC_BUFFER=True STATIC_BUFFER = numpy.empty(4096*20, dtype=numpy.float32) def render(i): # pretend these are different each time if USE_RANDOM: tex_left, tex_right, tex_top, tex_bottom = random.random(), random.random(), random.random(), random.random() left, right, top, bottom = random.random(), random.random(), random.random(), random.random() else: tex_left, tex_right, tex_top, tex_bottom = 0.0, 1.0, 1.0, 0.0 left, right, top, bottom = -1.0, 1.0, 1.0, -1.0 ibuffer = ( tex_left, tex_bottom, left, bottom, 0.0, # Lower left corner tex_right, tex_bottom, right, bottom, 0.0, # Lower right corner tex_right, tex_top, right, top, 0.0, # Upper right corner tex_left, tex_top, left, top, 0.0, # upper left ) return ibuffer # create python list.. convert to numpy array at end def create_array_1(): ibuffer = [] for x in xrange(4096): data = render(x) ibuffer += data ibuffer = numpy.array(ibuffer, dtype=numpy.float32) return ibuffer # numpy.array, placing individually by index def create_array_2(): if USE_STATIC_BUFFER: ibuffer = STATIC_BUFFER else: ibuffer = numpy.empty(4096*20, dtype=numpy.float32) index = 0 for x in xrange(4096): data = render(x) for v in data: ibuffer[index] = v index += 1 return ibuffer # using slicing def create_array_3(): if USE_STATIC_BUFFER: ibuffer = STATIC_BUFFER else: ibuffer = numpy.empty(4096*20, dtype=numpy.float32) index = 0 for x in xrange(4096): data = render(x) ibuffer[index:index+20] = data index += 20 return ibuffer # using numpy.concat on a list of ibuffers def create_array_4(): ibuffer_concat = [] for x in xrange(4096): data = render(x) # converting makes a diff! data = numpy.array(data, dtype=numpy.float32) ibuffer_concat.append(data) return numpy.concatenate(ibuffer_concat) # using numpy array.put def create_array_5(): if USE_STATIC_BUFFER: ibuffer = STATIC_BUFFER else: ibuffer = numpy.empty(4096*20, dtype=numpy.float32) index = 0 for x in xrange(4096): data = render(x) ibuffer.put( xrange(index, index+20), data) index += 20 return ibuffer # using ctype array CTYPES_ARRAY = ctypes.c_float*(4096*20) def create_array_6(): ibuffer = [] for x in xrange(4096): data = render(x) ibuffer += data ibuffer = CTYPES_ARRAY(*ibuffer) return ibuffer def equals(a, b): for i,v in enumerate(a): if b[i] != v: return False return True if __name__ == "__main__": number = 100 # if random, don't try and compare arrays if not USE_RANDOM and not USE_STATIC_BUFFER: a = create_array_1() assert equals( a, create_array_2() ) assert equals( a, create_array_3() ) assert equals( a, create_array_4() ) assert equals( a, create_array_5() ) assert equals( a, create_array_6() ) t = timeit.Timer( "testing2.create_array_1()", "import testing2" ) print 'from list:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_2()", "import testing2" ) print 'array: indexed:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_3()", "import testing2" ) print 'array: slicing:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_4()", "import testing2" ) print 'array: concat:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_5()", "import testing2" ) print 'array: put:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_6()", "import testing2" ) print 'ctypes float array:', t.timeit(number)/number*1000.0, 'ms' Timings using random numbers: $ python testing2.py from list: 15.0486779213 ms array: indexed: 24.8184704781 ms array: slicing: 50.2214789391 ms array: concat: 44.1691994667 ms array: put: 73.5879898071 ms ctypes float array: 20.6674289703 ms **edit note: changed code to produce random numbers for each render to reduce object reuse and to simulate different vertices each time.** **edit note2: added static buffer and force all numpy.empty() to use dtype=float32** **note 1/Apr/2010: still no progress and I don't really feel that any of the answers have solved the problem yet.** Answer: The reason that create_array_1 is so much faster seems to be that the items in the (python) list all point to the same object. You can see this if you test: print (ibuffer[0] is ibuffer[1]) inside the subroutines. In create_array_1 this is true (before you create the numpy array), while in create_array_2 this is always going to be false. I guess this means that data conversion step in the array conversion only has to happen once in create_array_1, while it happens 4096 times in create_array_2. If this is the reason, I guess the timings will be different if you make render generate random data. Create_array_5 is slowest as it makes a new array each time you add data to the end.
How do I print a line following a line containing certain text in a saved file in Python? Question: I have written a Python program to find the carrier of a cell phone given the number. It downloads the source of [http://www.whitepages.com/carrier_lookup?carrier=other&number_0=1112223333&response=1](http://www.whitepages.com/carrier_lookup?carrier=other&number_0=1112223333&response=1) (where 1112223333 is the phone number to lookup) and saves this as carrier.html. In the source, the carrier is in the line after the [div class="carrier_result"] tag. (switch in < and > for [ and ], as stackoverflow thought I was trying to format using the html and would not display it.) My program currently searches the file and finds the line containing the div tag, but now I need a way to store the next line after that as a string. My current code is: <http://pastebin.com/MSDN0vbC> Answer: What you really want to be doing is parsing the HTML properly. Use the BeautifulSoup library - it's wonderful at doing so. Sample code: import urllib2, BeautifulSoup opener = urllib2.build_opener() opener.addheaders[0] = ('User-agent', 'Mozilla/5.1') response = opener.open('http://www.whitepages.com/carrier_lookup?carrier=other&number_0=1112223333&response=1').read() bs = BeautifulSoup.BeautifulSoup(response) print bs.findAll('div', attrs={'class': 'carrier_result'})[0].next.strip()
Parsing broken XML with lxml.etree.iterparse Question: I'm trying to parse a huge xml file with lxml in a memory efficient manner (ie streaming lazily from disk instead of loading the whole file in memory). Unfortunately, the file contains some bad ascii characters that break the default parser. The parser works if I set recover=True, but the iterparse method doesn't take the recover parameter or a custom parser object. Does anyone know how to use iterparse to parse broken xml? #this works, but loads the whole file into memory parser = lxml.etree.XMLParser(recover=True) #recovers from bad characters. tree = lxml.etree.parse(filename, parser) #how do I do the equivalent with iterparse? (using iterparse so the file can be streamed lazily from disk) context = lxml.etree.iterparse(filename, tag='RECORD') #record contains 6 elements that I need to extract the text from Thanks for your help! EDIT -- Here is an example of the types of encoding errors I'm running into: In [17]: data Out[17]: '\t<articletext>&lt;p&gt;The cafeteria rang with excited voices. Our barbershop quartet, The Bell \r Tones was asked to perform at the local Home for the Blind in the next town. We, of course, were glad to entertain such a worthy group and immediately agreed . One wag joked, "Which uniform should we wear?" followed with, "Oh, that\'s right, they\'ll never notice." The others didn\'t respond to this, in fact, one said that we should wear the nicest outfit we had.&lt;/p&gt;&lt;p&gt;A small stage was set up for us and a pretty decent P.A. system was donated for the occasion. The audience was made up of blind persons of every age, from the thirties to the nineties. Some sported sighted companions or nurses who stood or sat by their side, sharing the moment equally. I observed several German shepherds lying at their feet, adoration showing in their eyes as they wondered what was going on. After a short introduction in which we identified ourselves, stating our voice part and a little about our livelihood, we began our program. Some songs were completely familiar and others, called "Oh, yeah" songs, only the chorus came to mind. We didn\'t mind at all that some sang along \x1e they enjoyed it so much.&lt;/p&gt;&lt;p&gt;In fact, a popular part of our program is when the audience gets to sing some of the old favorites. The harmony parts were quite evident as they tried their voices to the different parts. I think there was more group singing in the old days than there is now, but to blind people, sound and music is more important. We received a big hand at the finale and were made to promise to return the following year. Everyone was treated to coffee and cake, our quartet going around to the different circles of friends to sing a favorite song up close and personal. As we approached a new group, one blind lady amazed me by turning to me saying, "You\'re the baritone, aren\'t you?" Previously no one had ever been able to tell which singer sang which part but this lady was listening with her whole heart.&lt;/p&gt;&lt;p&gt;Retired portrait photographer. Main hobby - quartet singing.&lt;/p&gt;</articletext>\n' In [18]: lxml.etree.from lxml.etree.fromstring lxml.etree.fromstringlist In [18]: lxml.etree.fromstring(data) --------------------------------------------------------------------------- XMLSyntaxError Traceback (most recent call last) /mnt/articles/<ipython console> in <module>() /usr/lib/python2.5/site-packages/lxml-2.2.4-py2.5-linux-i686.egg/lxml/etree.so in lxml.etree.fromstring (src/lxml/lxml.etree.c:48270)() /usr/lib/python2.5/site-packages/lxml-2.2.4-py2.5-linux-i686.egg/lxml/etree.so in lxml.etree._parseMemoryDocument (src/lxml/lxml.etree.c:71812)() /usr/lib/python2.5/site-packages/lxml-2.2.4-py2.5-linux-i686.egg/lxml/etree.so in lxml.etree._parseDoc (src/lxml/lxml.etree.c:70673)() /usr/lib/python2.5/site-packages/lxml-2.2.4-py2.5-linux-i686.egg/lxml/etree.so in lxml.etree._BaseParser._parseDoc (src/lxml/lxml.etree.c:67442)() /usr/lib/python2.5/site-packages/lxml-2.2.4-py2.5-linux-i686.egg/lxml/etree.so in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/lxml.etree.c:63824)() /usr/lib/python2.5/site-packages/lxml-2.2.4-py2.5-linux-i686.egg/lxml/etree.so in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:64745)() /usr/lib/python2.5/site-packages/lxml-2.2.4-py2.5-linux-i686.egg/lxml/etree.so in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:64088)() XMLSyntaxError: PCDATA invalid Char value 30, line 1, column 1190 In [19]: chardet.detect(data) Out[19]: {'confidence': 1.0, 'encoding': 'ascii'} As you can see, chardet thinks it is an ascii file, but there is a "\x1e" right in the middle of this example which is making lxml raise an exception. Answer: The currently accepted answer is, well, not what one should do. The question itself also has a bad assumption: > parser = lxml.etree.XMLParser(recover=True) _#recovers from bad characters._ Actually `recover=True` is for recovering _from misformed XML_. There is however an ["encoding" option](http://lxml.de/parsing.html) which would have fixed your issue. parser = lxml.etree.XMLParser(encoding='utf-8' #Your encoding issue. recover=True, #I assume you probably still want to recover from bad xml, it's quite nice. If not, remove. ) That's it, that's the solution. * * * **BTW --** For anyone struggling with parsing XML in python, especially from third party sources. I know, I know, the documentation is bad and there are a lot of SO red herrings; a lot of bad advice. * **lxml.etree.fromstring()?** \- That's for perfectly formed XML, silly * **BeautifulStoneSoup?** \- Slow, and has a way-stupid policy for self closing tags * **lxml.etree.HTMLParser()?** \- (because the xml is broken) Here's a secret - HTMLParser() is... a Parser with recover=True * **lxml.html.soupparser?** \- The encoding detection is supposed to be better, but it has the same failings of BeautifulSoup for self closing tags. Perhaps you can combine XMLParser with BeautifulSoup's UnicodeDammit * **UnicodeDammit and other cockamamie stuff to fix encodings?** \- Well, UnicodeDammit is kind of cute, I like the name and it's useful for stuff beyond xml, but things are usually fixed if you do the right thing with XMLParser() You could be trying all sorts of stuff from what's available online. lxml documentation could be better. The code above is what you need for 90% of your XML parsing cases. Here I'll restate it: magical_parser = XMLParser(encoding='utf-8', recover=True) tree = etree.parse(StringIO(your_xml_string), magical_parser) #or pass in an open file object You're welcome. My headaches == your sanity. Plus it has other features you might need for, you know, XML.
Running a python script from webpy Question: I setup a lighttpd server along with webpy and fastcgi. I am trying to simply run a python script everytime the wenpy app is accessed. Though it seems even when I give the normal python code to execute the script it does nothing. So Id like to be able to run this script, any idea would be helpful. #!/usr/bin/env python import web, os urls = ( '/(.*)', 'hello' ) app = web.application(urls, globals()) class hello: def GET(self, name): os.system("python /srv/http/script/script.py") if not name: name = 'world' return "Running" web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr) if __name__ == "__main__": app.run() Answer: Assuming your method runs my top concern would be that an error is occurring and you are not getting standard output explaining the problem (os.system will get the return value, e.g. exit code). Python docs recommend replacing it with subprocess, I like to do this: from subprocess import Popen, PIPE proc = Popen('ls', shell=True, stdout=PIPE) proc.wait() proc.communicate()
Serial communication. Sending DTR in the right way? Question: I'm dealing with a [gm29](http://www.icpdas.com/products/GSM_GPRS/wireless/gm29.htm) by Sony Ericsson. The [datasheet](http://www.icpdas.com/download/wireless/gsm/gm29/gm29_tech%20description_r1b.pdf) says that plugging the power is not sufficient to switch on the modem. It says: * activate the RS232 control line DTR, high for > 0.2s. I'm writing some tests in python, but: #!/usr/bin/env python import serial from time import sleep socket = serial.Serial('/dev/ttyS0', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=1, xonxoff=0, rtscts=0 ) socket.setDTR(True) sleep(3) socket.setDTR(False) try: while True: socket.write('AT'+chr(13)); sleep(1) print "Reading" print socket.readlines() except: socket.close() does not works... I there a way to get DTR high in other ways? Let's say minicom or some other stuff? Or, easily, am I missing something? Thanks in advance. * * * Ok, that was driving me mad. The clue is that the power supplier was "broken", or better, it works good testing with a tester, but plugging on the modem some wires moves and does not carry voltage... Thanks anyway for the answer, marked as correct 'couse it was :D Answer: There are several things that occur to me here. 1) the spec says that DTR is active low, so you may need to swap the `true` and `false` values to `setDTR()`, depending on who is confused here. 2) You are setting `DTR` to false after you wake the modem. This tells the modem to go offline, and ignore all input till it goes `true` again. Try the following: import serial from time import sleep conn = serial.Serial('/dev/ttyS0', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=1, xonxoff=0, rtscts=0 ) # Wake Modem conn.setDTR(True) sleep(3) conn.setDTR(False) sleep(5) # Start talking conn.setDTR(True) try: while True: conn.write('AT'+chr(13)); print conn.readline() # readlines() will probably never return. finally: conn.close() 3) `socket` is probably a bad name for your serial connection.
Python - lexical analysis and tokenization Question: I'm looking to speed along my discovery process here quite a bit, as this is my first venture into the world of lexical analysis. Maybe this is even the wrong path. First, I'll describe my problem: I've got very large properties files (in the order of 1,000 properties), which when distilled, are really just about 15 important properties and the rest can be generated or rarely ever change. So, for example: general { name = myname ip = 127.0.0.1 } component1 { key = value foo = bar } This is the type of format I want to create to tokenize something like: property.${general.name}blah.home.directory = /blah property.${general.name}.ip = ${general.ip} property.${component1}.ip = ${general.ip} property.${component1}.foo = ${component1.foo} into property.mynameblah.home.directory = /blah property.myname.ip = 127.0.0.1 property.component1.ip = 127.0.0.1 property.component1.foo = bar Lexical analysis and tokenization sounds like my best route, but this is a very simple form of it. It's a simple grammar, a simple substitution and I'd like to make sure that I'm not bringing a sledgehammer to knock in a nail. I could create my own lexer and tokenizer, or ANTlr is a possibility, but I don't like re-inventing the wheel and ANTlr sounds like overkill. I'm not familiar with compiler techniques, so pointers in the right direction & code would be most appreciated. **Note** : I can change the input format. Answer: There's an excellent article on [Using Regular Expressions for Lexical Analysis](http://effbot.org/zone/xml-scanner.htm) at [effbot.org](http://effbot.org/). Adapting the tokenizer to your problem: import re token_pattern = r""" (?P<identifier>[a-zA-Z_][a-zA-Z0-9_]*) |(?P<integer>[0-9]+) |(?P<dot>\.) |(?P<open_variable>[$][{]) |(?P<open_curly>[{]) |(?P<close_curly>[}]) |(?P<newline>\n) |(?P<whitespace>\s+) |(?P<equals>[=]) |(?P<slash>[/]) """ token_re = re.compile(token_pattern, re.VERBOSE) class TokenizerException(Exception): pass def tokenize(text): pos = 0 while True: m = token_re.match(text, pos) if not m: break pos = m.end() tokname = m.lastgroup tokvalue = m.group(tokname) yield tokname, tokvalue if pos != len(text): raise TokenizerException('tokenizer stopped at pos %r of %r' % ( pos, len(text))) To test it, we do: stuff = r'property.${general.name}.ip = ${general.ip}' stuff2 = r''' general { name = myname ip = 127.0.0.1 } ''' print ' stuff '.center(60, '=') for tok in tokenize(stuff): print tok print ' stuff2 '.center(60, '=') for tok in tokenize(stuff2): print tok for: ========================== stuff =========================== ('identifier', 'property') ('dot', '.') ('open_variable', '${') ('identifier', 'general') ('dot', '.') ('identifier', 'name') ('close_curly', '}') ('dot', '.') ('identifier', 'ip') ('whitespace', ' ') ('equals', '=') ('whitespace', ' ') ('open_variable', '${') ('identifier', 'general') ('dot', '.') ('identifier', 'ip') ('close_curly', '}') ========================== stuff2 ========================== ('newline', '\n') ('identifier', 'general') ('whitespace', ' ') ('open_curly', '{') ('newline', '\n') ('whitespace', ' ') ('identifier', 'name') ('whitespace', ' ') ('equals', '=') ('whitespace', ' ') ('identifier', 'myname') ('newline', '\n') ('whitespace', ' ') ('identifier', 'ip') ('whitespace', ' ') ('equals', '=') ('whitespace', ' ') ('integer', '127') ('dot', '.') ('integer', '0') ('dot', '.') ('integer', '0') ('dot', '.') ('integer', '1') ('newline', '\n') ('close_curly', '}') ('newline', '\n')
Is there a way to specify a fixed (or variable) number of elements for lxml in Python Question: There must be an easier way to do this. I need some text from a large number of html documents. In my tests the most reliable way to find it is to look for specific word in the text_content of the div elements. If I want to inspect a specific element above the one that has my text I have been enumerating my list of div elements and using the index of the one that has my text to then specify a previous one by acting on the index. But I am sure there must be a better way. I can't seem to figure that out. If not clear for pair in enumerate(list_of_elements): if 'the string' in pair[1].text_content(): thelocation=pair[0] the_other_text=list_of_elements[thelocation-9].text_content() or theitem.getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().text_content() Answer: [lxml](http://codespeak.net/lxml/xpathxslt.html#xpath) supports [XPath](http://www.w3.org/TR/xpath/): from lxml import etree root = etree.fromstring("...your xml...") el, = root.xpath("//div[text() = 'the string']/preceding-sibling::*[9]")
How to delete all blank lines in the file with the help of python? Question: For example, we have some file like that: > first line > second line > > third line And in result we have to get: > first line > second line > third line Use ONLY python Answer: import fileinput for line in fileinput.FileInput("file",inplace=1): if line.rstrip(): print line
How do I calculate percentiles with python/numpy? Question: Is there a convenient way to calculate percentiles for a sequence or single- dimensional numpy array? I am looking for something similar to Excel's percentile function. I looked in NumPy's statistics reference, and couldn't find this. All I could find is the median (50th percentile), but not something more specific. Answer: You might be interested in the [SciPy Stats](http://docs.scipy.org/doc/scipy/reference/stats.html) package. It has [the percentile function](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.scoreatpercentile.html#scipy.stats.scoreatpercentile) you're after and many other statistical goodies. `percentile()` [is available](http://docs.scipy.org/doc/numpy/reference/generated/numpy.percentile.html) in `numpy` too. import numpy as np a = np.array([1,2,3,4,5]) p = np.percentile(a, 50) # return 50th percentile, e.g median. print p 3.0 ~~[This ticket](http://projects.scipy.org/numpy/ticket/626) leads me to believe they won't be integrating `percentile()` into numpy anytime soon.~~
Getting rid of Django IOErrors Question: I'm running a Django site (via Apache/mod_python) and I use Django's facilities to inform me and other developers about internal server errors. Sometimes errors like those appear: Traceback (most recent call last): File "/opt/webapp/externals/lib/django/core/handlers/base.py", line 92, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/opt/webapp/csite/apps/customers/views.py", line 29, in feedback form = FeedbackForm(request.POST) File "/opt/webapp/externals/lib/django/core/handlers/modpython.py", line 113, in _get_post self._load_post_and_files() File "/opt/webapp/externals/lib/django/core/handlers/modpython.py", line 96, in _load_post_and_files self._post, self._files = http.QueryDict(self.raw_post_data, encoding=self._encoding), datastructures.MultiValueDict() File "/opt/webapp/externals/lib/django/core/handlers/modpython.py", line 163, in _get_raw_post_data self._raw_post_data = self._req.read() IOError: Client read error (Timeout?) As far as I found out, those `IOError`s are generated by clients that disconnect in the wrong moment and that it's not a problem of my site. If that is the case: Can I disable the emails for those errors somehow? I really don't want to know about errors that I cannot fix and that aren't really errors. Answer: Extending the solution by @dlowe for Django 1.3, we can write the full working example as: # settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'supress_unreadable_post': { '()': 'common.logging.SuppressUnreadablePost', } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'filters': ['supress_unreadable_post'], } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } # common/logging.py import sys, traceback class SuppressUnreadablePost(object): def filter(self, record): _, exception, tb = sys.exc_info() if isinstance(exception, IOError): for _, _, function, _ in traceback.extract_tb(tb): if function == '_get_raw_post_data': return False return True
pybabel or other l10n libraries for PHP Question: [Babel or pybabel](http://babel.edgewall.org/) is an interface to the CLDR (Common Locale Data Repository) in Python. As such, it has the same 'knowledge' as PHP's i18n functions and classes (if the appropriate locales are installed on the host), but without the hassle of using process-wide settings like `setlocale()`. Is there a similar library or toolkit for PHP? Especially to achieve: 1. converting numbers to and fro language and region specific formats 2. converting dates likewise 3. accessing names, monetary and other information in a certain locale (like, e.g. >>> from babel import Locale >>> locale = Locale('en', 'US') >>> locale.territories['US'] u'United States' >>> locale = Locale('es', 'MX') >>> locale.territories['US'] u'Estados Unidos' Answer: PHP 5.3 comes with [intl](http://www.php.net/manual/en/book.intl.php) extension: > Internationalization extension (further is referred as Intl) is a wrapper > for ICU library, enabling PHP programmers to perform UCA-conformant > collation and date/time/number/currency formatting in their scripts. 1. Converting numbers is possible with _NumberFormatter_ class: $fmt = new NumberFormatter("de_DE", NumberFormatter::DECIMAL); echo $fmt->format(1234567.891234567890000); 2. Converting dates is possible with _IntlDateFormatter_ class: $fmt = new IntlDateFormatter("en_US", IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'America/Los_Angeles', IntlDateFormatter::GREGORIAN); echo $fmt->format(0); 3. Accessing names, monetary and other information in a certain locale is possible with _Locale_ class: echo Locale::getRegion('de-CH-1901'); In addition, there are _Collation_ and _MessageFormatter_ classes.
wsdl2py ComplexTypes Question: How do I add complex types to a SOAP request? I'm using WSDL2py generated requests, and trying to use the other TypeDefinitions that it made in the _*_ _types.py file (like AccountInfo, for authentication, that goes into every request). Then passing it the wsdl2py generated server, and I'm getting this error: >>> from AutomotiveDescriptionService6_client import * >>> from AutomotiveDescriptionService6_types import * >>> loc = AutomotiveDescriptionService6Locator() >>> server = loc.getAutomotiveDescriptionService6Port() >>> request = getDataVersions() >>> auth = ns0.AccountInfo_Def() >>> auth._accountName="**" >>> auth._accountSecret="***" >>> request._accountInfo = auth >>> server.getDataVersions(request) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "AutomotiveDescriptionService6_client.py", line 38, in getDataVersions self.binding.Send(None, None, request, soapaction="", **kw) File "/usr/lib/pymodules/python2.6/ZSI/client.py", line 246, in Send sw.serialize(obj, tc) File "/usr/lib/pymodules/python2.6/ZSI/writer.py", line 117, in serialize elt = typecode.serialize(self.body, self, pyobj, **kw) File "/usr/lib/pymodules/python2.6/ZSI/TC.py", line 609, in serialize pyobj.typecode.serialize(elt, sw, pyobj, **kw) File "/usr/lib/pymodules/python2.6/ZSI/TCcompound.py", line 275, in serialize self.cb(elt, sw, pyobj, name=name, **kw) File "/usr/lib/pymodules/python2.6/ZSI/TCcompound.py", line 424, in cb what.serialize(elem, sw, v, **kw) File "/usr/lib/pymodules/python2.6/ZSI/TCcompound.py", line 275, in serialize self.cb(elt, sw, pyobj, name=name, **kw) File "/usr/lib/pymodules/python2.6/ZSI/TCcompound.py", line 437, in cb sw.Backtrace(elt)) ZSI.EvaluateException: Got None for nillable(False), minOccurs(1) element (urn:description6.kp.chrome.com,accountNumber), <ns1:accountInfo xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ZSI="http://www.zolera.com/schemas/ZSI/" xmlns:ns1="urn:description6.kp.chrome.com" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></ns1:accountInfo> [Element trace: /SOAP-ENV:Body/ns1:DataVersionsRequest] As you can see, it's easy to generate request objects, wsdl2py uses GED() to give us those, but it DOESN'T expose the classes that those requests need. For the life of me, I can't figure out how the hell to get that complex type properly into the request object, without getting that error. I've been trying to instantiate the definition in the **_types.py file, and I've been trying just plain dicts. NOTHING seems to work. Here's what the auto-generated definition looks like, any suggestions? class ns0: targetNamespace = "urn:description6.kp.chrome.com" class AccountInfo_Def(ZSI.TCcompound.ComplexType, TypeDefinition): schema = "urn:description6.kp.chrome.com" type = (schema, "AccountInfo") def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw): ns = ns0.AccountInfo_Def.schema TClist = [ZSI.TC.String(pname=(ns,"accountNumber"), aname="_accountNumber", minOccurs=1, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded")), ZSI.TC.String(pname=(ns,"accountSecret"), aname="_accountSecret", minOccurs=1, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded")), GTD("urn:description6.kp.chrome.com","Locale",lazy=False)(pname=(ns,"locale"), aname="_locale", minOccurs=1, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded"))] self.attribute_typecode_dict = attributes or {} if extend: TClist += ofwhat if restrict: TClist = ofwhat ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw) class Holder: typecode = self def __init__(self): # pyclass self._accountNumber = None self._accountSecret = None return Holder.__name__ = "AccountInfo_Holder" self.pyclass = Holder Answer: So... found out that the problem is I needed to run wsdl2py with the --complextypes flag.This creates a whole slew of awesome methods inside of the reqeust object. methods like new_XXXXX where X is the name of the complex type that's required by that request.
Better way to script USB device mount in Linux Question: I'm writing a python module for a device that interacts with a user supplied USB memory stick. The user can insert a USB memory stick in the device USB slot, and the device will dump data onto the memory stick without user intervention. If the device is running when the user inserts the USB stick, I have hooked into D-Bus and have an auto mount routine all worked out. The new issue is, what if the stick is inserted while the device is powered off? I get no D-Bus insertion event, or any the associated nuggets of information about the memory stick after the device is powered on. I have worked out a way to derive the device node ( /dev/sd? ) from scanning the USB devices in /proc, by calling: `ls /proc/scsi/usb-storage` this gives the scsi device info if you cat each of the files in that folder. I then take the Vendor, Product, and Serial Number fields from the usb-storage records, generate an identifier string that I then use in `ll /dev/disc/by-id/usb_[vendor]`_[product]`_[serial_number]-0:0` So I can parse through the result to get the relative path `../../sdc` Then, I can mount the USB stick. This is a cumbersome procedure, pretty much all text based, and ready for bugs when someone introduces a weird character, or non-standard serial number string. It works with all 2 of the USB memory sticks I own. I have tried to map output from /var/log/messages but that ends up being text comparisons as well. Output from lsusb, fdisk, udevinfo, lsmod, and others only show half of the required data. My question: how do I determine, in the absence of a D-Bus message, the /dev device assigned to a USB memory stick without user intervention, or knowing in advance the specifics of the inserted device? Thanks, sorry about the novel. Answer: This seems to work combining `/proc/partitions` and the `/sys/class/block` approach ephimient took. #!/usr/bin/python import os partitionsFile = open("/proc/partitions") lines = partitionsFile.readlines()[2:]#Skips the header lines for line in lines: words = [x.strip() for x in line.split()] minorNumber = int(words[1]) deviceName = words[3] if minorNumber % 16 == 0: path = "/sys/class/block/" + deviceName if os.path.islink(path): if os.path.realpath(path).find("/usb") > 0: print "/dev/%s" % deviceName I'm not sure how portable or reliable this is, but it works for my USB stick. Of course `find("/usb")` could be made into a more rigorous regular expression. Doing mod 16 may also not be the best approach to find the disk itself and filter out the partitions, but it works for me so far.
HyperTreeList index out of range issue? Question: When i tried to run the following code. I am getting error. import wx from wx.lib.agw.hypertreelist import HyperTreeList class test(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, title='htl', size=(955,550)) self.CenterOnScreen() self.tree = HyperTreeList(self, style = wx.TR_FULL_ROW_HIGHLIGHT | wx.TR_HAS_VARIABLE_ROW_HEIGHT) # create columns self.tree.AddColumn("c1", 120) self.tree.AddColumn("c1") self.tree.AddColumn("c3", 120) self.tree.AddColumn("c4") self.tree.AddColumn("c5") self.tree.AddColumn("c6") self.tree.AddColumn("c7") self.tree.AddColumn("c8") self.tree.AddColumn("c9") root = self.tree.AddRoot("root") rc = self.tree.AppendItem(root, "child1") rc2 = self.tree.AppendItem(root, "child2") gauge = wx.Gauge(self.tree.GetMainWindow(), -1, 100, style=wx.GA_HORIZONTAL|wx.GA_SMOOTH) gauge.SetValue(25) *#can we add this value over/within gauge control/window* gauge.SetDimensions(100, 100, 100, 20) self.tree.SetItemWindow(rc2, gauge, 7) #here is problem self.tree.Expand(root) #end def #end test class App(wx.App): """Application class.""" def OnInit(self): self.frame = test() self.frame.Show() self.SetTopWindow(self.frame) return True def main(): app = App() app.MainLoop() if __name__ == '__main__': main() i got this error Traceback (most recent call last): File "/root/workspace/test/src/test.py", line 61, in <module> main() File "/root/workspace/test/src/test.py", line 57, in main app = App() File "/usr/lib/python2.6/site-packages/wx-2.8-gtk2-unicode/wx/_core.py", line 7974, in __init__ self._BootstrapApp() File "/usr/lib/python2.6/site-packages/wx-2.8-gtk2-unicode/wx/_core.py", line 7548, in _BootstrapApp return _core_.PyApp__BootstrapApp(*args, **kwargs) File "/root/workspace/test/src/test.py", line 51, in OnInit self.frame = test() File "/root/workspace/test/src/test.py", line 39, in __init__ self.tree.SetItemWindow(rc2, gauge, 7) File "/usr/lib/python2.6/site-packages/wx-2.8-gtk2-unicode/wx/lib/agw/hypertreelist.py", line 3282, in delegate return getattr(self._main_win, method)(*args, **kwargs) File "/usr/lib/python2.6/site-packages/wx-2.8-gtk2-unicode/wx/lib/agw/hypertreelist.py", line 1414, in SetItemWindow item.SetWindow(window, column) File "/usr/lib/python2.6/site-packages/wx-2.8-gtk2-unicode/wx/lib/agw/hypertreelist.py", line 1055, in SetWindow self._wnd[column] = wnd IndexError: list assignment index out of range What i am doing wrong? _Second, can we add percentage number within gauge control._ Regards, Answer: this a known bug that's fixed in SVN -- <http://trac.wxwidgets.org/ticket/11708> Download <http://svn.wxwidgets.org/svn/wx/wxPython/3rdParty/AGW/agw/hypertreelist.py> and use it in your application directly instead of using the one inside wx.
Python string decoding issue Question: I am trying to parse a CSV file containing some data, mostly numeral but with some strings - which I do not know their encoding, but I do know they are in Hebrew. Eventually I need to know the encoding so I can unicode the strings, print them, and perhaps throw them into a database later on. I tried using [Chardet](http://chardet.feedparser.org), which claims the strings are Windows-1255 (`cp1255`) but trying to do `print someString.decode('cp1255')` yields the notorious error: UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4: ordinal not in range(128) I tried every other encoding possible, to no avail. Also, the file is absolutely valid since I can open the CSV in Excel and I see the correct data. Any idea how I can properly decode these strings? * * * **EDIT:** here is an example. One of the strings looks like this (first five letters of the Hebrew alphabet): print repr(sampleString) #prints: '\xe0\xe1\xe2\xe3\xe4' (using Python 2.6.2) Answer: This is what's happening: * sampleString is a byte string (cp1255 encoded) * `sampleString.decode("cp1255")` decodes (decode==bytes -> unicode string) the byte string to a unicode string * `print sampleString.decode("cp1255")` attempts to print the unicode string to stdout. Print has to **encode** the unicode string to do that (encode==unicode string -> bytes). The error that you're seeing means that the python print statement cannot write the given unicode string to the console's encoding. `sys.stdout.encoding` is the terminal's encoding. So the problem is that your console does not support these characters. You should be able to tweak the console to use another encoding. The details on how to do that depends on your OS and terminal program. Another approach would be to manually specify the encoding to use: print sampleString.decode("cp1255").encode("utf-8") See also: * <http://wiki.python.org/moin/PrintFails> * <http://stackoverflow.com/questions/492483/setting-the-correct-encoding-when-piping-stdout-in-python> A simple test program you can experiment with: import sys print sys.stdout.encoding samplestring = '\xe0\xe1\xe2\xe3\xe4' print samplestring.decode("cp1255").encode(sys.argv[1]) On my utf-8 terminal: $ python2.6 test.py utf-8 UTF-8 אבגדה $ python2.6 test.py latin1 UTF-8 Traceback (most recent call last): UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-4: ordinal not in range(256) $ python2.6 test.py ascii UTF-8 Traceback (most recent call last): UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128) $ python2.6 test.py cp424 UTF-8 ABCDE $ python2.6 test.py iso8859_8 UTF-8 ����� The error messages for latin-1 and ascii means that the unicode characters in the string cannot be represented in these encodings. Notice the last two. I encode the unicode string to the cp424 and iso8859_8 encodings (two of the encodings listed on <http://docs.python.org/library/codecs.html#standard-encodings> that supports hebrew characters). I get no exception using these encodings, since the hebrew unicode characters have a representation in the encodings. But my utf-8 terminal gets very confused when it receives bytes in a different encoding than utf-8. In the first case (cp424), my UTF-8 terminal displays ABCDE, meaning that the utf-8 representation of A corresponds to the cp424 representation of ה, i.e. the byte value 65 means A in utf-8 and ה in cp424. The `encode` method has an optional string argument you can use to specify what should happen when the encoding cannot represent a character ([documentation](http://docs.python.org/library/codecs.html#codec-base- classes)). The supported strategies are strict (the default), ignore, replace, xmlcharref and backslashreplace. You can even [add your own custom strategies](http://docs.python.org/library/codecs.html#codecs.register_error). Another test program (I print with quotes around the string to better show how ignore behaves): import sys samplestring = '\xe0\xe1\xe2\xe3\xe4' print "'{0}'".format(samplestring.decode("cp1255").encode(sys.argv[1], sys.argv[2])) The results: $ python2.6 test.py latin1 strict Traceback (most recent call last): File "test.py", line 4, in <module> sys.argv[2])) UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-4: ordinal not in range(256) [/tmp] $ python2.6 test.py latin1 ignore '' [/tmp] $ python2.6 test.py latin1 replace '?????' [/tmp] $ python2.6 test.py latin1 xmlcharrefreplace '&#1488;&#1489;&#1490;&#1491;&#1492;' [/tmp] $ python2.6 test.py latin1 backslashreplace '\u05d0\u05d1\u05d2\u05d3\u05d4'
Python: File formatting Question: I have a for loop which references a dictionary and prints out the value associated with the key. Code is below: for i in data: if i in dict: print dict[i], How would i format the output so a new line is created every 60 characters? and with the character count along the side for example: > 0001 MRQLLLISDLDNTWVGDQQALEHLQEYLGDRRGNFYLAYATGRSYHSARELQKQVGLMEP > 0061 DYWLTAVGSEIYHPEGLDQHWADYLSEHWQRDILQAIADGFEALKPQSPLEQNPWKISYH > 0121 LDPQACPTVIDQLTEMLKETGIPVQVIFSSGKDVDLLPQRSNKGNATQYLQQHLAMEPSQ Answer: It's a finicky formatting problem, but I think the following code: import sys class EveryN(object): def __init__(self, n, outs): self.n = n # chars/line self.outs = outs # output stream self.numo = 1 # next tag to write self.tll = 0 # tot chars on this line def write(self, s): while True: if self.tll == 0: # start of line: emit tag self.outs.write('%4.4d ' % self.numo) self.numo += self.n # wite up to N chars/line, no more numw = min(len(s), self.n - self.tll) self.outs.write(s[:numw]) self.tll += numw if self.tll >= self.n: self.tll = 0 self.outs.write('\n') s = s[numw:] if not s: break if __name__ == '__main__': sys.stdout = EveryN(60, sys.stdout) for i, a in enumerate('abcdefgh'): print a*(5+ i*5), shows how to do it -- the output when running for demonstration purposes as the main script (five a's, ten b's, etc, with spaces in-between) is: 0001 aaaaa bbbbbbbbbb ccccccccccccccc dddddddddddddddddddd eeeeee 0061 eeeeeeeeeeeeeeeeeee ffffffffffffffffffffffffffffff ggggggggg 0121 gggggggggggggggggggggggggg hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh 0181 hhhhhhh
Load huge data to memory using python Question: I have to load large data to the memory, and the structure is list. How can I get another approach. thanx Answer: process the data line by line, eg for line in open("file"): print "do processing of line:",line Or if you really really want to load one whole chunk to memory, you can try memory mapping. import mmap,os,re bigfile = open( "file2" ) length = os.stat(bigfile.fileno()).st_size try: mapping = mmap.mmap(bigfile.fileno(), length, mmap.MAP_PRIVATE, mmap.PROT_READ ) except AttributeError: mapping = mmap.mmap(bigfile.fileno(), 0, None, mmap.ACCESS_READ ) data = mapping.read(length) # example, finding a pattern pat =re.compile("pattern",re.M|re.DOTALL) print pat.findall(data)
Linking a qtDesigner .ui file to python/pyqt? Question: So if I go into QtDesigner and build a UI, it'll be saved as a .ui file. How can I make this as a python file or use this in python? Answer: Another way to use .ui in your code is: from PyQt4 import QtCore, QtGui, uic class MyWidget(QtGui.QWidget) ... #somewhere in constructor: uic.loadUi('MyWidget.ui', self) both approaches are good. Do not forget, that if you use Qt resource files (extremely useful) for icons and so on, you must compile it too: pyrcc4.exe -o ui/images_rc.py ui/images/images.qrc Note, when `uic` compiles interface, it adds 'import images_rc' at the end of .py file, so you must compile resources into the file with this name, or rename it in generated code.
Does filehandle get closed automatically in Python after it goes out of scope? Question: If I do the following, does filehandle get closed automatically as it goes out of scope in Python: def read_contents(file_path): return file(file_path).read() If it doesn't, how can I write this function to close the scope automatically? Answer: To expand on FogleBird's answer, if you do not explicitly close it then the file will be closed automatically when the file object is destroyed. In CPython this will happen as soon as there are no more references to it, e.g. if it is a local variable in a function and the function ends. However if an exception is thrown in the function and file is not explicitly closed using a `with` statement or a `try:...finally:` then a reference to the file will be kept as part of the stack trace in the traceback object and the file will not be closed, at least until the next exception is thrown. Also IronPython and Jython use the garbage collection facilities of the .Net CLR and Java JVM respectively. These are not reference counted, so the file will remain open indefinitely until the garbage collector decides to reclaim the object's memory or the program terminates. So in general it is important to explicitly close the file using either `with:` or `try:...finally:`. Of course all this is holds true for any other type of object that requires explicit cleanup.
Python nonblocking console input Question: I am trying to make a simple IRC client in Python (as kind of a project while I learn the language). I have a loop that I use to receive and parse what the IRC server sends me, but if I use `raw_input` to input stuff, it stops the loop dead in its tracks until I input something (obviously). How can I input something without the loop stopping? Thanks in advance. (I don't think I need to post the code, I just want to input something without the _while 1_ loop stopping.) EDIT: I'm on Windows. Answer: For Windows, console only, use the [`msvcrt`](http://www.python.org/doc/2.5.2/lib/msvcrt-console.html) module: import msvcrt num = 0 done = False while not done: print num num += 1 if msvcrt.kbhit(): print "you pressed",msvcrt.getch(),"so now i will quit" done = True For Linux, this [article](http://www.darkcoding.net/software/non-blocking- console-io-is-not-possible/) describes the following solution, it requires the `termios` module: import sys import select import tty import termios def isData(): return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []) old_settings = termios.tcgetattr(sys.stdin) try: tty.setcbreak(sys.stdin.fileno()) i = 0 while 1: print i i += 1 if isData(): c = sys.stdin.read(1) if c == '\x1b': # x1b is ESC break finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings) For cross platform, or in case you want a GUI as well, you can use Pygame: import pygame from pygame.locals import * def display(str): text = font.render(str, True, (255, 255, 255), (159, 182, 205)) textRect = text.get_rect() textRect.centerx = screen.get_rect().centerx textRect.centery = screen.get_rect().centery screen.blit(text, textRect) pygame.display.update() pygame.init() screen = pygame.display.set_mode( (640,480) ) pygame.display.set_caption('Python numbers') screen.fill((159, 182, 205)) font = pygame.font.Font(None, 17) num = 0 done = False while not done: display( str(num) ) num += 1 pygame.event.pump() keys = pygame.key.get_pressed() if keys[K_ESCAPE]: done = True
why does python.subprocess hang after proc.communicate()? Question: I've got an interactive program called `my_own_exe`. First, it prints out `alive`, then you input `S\n` and then it prints out `alive` again. Finally you input `L\n`. It does some processing and exits. However, when I call it from the following python script, the program seemed to hang after printing out the first 'alive'. Can anyone here tell me why this is happening? // after reading the follow ups (thank you guys), i modified the code as following: import subprocess import time base_command = "./AO_FelixStrategy_UnitTest --bats 31441 --chix 12467 --enxutp 31884 --turq 26372 --symbol SOGN --target_date " + '2009-Oct-16' print base_command proc2 = subprocess.Popen(base_command, shell=True , stdin=subprocess.PIPE,) time.sleep(2); print "aliv" proc2.communicate('S\n') print "alive" time.sleep(6) print "alive" print proc2.communicate('L\n') time.sleep(6) the program now goes well with the first input 'S\n', but then stopped, and I the second 'L\n' is kinda ignored. Can anyone give me an idea why it's like this? Answer: From the [docs for `communicate`](http://docs.python.org/library/subprocess#subprocess.Popen.communicate): > Interact with process: Send data to stdin. Read data from stdout and stderr, > until end-of-file is reached. **Wait for process to terminate.** So after `communicate()` runs, the process has been **terminated**. If you want to write and read without waiting for the process to stop: * Don't **ever** use `shell=True` \- it needlessy invokes a shell to in turn call your program, so there will be another process between you and your program. That has lots of unpleasant side-effects. The default is `shell=False` so you should stick with that. Change your `Popen` line to: p = subprocess.Popen(["./AO_FelixStrategy_UnitTest", "--bats", "31441", "--chix", "12467", "--enxutp", "31884", "--turq", "26372", "--symbol", "SOGN", "--target_date", '2009-Oct-16'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) * Use `p.stdin.write` to write to the process. Use `p.stdout.read` to read from it. * Calling `p.stdout.read` if there's nothing to read will block. Calling `p.stdin.write` if the write buffer is full will block. So you have to make sure you have something to read/write - you do that on unix OS by using `select`. On windows you unfortunately must resort to threads. At least that is what `Popen.communicate` does internally. * If you didn't write `AO_FelixStrategy_UnitTest` then you have possible additional problems: * It could be reading from somewhere else, not standard input. Some programs read directly from the terminal, others use some OS API to read. That means data written to stdin won't go to the program. This is often true for password prompts. * Remember that you have to account for `AO_FelixStrategy_UnitTest` buffers. By default standard C PIPE communication is buffered so you may not see any output until after you've closed the input side (by doing `p.stdin.close()`. Unless `AO_FelixStrategy_UnitTest` flushes the output periodically. Here's some example code, based on what you describe. It could work depending on how `AO_FelixStrategy_UnitTest` was developed: p = subprocess.Popen(["./AO_FelixStrategy_UnitTest", "--bats", "31441", "--chix", "12467", "--enxutp", "31884", "--turq", "26372", "--symbol", "SOGN", "--target_date", '2009-Oct-16'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) output = p.communicate('S\nL\n')[0] print output
how to get data from csv file in python Question: I am using csv.reader to read file but it giving me whole file. file_data = self.request.get('file_in'); file_Reader = csv.reader( file_data ); for fields in file_Reader: I want one line at a time and separate data from that line. ex: filedata = name,sal,dept x,12000,it o\p= name sal dept . . . Answer: This >>> import csv >>> spamReader = csv.reader(open('eggs.csv'), delimiter=' ', quotechar='|') >>> for row in spamReader: ... print ', '.join(row) Spam, Spam, Spam, Spam, Spam, Baked Beans Spam, Lovely Spam, Wonderful Spam Was taken from [the manual](http://docs.python.org/library/csv.html) Hope that helps...
How to only pay the dependency penalty for the implementation you use in Python? Question: I have a fairly simple set of functionality for which I have multiple implementations, e.g., a datastore that could be backed by Redis, MongoDB, or PostgreSQL. How should I structure/write my code so that code that wants to use one of these implementations only needs the dependencies for that implementation, e.g., they don't need to have `psycopg2` installed if they are using the Redis backend. Here's an example. Assume the following module, `example.py`. class RedisExample(object): try: import redis except ImportError: print("You need to install redis-py.") def __init__(self): super(RedisExample, self).__init__() class UnsatisfiedExample(object): try: import flibbertigibbet except ImportError: print("You need to install flibbertigibbet-py") def __init__(self): super(UnsatisfiedExample, self).__init__() Here's my Python shell experience: >>> import example You need to install flibbertigibbet-py Alternately: >>> from example import RedisExample You need to install flibbertigibbet-py I'd really rather I didn't get that error until I tried to instantiate an `UnsatisfiedExample`. Is there any sort of common way to approach this problem? I've thought about making `example` a package with each backend getting its own module and using a factory function, but I wanted to make sure I wasn't missing something better. Thanks. Answer: Can't you simply put the `import` statement in the `__init__` method of each class? Then it won't be run until you try to make an instance: class UnsatisfiedExample(object): def __init__(self): try: import flibbertigibbet except ImportError: raise RuntimeError("You need to install flibbertigibbet-py") super(UnsatisfiedExample, self).__init__()
Error in gui programming in python using tkinter Question: #!/usr/bin/python # -*- coding: iso-8859-1 -*- import Tkinter class simpleapp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent=parent def initialize(self): self.grid() self.entry=Tkinter.Entry(self) self.entry.grid(column=0,row=0,sticky='EW') self.entry.bind("<Return>",self.OnPressEnter) button=Tkinter.Button(self,test="Post it!",command=self.OnButtonClick) button.grid(column=1,row=0) label=Tkinter.Label(self,anchor="w",fg="white",bg="blue") label=grid(column=0,row=1,columnspan=2,sticky='EW') self.grid_columnconfigure(0,weight=1) def OnButtonClick(self): print "you clicked the button!" def OnPressEnter(self,event): print "you pressed enter!" if __name__=="__main__": app=simpleapp_tk(None) app.title('poster') app.mainloop() I wrote this program so as to make a box to input text and a button, but it shows nothing apart from a window. Where is the error? Answer: The main issue was that you forgot to call `app.initialize()`, but you also had a couple of typos. I've pointed out where in the comments in this fixed version. import Tkinter class simpleapp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent=parent def initialize(self): self.grid() self.entry=Tkinter.Entry(self) self.entry.grid(column=0,row=0,sticky='EW') self.entry.bind("<Return>",self.OnPressEnter) button=Tkinter.Button(self,text="Post it!",command=self.OnButtonClick) # the text keyword argument was mis-typed as 'test' button.grid(column=1,row=0) label=Tkinter.Label(self,anchor="w",fg="white",bg="blue") label.grid(column=0,row=1,columnspan=2,sticky='EW') # the . in label.grid was mis-typed as '=' self.grid_columnconfigure(0,weight=1) def OnButtonClick(self): print "you clicked the button!" def OnPressEnter(self,event): print "you pressed enter!" if __name__=="__main__": app=simpleapp_tk(None) app.title('poster') app.initialize() # you forgot this app.mainloop()
Testing warnings with doctest Question: I'd like to use [doctests](http://docs.python.org/library/doctest.html) to test the presence of certain warnings. For example, suppose I have the following module: from warnings import warn class Foo(object): """ Instantiating Foo always gives a warning: >>> foo = Foo() testdocs.py:14: UserWarning: Boo! warn("Boo!", UserWarning) >>> """ def __init__(self): warn("Boo!", UserWarning) If I run `python -m doctest testdocs.py` to run the doctest in my class and make sure that the warning is printed, I get: testdocs.py:14: UserWarning: Boo! warn("Boo!", UserWarning) ********************************************************************** File "testdocs.py", line 7, in testdocs.Foo Failed example: foo = Foo() Expected: testdocs.py:14: UserWarning: Boo! warn("Boo!", UserWarning) Got nothing ********************************************************************** 1 items had failures: 1 of 1 in testdocs.Foo ***Test Failed*** 1 failures. It looks like the warning is getting printed but not captured or noticed by doctest. I'm guessing that this is because warnings are printed to `sys.stderr` instead of `sys.stdout`. But this happens even when I say `sys.stderr = sys.stdout` at the end of my module. So is there any way to use doctests to test for warnings? I can find no mention of this one way or the other in the documentation or in my Google searching. Answer: The [Testing Warnings](http://docs.python.org/library/warnings.html#testing- warnings) sections of the Python documentation is dedicated to this topic. However, to summarize, you have two options: ## (A) Use the `catch_warnings` context manager This is recommended course in the official documentation. However, the `catch_warnings` context manager only came into existence with Python 2.6. import warnings def fxn(): warnings.warn("deprecated", DeprecationWarning) with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") # Trigger a warning. fxn() # Verify some things assert len(w) == 1 assert issubclass(w[-1].category, DeprecationWarning) assert "deprecated" in str(w[-1].message) ## (B) Upgrade Warnings to Errors If the warning hasn't been seen before-- and thus was registered in the warnings registry-- then you can set warnings to raise exceptions and catch it. import warnings def fxn(): warnings.warn("deprecated", DeprecationWarning) if __name__ == '__main__': warnings.simplefilter("error", DeprecationWarning) try: fxn() except DeprecationWarning: print "Pass" else: print "Fail" finally: warnings.simplefilter("default", DeprecationWarning)
OSX : Defining a new URL handler that points straight at a Python script Question: I'm trying to define a new URL handler under OSX that will point at a python script. I've wrapped the Python script up into an applet (right-clicked on the .py, and gone Open With -> Build Applet) I've added the following into the applet's Info.plist: <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLName</key> <string>Do My Thing</string> <key>CFBundleURLSchemes</key> <array> <string>dmt</string> </array> </dict> </array> I've also used the [More Internet preferences pane](http://www.monkeyfood.com/software/moreInternet/) to specify "dmt" as a protocol, but when I try to get it to link the protocol to my applet, it says that "There was a problem setting the app as the helper" Anyone know where I should go from here? Thanks Answer: After a lot of messing around, I've managed to get this working under OSX... This is how I'm doing it: in the AppleScript Script Editor, write the following script: on open location this_URL do shell script "/scripts/runLocalCommand.py '" & this_URL & "'" end open location If you want to make sure you're running the Python from a certain shell (in my case, I'm using tcsh generally, and have a .tcshrc file that defines some environment variables that I want to have access to) then that middle line might want to be: do shell script "tcsh -c \"/scripts/localCommand.py '" & this_URL & "'\"" I was wanting to do all of my actual processing inside a python script - but because of the way URL handers work in OSX, they have to call an application bundle rather than a script, so doing this in AppleScript seemed to be the easiest way to do it. in the Script Editor, Save As an "Application Bundle" Find the saved Application Bundle, and Open Contents. Find the Info.plist file, and open it. Add the following: <key>CFBundleIdentifier</key> <string>com.mycompany.AppleScript.LocalCommand</string> <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLName</key> <string>LocalCommand</string> <key>CFBundleURLSchemes</key> <array> <string>local</string> </array> </dict> </array> Just before the last two lines, which should be: </dict> </plist> There are three strings in there that might want to be changed: com.mycompany.AppleScript.LocalCommand LocalCommand local The third of these is the handler ID - so a URL would be local://something So, then this passes over to the Python script. This is what I've got for this: #!/usr/bin/env python import sys import urllib arg = sys.argv[1] handler, fullPath = arg.split(":", 1) path, fullArgs = fullPath.split("?", 1) action = path.strip("/") args = fullArgs.split("&") params = {} for arg in args: key, value = map(urllib.unquote, arg.split("=", 1)) params[key] = value
Uneditable file and Unreadable(for further processing) file( WHY? ) after processing it through C++ Program Question: :) This might look to be a very long question to you I understand, but trust me on this its not long. I am not able to identify why after processing this text is not being able to be read and edited. I tried using the ord() function in python to check if the text contains any Unicode characters( non ascii characters) apart from the ascii ones.. I found quite a number of them. I have a strong feeling that this could be due to the original text itself( The INPUT ). Input-File: Just copy paste it into a file "[acle5v1.txt](http://paste.pocoo.org/show/188252/)" The objective of this code below is to check for upper case characters and to convert it to lower case and also to remove all punctuations so that these words are taken for further processing for word alignment #include<iostrea> #include<fstream> #include<ctype.h> #include<cstring> using namespace std; ifstream fin2("acle5v1.txt"); ofstream fin3("acle5v1_op.txt"); ofstream fin4("chkcharadded.txt"); ofstream fin5("chkcharntadded.txt"); ofstream fin6("chkprintchar.txt"); ofstream fin7("chknonasci.txt"); ofstream fin8("nonprinchar.txt"); int main() { char ch,ch1; fin2.seekg(0); fin3.seekp(0); int flag = 0; while(!fin2.eof()) { ch1=ch; fin2.get(ch); if (isprint(ch))// if the character is printable flag = 1; if(flag) { fin6<<"Printable character:\t"<<ch<<"\t"<<(int)ch<<endl; flag = 0; } else { fin8<<"Non printable character caught:\t"<<ch<<"\t"<<int(ch)<<endl; } if( isalnum(ch) || ch == '@' || ch == ' ' )// checks for alpha numeric characters { fin4<<"char added: "<<ch<<"\tits ascii value: "<<int(ch)<<endl; if(isupper(ch)) { //tolower(ch); fin3<<(char)tolower(ch); } else { fin3<<ch; } } else if( ( ch=='\t' || ch=='.' || ch==',' || ch=='#' || ch=='?' || ch=='!' || ch=='"' || ch != ';' || ch != ':') && ch1 != ' ' ) { fin3<<' '; } else if( (ch=='\t' || ch=='.' || ch==',' || ch=='#' || ch=='?' || ch=='!' || ch=='"' || ch != ';' || ch != ':') && ch1 == ' ' ) { //fin3<<" '; } else if( !(int(ch)>=0 && int(ch)<=127) ) { fin5<<"Char of ascii within range not added: "<<ch<<"\tits ascii value: "<<int(ch)<<endl; } else { fin7<<"Non ascii character caught(could be a -ve value also)\t"<<ch<<int(ch)<<endl; } } return 0; } I have a **similar** code as the above written in python which gives me an otput which is again not readable and not editable The code in python looks like this: #!/usr/bin/python # -*- coding: UTF-8 -*- import sys input_file=sys.argv[1] output_file=sys.argv[2] list1=[] f=open(input_file) for line in f: line=line.strip() #line=line.rstrip('.') line=line.replace('.','') line=line.replace(',','') line=line.replace('#','') line=line.replace('?','') line=line.replace('!','') line=line.replace('"','') line=line.replace('।','') line=line.replace('|','') line = line.lower() list1.append(line) f.close() f1=open(output_file,'w') f1.write(' '.join(list1)) f1.close() the file takes ip and op at runtime.. as: python punc_remover.py acle5v1.txt acle5v1_op.txt The output of this file is in "acle5v1_op.txt" now after processing this particular output file is needed for further processing. This particular file "aclee5v1_op.txt" is the UNREADABLE Aand UNEDITABLE File that I am not being able to use for further processing. I need this for Word alignment in NLP. I tried readin this output with the following program #include<iostream> #include<fstream> using namespace std; ifstream fin1("acle5v1_op.txt"); ofstream fout1("chckread_acle5v1_op.txt"); ofstream fout2("chcknotread_acle5v1_op.txt"); int main() { char ch; int flag = 0; long int r = 0; long int nr = 0; while(!(fin1)) { fin1.get(ch); if(ch) { flag = 1; } if(flag) { fout1<<ch; flag = 0; r++; } else { fout2<<"Char not been able to be read from source file\n"; nr++; } } cout<<"Number of characters able to be read: "<<r; cout<<endl<<"Number of characters not been able to be read: "<<nr; return 0; } which prints the character if its readable and if not it doesn't print them but I observed the output of both the file is blank thus I could draw a conclusion that this file "acle5v1_op.txt" is UNREADABLE AND UNEDITABLE. Could you please help me on how to deal with this problem.. To tell you a bit about the statistics wrt the original input file "acle5v1.txt" file it has around 3441 lines in it and around 3 million characters in it. Keeping in mind the number of characters in the file you editor might/might not be able to manage to open the file.. I was able to open the file in gedit of Fedora 10 which I am currently using .. This is just to notify you that opening with a particular editor was not actually an issue at least in my case... Can I use scripting languages like Python and Perl to deal with this problem if Yes how? could please be specific on that regard as I am a novice to Perl and Python. Or could you please tell me how do I solve this problem using C++ itself.. Thank you...:) I am really looking forward to some help or guidance on how to go about this problem.... Answer: (now i can reply, after taking some time editing the post. when posting, please use the preview and read the help !) There is no problem Python cannot tackle... and this problam can definitely be solved using python. After modifying a bit your python script (indentation is messed up !), i was able to process the content i could copy from your link, the output was fine (but still containing some punctuation like ':' and '()'). you say that after the first processing step, the output is unreadable and uneditable, but what is the content of the output file after processing ? did you try opening it in your editor and see what was in the file ? if this first step is not working, then correct your code at the first step and focus your question on this first step. try using a debugger to see where your code fails. personally, i suspect an encoding problem: is your input file a pure ascii file ? or could it be that it is encoded in unicode ? please note that a 3MB file is not much. if this is posing some problems to you, change your editor ! (try jEdit, epsilon, emacs, vi...)
How to look ahead one element in a Python generator? Question: I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone. Here is what I mean: gen = iter([1,2,3]) next_value = gen.next() # okay, I looked forward and see that next_value = 1 # but now: list(gen) # is [2, 3] -- the first value is gone! Here is a more real example: gen = element_generator() if gen.next_value() == 'STOP': quit_application() else: process(gen.next()) Can anyone help me write a generator that you can look one element forward? Thanks, Boda Cydo. Answer: The Python generator API is one way: You can't push back elements you've read. But you can create a new iterator using the [itertools module](http://docs.python.org/library/itertools.html) and prepend the element: import itertools gen = iter([1,2,3]) peek = gen.next() print list(itertools.chain([peek], gen))
Java equivalent for database schema changes like South for Django? Question: I've been working on a Django project using South to track and manage database schema changes. I'm starting a new Java project using Google Web Toolkit and wonder if there is an equivalent tool. For those who don't know, here's what South does: * Automatically recognize changes to my Python database models (add/delete columns, tables etc.) * Automatically create SQL statements to apply those changes to my database * Track the applied schema migrations and apply them in order * Allow data migrations using Python code. For example, splitting a name field into a first-name and last-name field using the Python split() function I haven't decided on my Java ORM yet, but Hibernate looks like the most popular. For me, the ability to easily make database schema changes will be an important factor. Answer: Wow, South sounds pretty awesome! I'm not sure of anything out-of-the-box that will help you nearly as much as that does, however if you choose Hibernate as your ORM solution you can build your own incremental data migration suite without a lot of trouble. Here was the approach that I used in my own project, it worked fairly well for me for over a couple of years and several updates/schema changes: 1. Maintain a schema_version table in the database that simply defines a number that represents the version of your database schema. This table can be handled outside of the scope of Hibernate if you wish. 2. Maintain the "current" version number for your schema inside your code. 3. When the version number in code is newer than what's the database, you can use Hibernate's SchemaUpdate utility which will detect any schema additions (NOTE, just additions) such as new tables, columns, and constraints. 4. Finally I maintained a "script" if you will of migration steps that were more than just schema changes that were identified by which schema version number they were required for. For instance new columns needed default values applied or something of that nature. This may sounds like a lot of work, especially when coming from an environment that took care of a lot of it for you, but you can get a setup like this rolling pretty quickly with Hibernate and it is pretty easy to add onto as you go on. I never ended up making any changes to my incremental update framework over that time except to add new migration tasks. Hopefully someone will come along with a good answer for a more "hands-off" approach, but I thought I'd share an approach that worked pretty well for me. Good luck to you!
How do I add my own custom attributes to existing built-in Python types? Like a string? Question: I want to do something like this... def helloWorld(): print "Hello world!" str.helloWorld = helloWorld "foo".helloWorld() Which would print out "Hello world!" EDIT: Refer to [Can I add custom methods/attributes to built-in Python types?](http://stackoverflow.com/questions/4698493/can-i-add-custom-methods- attributes-to-built-in-python-types) Answer: On CPython you can use ctypes to access the C-API of the interpreter, this way you can change builtin types at runtime. import ctypes as c class PyObject_HEAD(c.Structure): _fields_ = [ ('HEAD', c.c_ubyte * (object.__basicsize__ - c.sizeof(c.c_void_p))), ('ob_type', c.c_void_p) ] _get_dict = c.pythonapi._PyObject_GetDictPtr _get_dict.restype = c.POINTER(c.py_object) _get_dict.argtypes = [c.py_object] def get_dict(object): return _get_dict(object).contents.value def my_method(self): print 'tada' get_dict(str)['my_method'] = my_method print ''.my_method() Although this is interesting to look at and may be quite interesting to figure out... **don't** ever use it in productive code. Just subclass the builtin type or try to figure out if there is another, may be more pythonic, approach to your problem.
How to get the list of price offers on an item from Amazon with python-amazon-product-api item_lookup function? Question: I am trying to write a function to get a list of offers (their prices) for an item based on the ASIN: def price_offers(asin): from amazonproduct import API, ResultPaginator, AWSError from config import AWS_KEY, SECRET_KEY api = API(AWS_KEY, SECRET_KEY, 'de') str_asin = str(asin) node = api.item_lookup(id=str_asin, ResponseGroup='Offers', Condition='All', MerchantId='All') for a in node: print a.Offer.OfferListing.Price.FormattedPrice I am reading <http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/index.html?ItemLookup.html> and trying to make this work, but all the time it just says: Failure instance: Traceback: <type 'exceptions.AttributeError'>: no such child: {http://webservices.amazon.com/AWSECommerceService/2009-10-01}Offer Answer: Seems like there is no Offer element in your response. Try node = api.item_lookup(...) from lxml import etree print etree.tostring(node, pretty_print=True) to see how the returned XML looks like.
Change Name of Import in Java, or import two classes with the same name Question: In Python you can do a: from a import b as c How would you do this in Java, as I have two imports that are clashing. Answer: There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified. Import one class and use the fully qualified name for the other one, i.e. import com.text.Formatter; private Formatter textFormatter; private com.json.Formatter jsonFormatter;
Any way to assign terminal output to variable with python? Question: I need to grab the duration of a video file via python as part of a larger script. I know I can use ffmpeg to grab the duration, but I need to be able to save that output as a variable back in python. I thought this would work, but it's giving me a value of 0: cmd = 'ffmpeg -i %s 2>&1 | grep "Duration" | cut -d \' \' -f 4 | sed s/,//' % ("Video.mov") duration = os.system(cmd) print duration Am I doing the output redirect wrong? Or is there simply no way to pipe the terminal output back into python? Answer: `os.system` returns a return value indicating the success or failure of the command. It does not return the output from stdout or stderr. To grab the output from stdout (or stderr), use `subprocess.Popen`. import subprocess proc=subprocess.Popen('echo "to stdout"', shell=True, stdout=subprocess.PIPE, ) output=proc.communicate()[0] print output See the wonderfully written [Python Module of the Week blog](http://www.doughellmann.com/PyMOTW/subprocess/).
decrypt excel files Question: Hi I have 1000 encrypted workbooks which I would like to decrypt by providing a pwd. I could not find a decrypt method under apache poi or python's xlrd module. Does anyone know a library which could handle this (`wbc.decrypt(pwd)`). I would prefer a lib i could you use from a unix box. Thanks Answer: Use the COM bindings to call the `Unprotect` method. import win32com.client excel = win32com.client.Dispatch('Excel.Application') workbook = excel.Workbooks.open(r'c:\mybook.xls', 'password') workbook.SaveAs('unencrypted.xls') SaveAs can apply a new password. See: <http://msdn.microsoft.com/en- us/library/microsoft.office.tools.excel.workbook.saveas%28VS.80%29.aspx>
Normalising book titles - Python Question: I have a list of books titles: * "The Hobbit: 70th Anniversary Edition" * "The Hobbit" * "The Hobbit (Illustrated/Collector Edition)[There and Back Again]" * "The Hobbit: or, There and Back Again" * "The Hobbit: Gift Pack" and so on... * * * I thought that if I normalised the titles somehow, it would be easier to implement an automated way to know what book each edition is referring to. normalised = ''.join([char for char in title if char in (string.ascii_letters + string.digits)]) or normalised = '' for char in title: if char in ':/()|': break normalised += char return normalised But obviously they are not working as intended, as titles can contain special characters and editions can basically have very different title layouts. * * * Help would be very much appreciated! Thanks :) Answer: It depends completely on your data. For the examples you gave, a simple normalization solution could be: import re book_normalized = re.sub(r':.*|\[.*?\]|\(.*?\)|\{.*?\}', '', book_name).strip() This will return "The Hobbit" for all the examples. What it does is remove anything after and including the first colon, or anything in brackets (normal, square, curly) as well as leading and trailing spaces. However, this is not a very good solution in the general case, as some books have colons or bracketed parts in the actual book name. E.g. the name of the series, followed by a colon, followed by the name of the particular entry of the series.
Python importing Question: I have a file, `myfile.py`, which imports `Class1` from `file.py` and `file.py` contains imports to different classes in `file2.py`, `file3.py`, `file4.py`. In my `myfile.py`, can I access these classes or do I need to again import file2.py, file3.py, etc.? Does Python automatically add all the imports included in the file I imported, and can I use them automatically? Answer: Best practice is to import every module that defines identifiers you need, and use those identifiers as _qualified_ by the module's name; I recommend using `from` only when what you're importing is a module from within a package. The question has often been discussed on SO. Importing a module, say `moda`, from many modules (say `modb`, `modc`, `modd`, ...) that need one or more of the identifiers `moda` defines, does not slow you down: `moda`'s bytecode is loaded (and possibly build from its sources, if needed) only once, the first time `moda` is imported anywhere, then all other imports of the module use a fast path involving a cache (a dict mapping module names to module objects that is accessible as `sys.modules` in case of need... if you first `import sys`, of course!-).
python FancyURLopener timeout Question: is there a way to set connection timeout for FancyURLopener()? I'm using FancyURLopener.retrieve() to download a file, but sometimes it just stucks and that's all... I think this is because it's still trying to connect and it's not possible. So is there a way to set that timeout? Thanks for every reply Answer: If you want to use `retrieve()` with a timeout, you can set it in the `socket` module. import socket socket.setdefaulttimeout(5) Source: <http://docs.python.org/py3k/howto/urllib2.html#sockets-and-layers>
Twisted: why is it that passing a deferred callback to a deferred thread makes the thread blocking all of a sudden? Question: I unsuccessfully tried using txredis (the non blocking twisted api for redis) for a persisting message queue I'm trying to set up with a scrapy project I am working on. I found that although the client was not blocking, it became much slower than it could have been because what should have been one event in the reactor loop was split up into thousands of steps. So instead, I tried making use of redis-py (the regular blocking twisted api) and wrapping the call in a deferred thread. It works great, however I want to perform an inner deferred when I make a call to redis as I would like to set up connection pooling in attempts to speed things up further. Below is my interpretation of some sample code taken from the twisted docs for a deferred thread to illustrate my use case: #!/usr/bin/env python from twisted.internet import reactor,threads from twisted.internet.task import LoopingCall import time def main_loop(): print 'doing stuff in main loop.. do not block me!' def aBlockingRedisCall(): print 'doing lookup... this may take a while' time.sleep(10) return 'results from redis' def result(res): print res def main(): lc = LoopingCall(main_loop) lc.start(2) d = threads.deferToThread(aBlockingRedisCall) d.addCallback(result) reactor.run() if __name__=='__main__': main() And here is my alteration for connection pooling that makes the code in the deferred thread blocking : #!/usr/bin/env python from twisted.internet import reactor,defer from twisted.internet.task import LoopingCall import time def main_loop(): print 'doing stuff in main loop.. do not block me!' def aBlockingRedisCall(x): if x<5: #all connections are busy, try later print '%s is less than 5, get a redis client later' % x x+=1 d = defer.Deferred() d.addCallback(aBlockingRedisCall) reactor.callLater(1.0,d.callback,x) return d else: print 'got a redis client; doing lookup.. this may take a while' time.sleep(10) # this is now blocking.. any ideas? d = defer.Deferred() d.addCallback(gotFinalResult) d.callback(x) return d def gotFinalResult(x): return 'final result is %s' % x def result(res): print res def aBlockingMethod(): print 'going to sleep...' time.sleep(10) print 'woke up' def main(): lc = LoopingCall(main_loop) lc.start(2) d = defer.Deferred() d.addCallback(aBlockingRedisCall) d.addCallback(result) reactor.callInThread(d.callback, 1) reactor.run() if __name__=='__main__': main() So my question is, does anyone know why my alteration causes the deferred thread to be blocking and/or can anyone suggest a better solution? Answer: Well, as the [twisted docs](http://twistedmatrix.com/documents/current/core/howto/gendefer.html) say: > Deferreds do not make the code magically not block Whenever you're using blocking code, such as `sleep`, you have to defer it to a new thread. #!/usr/bin/env python from twisted.internet import reactor,defer, threads from twisted.internet.task import LoopingCall import time def main_loop(): print 'doing stuff in main loop.. do not block me!' def aBlockingRedisCall(x): if x<5: #all connections are busy, try later print '%s is less than 5, get a redis client later' % x x+=1 d = defer.Deferred() d.addCallback(aBlockingRedisCall) reactor.callLater(1.0,d.callback,x) return d else: print 'got a redis client; doing lookup.. this may take a while' def getstuff( x ): time.sleep(3) return "stuff is %s" % x # getstuff is blocking, so you need to push it to a new thread d = threads.deferToThread(getstuff, x) d.addCallback(gotFinalResult) return d def gotFinalResult(x): return 'final result is %s' % x def result(res): print res def aBlockingMethod(): print 'going to sleep...' time.sleep(10) print 'woke up' def main(): lc = LoopingCall(main_loop) lc.start(2) d = defer.Deferred() d.addCallback(aBlockingRedisCall) d.addCallback(result) reactor.callInThread(d.callback, 1) reactor.run() if __name__=='__main__': main() In case the redis api is not very complex it might be more natural to rewrite it using twisted.web, instead of just calling the blocking api in a lot threads.
Django: CharField with fixed length, how? Question: I wold like to have in my model a CharField with fixed length. In other words I want that only a specified length is valid. I tried to do something like volumenumber = models.CharField('Volume Number', max_length=4, min_length=4) but it gives me an error (it seems that I can use both max_length and min_length at the same time). Is there another quick way? Thanks EDIT: Following the suggestions of some people I will be a bit more specific: My model is this: class Volume(models.Model): vid = models.AutoField(primary_key=True) jid = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal") volumenumber = models.CharField('Volume Number') date_publication = models.CharField('Date of Publication', max_length=6, blank=True) class Meta: db_table = u'volume' verbose_name = "Volume" ordering = ['jid', 'volumenumber'] unique_together = ('jid', 'volumenumber') def __unicode__(self): return (str(self.jid) + ' - ' + str(self.volumenumber)) What I want is that the `volumenumber` must be exactly 4 characters. I.E. if someone insert '4b' django gives an error because it expects a string of 4 characters. So I tried with volumenumber = models.CharField('Volume Number', max_length=4, min_length=4) but it gives me this error: Validating models... Unhandled exception in thread started by <function inner_run at 0x70feb0> Traceback (most recent call last): File "/Library/Python/2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Python/2.5/site-packages/django/core/management/validation.py", line 28, in get_validation_errors for (app_name, error) in get_app_errors().items(): File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 131, in get_app_errors self._populate() File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 58, in _populate self.load_app(app_name, True) File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 74, in load_app models = import_module('.models', app_name) File "/Library/Python/2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Users/Giovanni/src/djangoTestSite/../djangoTestSite/journaldb/models.py", line 120, in <module> class Volume(models.Model): File "/Users/Giovanni/src/djangoTestSite/../djangoTestSite/journaldb/models.py", line 123, in Volume volumenumber = models.CharField('Volume Number', max_length=4, min_length=4) TypeError: __init__() got an unexpected keyword argument 'min_length' That obviously doesn't appear if I use only "max_length" OR "min_length". I read the documentation on the django web site and it seems that I'm right (I cannot use both together) so I'm asking if there is another way to solve the problem. Thanks again Answer: You don't even have to write a costum one. Just use the RegexValidator which Django supllies. from django.core.validators import RegexValidator class MyModel(models.Model): myfield = models.CharField(validators=[RegexValidator(regex='^.{4}$', message='Length has to be 4', code='nomatch')]) From the Django Docs: [`class RegexValidator(\[regex=None, message=None, code=None\])`](https://docs.djangoproject.com/en/dev/ref/validators/#regexvalidator) `regex`: A valid regular expression to match. For more on regex in Python check this excellent HowTo: <http://docs.python.org/howto/regex.html> `message`: The message returned to the user in case of failure. `code`: error code returned by ValidationError. Not important for your usage case, you can leave it out. Watch out, the regex suggested by me will allow any characters including whitespace. To allow only alphanumeric characters, substitute the '.' with '\w' in the regex argument. For other requirements, ReadTheDocs ;).
Cannot turn off autocommit in a script using the Django ORM Question: I have a command line script that uses the Django ORM and MySQL backend. I want to turn off autocommit and commit manually. For the life of me, I cannot get this to work. Here is a pared down version of the script. A row is inserted into testtable every time I run this and I get this warning from MySQL: "Some non-transactional changed tables couldn't be rolled back". #!/usr/bin/python import os import sys django_dir = os.path.abspath(os.path.normpath(os.path.join(os.path.dirname(__file__), '..'))) sys.path.append(django_dir) os.environ['DJANGO_DIR'] = django_dir os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' from django.core.management import setup_environ from myproject import settings setup_environ(settings) from django.db import transaction, connection cursor = connection.cursor() cursor.execute('SET autocommit = 0') cursor.execute('insert into testtable values (\'X\')') cursor.execute('rollback') I also tried placing the insert in a function and adding Django's commit_manually wrapper, like so: @transaction.commit_manually def myfunction(): cursor = connection.cursor() cursor.execute('SET autocommit = 0') cursor.execute('insert into westest values (\'X\')') cursor.execute('rollback') myfunction() I also tried setting DISABLE_TRANSACTION_MANAGEMENT = True in settings.py, with no further luck. I feel like I am missing something obvious. Any help you can give me is greatly appreciated. Thanks! Answer: Are your tables MyISAM or InnoDB? Remember that MyISAM isn't transactional, so can't be rolled back. See for example [this page](http://dev.mysql.com/doc/refman/5.1/en/ansi-diff-transactions.html) in the MySQL documentation: > In transactional terms, MyISAM tables effectively always operate in > autocommit = 1 mode.
Python 'datetime.datetime' object is unsubscriptable Question: First, I am NOT a python developer. I am trying to fix an issue within a python script that is being executed from the command line. This script was written by someone who is no longer around, and no longer willing to help with issues. This is python 2.5, and for the moment it cannot be upgraded. Here are the lines of code in question: start_time = datetime.strptime(str(paf.Start),"%Y-%m-%d %H:%M:%S") dict_start = datetime(*start_time[:6]) end_time = datetime.strptime(str(paf.End),"%Y-%m-%d %H:%M:%S") dict_end = datetime(*end_time[:6]) When this code is ran, it generates an error with the description: 'datetime.datetime' object is unsubscriptable. This is the import statement: from datetime import datetime I have a feeling that this is something simple, but not being my native language and Google not yielding any valuable results, I am stuck. I have tried a couple of different import methods, yielding different errors, but all with these statements. Any help on this would be greatly appreciated. Answer: It looks like you just want the time right? The datetime.strptime method returns a 'datetime' object and as such the following attributes contain the time: datetime.day, datetime.hour, datetime.year, etc.
Character encoding for US Census Cartographic Boundary Files Question: I'm trying to import the US Census cartographic boundary files (available here: <http://www.census.gov/geo/www/cob/bdy_files.html> ) into a GeoDjango application. However, python is complaining about UnicodeDecodeErrors (for example, for the non-ascii characters in Puerto Rico). The shapefile description file (*.dbf) doesn't specify what character encoding it uses; this is not defined by the spec for shapefiles. What is the correct character encoding to use? Answer: I was having the same issue with CBSA and Place data from 2010 Census full geometry shapes. These are not the clipped carto files. IBM850 Did not work correctly for me. On a whim, I tried latin1 and it worked perfectly.
Inconsistency in modified/created/accessed time on mac Question: I'm having trouble using `os.utime` to correctly set the modification time on the mac (Mac OS X 10.6.2, running Python 2.6.1 from `/usr/bin/python`). It's not consistent with the `touch` utility, and it's not consistent with the properties displayed in the Finder's "get info" window. Consider the following command sequence. The 'created' and 'modified' times in the plain text refer to the attributes shown in the "get info" window in the finder. As a reminder, [os.utime](http://docs.python.org/library/os.html#os.utime) takes arguments `(filename, (atime, mtime))`. >>> import os >>> open('tempfile','w').close() 'created' and 'modified' are both the current time. >>> os.utime('tempfile', (1000000000, 1500000000) ) 'created' is the current time, 'modified' is July 13, 2017. >>> os.utime('tempfile', (1000000000, 1000000000) ) 'created' and 'modified' are both September 8, 2001. >>> os.path.getmtime('tempfile') 1000000000.0 >>> os.path.getctime('tempfile') 1269021939.0 >>> os.path.getatime('tempfile') 1269021951.0 ...but the `os.path.get?time` and `os.stat` don't reflect it. >>> os.utime('tempfile', (1500000000, 1000000000) ) 'created' and 'modified' are _still_ both September 8, 2001. >>> os.utime('tempfile', (1500000000, 1500000000) ) 'created' is September 8, 2001, 'modified' is July 13, 2017. I'm not sure if this is a Python problem or a Mac stat problem. When I exit the Python shell and run touch -a -t 200011221234 tempfile neither the modification nor the creation times are changed, as expected. Then I run touch -m -t 200011221234 tempfile and both 'created' and 'modified' times are changed. Does anyone have any idea what's going on? How do I change the modification and creation times consistently on the mac? (Yes, I am aware that on Unixy systems there is no "creation time.") * * * Result from running Chris Johnsen's script: seth@local:~$ /usr/bin/python timetest.py tempfile 5 initial: (1269631281.0, 1269631281.0, 1269631281.0, 1269631281, 1269631281, 1269631281) test: (1000000000, 1000000000) (1000000000.0, 1000000000.0, 1269631281.0, 1000000000, 1000000000, 1269631281) (1269631281.0, 1000000000.0, 1269631281.0, 1269631281, 1000000000, 1269631281) test: (1000000000, 1500000000) (1000000000.0, 1500000000.0, 1269631286.0, 1000000000, 1500000000, 1269631286) (1269631286.0, 1500000000.0, 1269631286.0, 1269631286, 1500000000, 1269631286) test: (1500000000, 1000000000) (1500000000.0, 1000000000.0, 1269631291.0, 1500000000, 1000000000, 1269631291) (1269631291.0, 1000000000.0, 1269631291.0, 1269631291, 1000000000, 1269631291) test: (1500000000, 1500000000) (1500000000.0, 1500000000.0, 1269631296.0, 1500000000, 1500000000, 1269631296) (1269631296.0, 1500000000.0, 1269631296.0, 1269631296, 1500000000, 1269631296) At the end of the exercise, the 'created' date as visible in the finder is 9/8/01 and the 'modified' date is 7/13/17. (The access date, thanks to presumably spotlight as you suggest and as I've read about, is roughly 'now.') The created and modified dates visible in the finder still make no sense. Answer: # POSIX _atime_ , _mtime_ , _ctime_ It might help if you included a full script and its actual and expected outputs instead of the REPL fragments. import sys, os, stat, time def get_times(p): s = os.stat(p) return ( os.path.getatime(p), os.path.getmtime(p), os.path.getctime(p), s[stat.ST_ATIME], s[stat.ST_MTIME], s[stat.ST_CTIME], ) def main(p, delay=1): delay = float(delay) (a,b) = (1000000000, 1500000000) open(p,'w').close() print 'initial:' print get_times(p) for t in [ (a,a), (a,b), (b,a), (b,b) ]: print print 'test:', t os.utime(p,t) print get_times(p) time.sleep(delay) print get_times(p) main(*sys.argv[1:]) I get this on my 10.4 system with `cd "$HOME" && python test.py tempfile 5` (system default Python 2.3.6 and MacPorts Python 2.6.4 both give the same result (leaving out the initial times and _ctime_ , of course)): % python /tmp/test.py tempfile 5 initial: (1000000000.0, 1000000000.0, 1269629881.0, 1000000000, 1000000000, 1269629881) test: (1000000000, 1000000000) (1000000000.0, 1000000000.0, 1269629881.0, 1000000000, 1000000000, 1269629881) (1000000000.0, 1000000000.0, 1269629881.0, 1000000000, 1000000000, 1269629881) test: (1000000000, 1500000000) (1000000000.0, 1500000000.0, 1269629886.0, 1000000000, 1500000000, 1269629886) (1000000000.0, 1500000000.0, 1269629886.0, 1000000000, 1500000000, 1269629886) test: (1500000000, 1000000000) (1500000000.0, 1000000000.0, 1269629891.0, 1500000000, 1000000000, 1269629891) (1500000000.0, 1000000000.0, 1269629891.0, 1500000000, 1000000000, 1269629891) test: (1500000000, 1500000000) (1500000000.0, 1500000000.0, 1269629896.0, 1500000000, 1500000000, 1269629896) (1500000000.0, 1500000000.0, 1269629896.0, 1500000000, 1500000000, 1269629896) That seems reasonable. I wonder what you get. I have heard that Spotlight can sometimes aggressively reset _atime_ due to re-indexing changed files. I would not expect it to re-index a file that has only undergone utime()/utimes(), but I suppose it is possible. To eliminate Spotlight as a possible complication use a file in a location that is not indexed by Spotlight (e.g. /tmp/testfile). # Date Created in _Finder_ (shown as “Created:” in Get Info windows of Finder) If you have the Developer tools installed, you can use `/Developer/Tools/GetFileInfo` to see the HFS creationDate. I added the following lines after every `print get_times(p)` line: sys.stdout.flush() os.system('/Developer/Tools/GetFileInfo ' + p) I also changed the iteration to match your initial description (`[ (a,b), (a,a), (b,a), (b,b) ]`). The result now looks like this: % rm /tmp/tempfile; python /tmp/test.py /tmp/tempfile 1 initial: (1269636574.0, 1269636574.0, 1269636574.0, 1269636574, 1269636574, 1269636574) file: "/private/tmp/tempfile" type: "" creator: "" attributes: avbstclinmedz created: 03/26/2010 15:49:34 modified: 03/26/2010 15:49:34 test: (1000000000, 1500000000) (1000000000.0, 1500000000.0, 1269636574.0, 1000000000, 1500000000, 1269636574) file: "/private/tmp/tempfile" type: "" creator: "" attributes: avbstclinmedz created: 03/26/2010 15:49:34 modified: 07/13/2017 21:40:00 (1000000000.0, 1500000000.0, 1269636574.0, 1000000000, 1500000000, 1269636574) file: "/private/tmp/tempfile" type: "" creator: "" attributes: avbstclinmedz created: 03/26/2010 15:49:34 modified: 07/13/2017 21:40:00 test: (1000000000, 1000000000) (1000000000.0, 1000000000.0, 1269636576.0, 1000000000, 1000000000, 1269636576) file: "/private/tmp/tempfile" type: "" creator: "" attributes: avbstclinmedz created: 09/08/2001 20:46:40 modified: 09/08/2001 20:46:40 (1000000000.0, 1000000000.0, 1269636576.0, 1000000000, 1000000000, 1269636576) file: "/private/tmp/tempfile" type: "" creator: "" attributes: avbstclinmedz created: 09/08/2001 20:46:40 modified: 09/08/2001 20:46:40 test: (1500000000, 1000000000) (1500000000.0, 1000000000.0, 1269636577.0, 1500000000, 1000000000, 1269636577) file: "/private/tmp/tempfile" type: "" creator: "" attributes: avbstclinmedz created: 09/08/2001 20:46:40 modified: 09/08/2001 20:46:40 (1500000000.0, 1000000000.0, 1269636577.0, 1500000000, 1000000000, 1269636577) file: "/private/tmp/tempfile" type: "" creator: "" attributes: avbstclinmedz created: 09/08/2001 20:46:40 modified: 09/08/2001 20:46:40 test: (1500000000, 1500000000) (1500000000.0, 1500000000.0, 1269636578.0, 1500000000, 1500000000, 1269636578) file: "/private/tmp/tempfile" type: "" creator: "" attributes: avbstclinmedz created: 09/08/2001 20:46:40 modified: 07/13/2017 21:40:00 (1500000000.0, 1500000000.0, 1269636578.0, 1500000000, 1500000000, 1269636578) file: "/private/tmp/tempfile" type: "" creator: "" attributes: avbstclinmedz created: 09/08/2001 20:46:40 modified: 07/13/2017 21:40:00 This seems to be consistent with your observations from your Get Info window in _Finder_. My interpretation (borne out by other experimentation) is that the HFS creationDate is updated by utime, but it only ever goes backwards (never forwards). If you want to update the HFS creationDate to a newer value, then you probably will have to use a Mac-specific API to do it. One other note: you may have to switch windows a bit to get the _Get Info_ window to update. On my system, its display does not automatically update unless I switch windows either to or from the Get Info window.
Resulting .exe from PyInstaller with wxPython crashing Question: I'm trying to compile a very simple wxPython script into an executable by using PyInstaller on Windows Vista. The Python script is nothing but a Hello World in wxPython. I'm trying to get that up and running as a Windows executable before I add any of the features that the program needs to have. But I'm already stuck. I've jumped through some loops in regards to MSVCR90.DLL, MSVCP90.DLL and MSVCPM90.DLL, which I ended up copying from my Visual Studio installation (C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT). As according to the instructions for PyInstaller, I run: Command: Configure.py Output: I: computing EXE_dependencies I: Finding TCL/TK... I: could not find TCL/TK I: testing for Zlib... I: ... Zlib available I: Testing for ability to set icons, version resources... I: ... resource update available I: Testing for Unicode support... I: ... Unicode available I: testing for UPX... I: ...UPX available I: computing PYZ dependencies... So far, so good. I continue. Command: Makespec.py -F guitest.py Output: wrote C:\Code\PromoUSB\guitest.spec now run Build.py to build the executable Then there's the final command. Command: Build.py guitest.spec Output: checking Analysis building Analysis because out0.toc non existent running Analysis out0.toc Analyzing: C:\Python26\pyinstaller-1.3\support\_mountzlib.py Analyzing: C:\Python26\pyinstaller-1.3\support\useUnicode.py Analyzing: guitest.py Warnings written to C:\Code\PromoUSB\warnguitest.txt checking PYZ rebuilding out1.toc because out1.pyz is missing building PYZ out1.toc checking PKG rebuilding out3.toc because out3.pkg is missing building PKG out3.pkg checking ELFEXE rebuilding out2.toc because guitest.exe missing building ELFEXE out2.toc I get the resulting 'guitest.exe' file, but upon execution, it "simply crashes"... and there is no debug info. It's just one of those standard Windows Vista crashes. The script itself, guitest.py runs just fine by itself. It only crashes as an executable, and I'm completely lost. I don't even know what to look for, since nothing I've tried has returned any relevant results. Another file is generated as a result of the compilation process, called 'warnguitest.txt'. Here are its contents. W: no module named posix (conditional import by os) W: no module named optik.__all__ (top-level import by optparse) W: no module named readline (delayed, conditional import by cmd) W: no module named readline (delayed import by pdb) W: no module named pwd (delayed, conditional import by posixpath) W: no module named org (top-level import by pickle) W: no module named posix (delayed, conditional import by iu) W: no module named fcntl (conditional import by subprocess) W: no module named org (top-level import by copy) W: no module named _emx_link (conditional import by os) W: no module named optik.__version__ (top-level import by optparse) W: no module named fcntl (top-level import by tempfile) W: __all__ is built strangely at line 0 - collections (C:\Python26\lib\collections.pyc) W: delayed exec statement detected at line 0 - collections (C:\Python26\lib\collections.pyc) W: delayed conditional __import__ hack detected at line 0 - doctest (C:\Python26\lib\doctest.pyc) W: delayed exec statement detected at line 0 - doctest (C:\Python26\lib\doctest.pyc) W: delayed conditional __import__ hack detected at line 0 - doctest (C:\Python26\lib\doctest.pyc) W: delayed __import__ hack detected at line 0 - encodings (C:\Python26\lib\encodings\__init__.pyc) W: __all__ is built strangely at line 0 - optparse (C:\Python26\pyinstaller-1.3\optparse.pyc) W: __all__ is built strangely at line 0 - dis (C:\Python26\lib\dis.pyc) W: delayed eval hack detected at line 0 - os (C:\Python26\lib\os.pyc) W: __all__ is built strangely at line 0 - __future__ (C:\Python26\lib\__future__.pyc) W: delayed conditional __import__ hack detected at line 0 - unittest (C:\Python26\lib\unittest.pyc) W: delayed conditional __import__ hack detected at line 0 - unittest (C:\Python26\lib\unittest.pyc) W: __all__ is built strangely at line 0 - tokenize (C:\Python26\lib\tokenize.pyc) W: __all__ is built strangely at line 0 - wx (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.pyc) W: __all__ is built strangely at line 0 - wx (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.pyc) W: delayed exec statement detected at line 0 - bdb (C:\Python26\lib\bdb.pyc) W: delayed eval hack detected at line 0 - bdb (C:\Python26\lib\bdb.pyc) W: delayed eval hack detected at line 0 - bdb (C:\Python26\lib\bdb.pyc) W: delayed __import__ hack detected at line 0 - pickle (C:\Python26\lib\pickle.pyc) W: delayed __import__ hack detected at line 0 - pickle (C:\Python26\lib\pickle.pyc) W: delayed conditional exec statement detected at line 0 - iu (C:\Python26\pyinstaller-1.3\iu.pyc) W: delayed conditional exec statement detected at line 0 - iu (C:\Python26\pyinstaller-1.3\iu.pyc) W: delayed eval hack detected at line 0 - gettext (C:\Python26\lib\gettext.pyc) W: delayed __import__ hack detected at line 0 - optik.option_parser (C:\Python26\pyinstaller-1.3\optik\option_parser.pyc) W: delayed conditional eval hack detected at line 0 - warnings (C:\Python26\lib\warnings.pyc) W: delayed conditional __import__ hack detected at line 0 - warnings (C:\Python26\lib\warnings.pyc) W: __all__ is built strangely at line 0 - optik (C:\Python26\pyinstaller-1.3\optik\__init__.pyc) W: delayed exec statement detected at line 0 - pdb (C:\Python26\lib\pdb.pyc) W: delayed conditional eval hack detected at line 0 - pdb (C:\Python26\lib\pdb.pyc) W: delayed eval hack detected at line 0 - pdb (C:\Python26\lib\pdb.pyc) W: delayed conditional eval hack detected at line 0 - pdb (C:\Python26\lib\pdb.pyc) W: delayed eval hack detected at line 0 - pdb (C:\Python26\lib\pdb.pyc) I don't know what the heck to make of any of that. Again, my searches have been fruitless. Answer: On windows I have found Py2exe to be more stable and easier to use, have you tried that.
python metaprogramming Question: I'm trying to archive a task which turns out to be a bit complicated since I'm not very good at Python metaprogramming. I want to have a module `locations` with function `get_location(name)`, which returns a class defined in a folder locations/ in the file with the name passed to function. Name of a class is something like NameLocation. So, my folder structure: program.py locations/ __init__.py first.py second.py program.py will be smth with with: from locations import get_location location = get_location('first') and the location is a class defined in first.py smth like this: from locations import Location # base class for all locations, defined in __init__ (?) class FirstLocation(Location): pass etc. Okay, I've tried a lot of **import** and **getattribute** statements but now I'm bored and surrender. How to archive such behaviour? * * * I don't know why, but this code def get_location(name): module = __import__(__name__ + '.' + name) #return getattr(module, titlecase(name) + 'Location') return module returns >>> locations.get_location( 'first') <module 'locations' from 'locations/__init__.py'> the locations module! why?! Answer: You do need to `__import__` the module; after that, getting an attr from it is not hard. import sys def get_location(name): fullpath = 'locations.' + name package = __import__(fullpath) module = sys.modules[fullpath] return getattr(module, name.title() + 'Location') **Edit** : `__import__` returns the package, so you need one more `getattr`, see [the docs](http://docs.python.org/library/functions.html?highlight=__import__#__import__) (and read all the section carefully -- "do as I say not as I do";-).
Send an email using python script Question: Today I needed to send email from a Python script. As always I searched Google and found the following script that fits to my need. import smtplib SERVER = "localhost" FROM = "[email protected]" TO = ["[email protected]"] # must be a list SUBJECT = "Hello!" TEXT = "This message was sent with Python's smtplib." # Prepare actual message message = """\ From: %s To: %s Subject: %s %s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) # Send the mail server = smtplib.SMTP(SERVER) server.sendmail(FROM, TO, message) server.quit() But when I tried to run the program, I got the following error message: Traceback (most recent call last): File "C:/Python26/email.py", line 1, in <module> import smtplib File "C:\Python26\lib\smtplib.py", line 46, in <module> import email.utils File "C:/Python26/email.py", line 24, in <module> server = smtplib.SMTP(SERVER) AttributeError: 'module' object has no attribute 'SMTP' How can i solve this problem? Any one can help me? Thanks in advance, Nimmy. * * * changed the name to emailsendin .py. But I got the following error Traceback (most recent call last): File "C:\Python26\emailsending.py", line 24, in <module> server = smtplib.SMTP(SERVER) File "C:\Python26\lib\smtplib.py", line 239, in __init__ (code, msg) = self.connect(host, port) File "C:\Python26\lib\smtplib.py", line 295, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Python26\lib\smtplib.py", line 273, in _get_socket return socket.create_connection((port, host), timeout) File "C:\Python26\lib\socket.py", line 512, in create_connection raise error, msg error: [Errno 10061] No connection could be made because the target machine actively refused it Answer: You've named your module the same as one of Python's internal modules. When you import `smtplib`, it tries to import `email`, and finds your module instead of the internal one. When two modules import one another, only the variables in each module visible before the both import statements will be visible to one another. Renaming your module will fix the problem. You can see this, although it's slightly obscure, in the stack trace. The `import email.utils` line from `smtplib.py` is calling _your_ module, in "c:/Python26/email.py". Another note: it's probably not a great idea to use your Python install directory as your working directory for Python code.
Clever way of building a tag cloud? - Python Question: I've built a content aggregator and would like to add a tag cloud representing the current trends. Unfortunately this is quite complex, as I have to look for **keywords** that represent the context of each article. For example words such as **I** , **was** , **the** , **amazing** , **nice** have no relation to context. * * * Help would be much appreciated! :) Answer: Use [NLTK](http://www.acm.org/crossroads/xrds13-4/natural_language.html), and in particular its **Stopwords corpus** : > Besides regular content words, there is another class of words called stop > words that perform important grammatical functions, but are unlikely to be > interesting by themselves. These include prepositions, complementizers, and > determiners. NLTK comes bundled with the Stopwords corpus, a list of 2400 > stop words across 11 different languages (including English).
python parallel computing: split keyspace to give each node a range to work on Question: My question is rather complicated for me to explain, as i'm not really good at maths, but i'll try to be as clear as possible. I'm trying to code a cluster in python, which will generate words given a charset (i.e. with lowercase: aaaa, aaab, aaac, ..., zzzz) and make various operations on them. I'm searching how to calculate, given the charset and the number of nodes, what range each node should work on (i.e.: node1: aaaa-azzz, node2: baaa-czzz, node3: daaa-ezzz, ...). Is it possible to make an algorithm that could compute this, and if it is, how could i implement this in python? I really don't know how to do that, so any help would be much appreciated Answer: Any way that you could compute a small integer from the string would be fine for clustering. For example, compute a hash with md5, and look at a byte of it: import hashlib s = "aaac" num_nodes = 5 # or whatever m = hashlib.md5(s) node = ord(m.digest()[0]) % num_nodes print node # prints 2 This won't guarantee to evenly distribute all the strings, but it will be close.
how to do asynchronous http requests with epoll and python 3.1 Question: **UPDATE: after much laboring with Py3, including writing my own asynchronous webserver (following a presentation given by Dave Beazley), i finally dumped Python (and a huge stack of my code )-: in favor of[CoffeeScript](http://coffeescript.org/) running on [NodeJS](http://nodejs.org/). Check it out: [GitHub](https://github.com) (where you'll find like 95% of all interesting code these days), [npm](http://npmjs.org/) (package manager that couldn't be any user friendly; good riddance, `easy_install`, you never lived up to your name), an insanely huge repository of modules (with tons of new stuff being published virtually 24/7), a huge and vibrant community, out-of-the-box asynchronous HTTP and filehandling..., all that (thanks to [V8](http://code.google.com/apis/v8/)) at [one third the speed of light](http://onlyjob.blogspot.com/2011/03/perl5-python-ruby-php-c-c-lua- tcl.html) — what's not to like? read more propaganda: ["The future of Scripting"](http://spreewebdesign.de/node/) (slide hosting courtesy [SpreeWebdesign](http://spreewebdesign.de)).** there is an interesting page <http://scotdoyle.com/python-epoll-howto.html> about how to do asnchronous / non-blocking / AIO http serving in python 3. there is the [tornado web server](http://www.tornadoweb.org/) which does include a non-blocking http client. i have managed to port parts of the server to python 3.1, but the implementation of the client requires [pyCurl](http://pycurl.sourceforge.net/) and [seems to have problems](http://groups.google.com/group/python- tornado/browse_thread/thread/276059a076593266/c49e8f834497271e?lnk=gst&q=httpclient+trouble+with+epoll#c49e8f834497271e) (with one participant stating how ‘Libcurl is such a pain in the neck’, and looking at the incredibly ugly pyCurl page i doubt pyCurl will arrive in py3+ any time soon). now that epoll is available in the standard library, it should be possible to do asynchronous http requests out of the box with python. i really do not want to use asyncore or whatnot; epoll has a reputation for being the ideal tool for the task, and it is part of the python distribution, so using anything but epoll for non-blocking http is highly counterintuitive (prove me wrong if you feel like it). oh, and i feel threading is horrible. no threading. i use [stackless](http://stackless.com/). _people further interested in the topic of asynchronous http should not miss out on this[talk by peter portante at PyCon2010](http://python.mirocommunity.org/video/1501/pycon-2010-demystifying- non-bl); also of interest is [the keynote](http://python.mirocommunity.org/video/1605/pycon-2010-keynote- relentlessl), where speaker antonio rodriguez at one point emphasizes the importance of having up-to-date web technology libraries right in the standard library._ **edit** there may be many ways to achieve high throughputs with little resource consumption. however, it is not only me who thinks that abandoning threads (and other, partially outdated, methods); the people over at the [google skipfish project](http://code.google.com/p/skipfish/wiki/SkipfishDoc) seem to think similar: they say skipfish uses a > Multiplexing single-thread, fully asynchronous network I/O and data > processing model that eliminates memory management, scheduling, and IPC > inefficiencies present in some multi-threaded clients. Answer: In [this poll](http://www.mail-archive.com/python-bugs- [email protected]/msg61273.html), months ago, Giampaolo Rodolá said > I have a patch for adding epoll() support which is almost ready (asyncore > supports poll(), not epoll()), it's just a matter of writing tests. I'm not sure where to find that patch, but it seems a simple enough task that it should be readily portable into `asyncore` (the standard python library approach to async servers and clients -- sure, way behind Twisted or Tornado, but that's what the stdlib has;-).
How do I introspect things in Ruby? Question: For instance, in Python, I can do things like this if I want to get all attributes on an object: >>> import sys >>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'pydebug', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions'] Or if I want to view the documentation of something, I can use the help function: >>> help(str) Is there any way to do similar things in Ruby? Answer: Sure, it's even simpler than in Python. Depending on what information you're looking for, try: obj.methods and if you want just the methods defined for obj (as opposed to getting methods on `Object` as well) obj.methods - Object.methods Also interesting is doing stuff like: obj.methods.grep /to_/ To get instance variables, do this: obj.instance_variables and for class variables: obj.class_variables
Trying to grab just absolute links from a webpage using BeautifulSoup Question: I am reading the contents of a webpage using BeautifulSoup. What I want is to just grab the `<a href>` that start with `http://`. I know in beautifulsoup you can search by the attributes. I guess I am just having a syntax issue. I would imagine it would go something like. page = urllib2.urlopen("http://www.linkpages.com") soup = BeautifulSoup(page) for link in soup.findAll('a'): if link['href'].startswith('http://'): print links But that returns: Traceback (most recent call last): File "<stdin>", line 2, in <module> File "C:\Python26\lib\BeautifulSoup.py", line 598, in __getitem__ return self._getAttrMap()[key] KeyError: 'href' Any ideas? Thanks in advance. _EDIT_ This isn't for any site in particular. The script gets the url from the user. So internal link targets would be an issue, that's also why I only want the `<'a'>` from the pages. If I turn it towards `www.reddit.com`, it parses the beginning links and it gets to this: <a href="http://www.reddit.com/top/">top</a> <a href="http://www.reddit.com/saved/">saved</a> Traceback (most recent call last): File "<stdin>", line 2, in <module> File "C:\Python26\lib\BeautifulSoup.py", line 598, in __getitem__ return self._getAttrMap()[key] KeyError: 'href' Answer: from BeautifulSoup import BeautifulSoup import re import urllib2 page = urllib2.urlopen("http://www.linkpages.com") soup = BeautifulSoup(page) for link in soup.findAll('a', attrs={'href': re.compile("^http://")}): print link
Having trouble scraping an ASP .NET web page Question: I am trying to scrape an ASP.NET website but am having trouble getting the results from a post. I have the following python code and am using httplib2 and BeautifulSoup: conn = Http() # do a get first to retrieve important values page = conn.request(u"http://somepage.com/Search.aspx", "GET") #event_validation and viewstate variables retrieved from GET here... body = {"__EVENTARGUMENT" : "", "__EVENTTARGET" : "" , "__EVENTVALIDATION": event_validation, "__VIEWSTATE" : viewstate, "ctl00_ContentPlaceHolder1_GovernmentCheckBox" : "On", "ctl00_ContentPlaceHolder1_NonGovernmentCheckBox" : "On", "ctl00_ContentPlaceHolder1_SchoolKeyValue" : "", "ctl00_ContentPlaceHolder1_SchoolNameTextBox" : "", "ctl00_ContentPlaceHolder1_ScriptManager1" : "ctl00_ContentPlaceHolder1_UpdatePanel1|cct100_ContentPlaceHolder1_SearchImageButton", "ct100_ContentPlaceHolder1_SearchImageButton.x" : "375", "ct100_ContentPlaceHolder1_SearchImageButton.y" : "11", "ctl00_ContentPlaceHolder1_SuburbTownTextBox" : "Adelaide,SA,5000", "hiddenInputToUpdateATBuffer_CommonToolkitScripts" : 1} headers = {"Content-type": "application/x-www-form-urlencoded"} resp, content = conn.request(url,"POST", headers=headers, body=urlencode(body)) When I print `content` I still seem to be getting the same results as the "GET" or is there a fundamental concept I'm missing to retrieve the result values of an ASP .NET post? Answer: This isn't technically an answer, but you could use [Fiddler](http://www.fiddler2.com/fiddler2/) to examine the difference between what you are sending with your python code, versus what would be sent if you used a web browser to do the post. I find that usually helps in these types of situations.
A 3-D grid of regularly spaced points Question: I want to create a list containing the 3-D coords of a grid of regularly spaced points, each as a 3-element tuple. I'm looking for advice on the most efficient way to do this. In C++ for instance, I simply loop over three nested loops, one for each coordinate. In Matlab, I would probably use the meshgrid function (which would do it in one command). I've read about meshgrid and mgrid in Python, and I've also read that using numpy's broadcasting rules is more efficient. It seems to me that using the zip function in combination with the numpy broadcast rules might be the most efficient way, but zip doesn't seem to be overloaded in numpy. Answer: Use `ndindex`: import numpy as np ind=np.ndindex(3,3,2) for i in ind: print(i) # (0, 0, 0) # (0, 0, 1) # (0, 1, 0) # (0, 1, 1) # (0, 2, 0) # (0, 2, 1) # (1, 0, 0) # (1, 0, 1) # (1, 1, 0) # (1, 1, 1) # (1, 2, 0) # (1, 2, 1) # (2, 0, 0) # (2, 0, 1) # (2, 1, 0) # (2, 1, 1) # (2, 2, 0) # (2, 2, 1)
Spikes in Socket Performance Question: We are facing random spikes in high throughput transaction processing system using sockets for IPC. Below is the setup used for the run: 1. The client opens and closes new connection for every transaction, and there are 4 exchanges between the server and the client. 2. We have disabled the `TIME_WAIT`, by setting the socket linger (`SO_LINGER`) option via getsockopt as we thought that the spikes were caused due to the sockets waiting in `TIME_WAIT`. 3. There is no processing done for the transaction. Only messages are passed. 4. OS used Centos 5.4 The average round trip time is around 3 milli seconds, but some times the round trip time ranges from 100 milli seconds to couple of seconds. **Steps used for Execution and Measurement and output** 1. Starting the server $ python sockServerLinger.py > /dev/null & 2. Starting the client to post 1 million transactions to the server. And logs the time for a transaction in the client.log file. $ python sockClient.py 1000000 > client.log 3. Once the execution finishes the following command will show the execution time greater than 100 milliseconds in the format `<line_number>:<execution_time>`. $ grep -n "0.[1-9]" client.log | less Below is the example code for Server and Client. **Server** # File: sockServerLinger.py import socket, traceback,time import struct host = '' port = 9999 l_onoff = 1 l_linger = 0 lingeropt = struct.pack('ii', l_onoff, l_linger) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, lingeropt) s.bind((host, port)) s.listen(1) while 1: try: clientsock, clientaddr = s.accept() print "Got connection from", clientsock.getpeername() data = clientsock.recv(1024*1024*10) #print "asdasd",data numsent=clientsock.send(data) data1 = clientsock.recv(1024*1024*10) numsent=clientsock.send(data) ret = 1 while(ret>0): data1 = clientsock.recv(1024*1024*10) ret = len(data) clientsock.close() except KeyboardInterrupt: raise except: print traceback.print_exc() continue **Client** # File: sockClient.py import socket, traceback,sys import time i = 0 while 1: try: st = time.time() s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) while (s.connect_ex(('127.0.0.1',9999)) != 0): continue numsent=s.send("asd"*1000) response = s.recv(6000) numsent=s.send("asd"*1000) response = s.recv(6000) i+=1 if i == int(sys.argv[1]): break except KeyboardInterrupt: raise except: print "in exec:::::::::::::",traceback.print_exc() continue print time.time() -st Answer: Here is one possibility that comes to mind: 1) Because you are using SOCK_STREAM, you are using the TCP protocol 2) As a reliable protocol, TCP will resend packets that have timed out, to ensure that everything eventually arrives. 3) TCP uses a dynamic timeout value that is calculated based on what the current round-trip time (RTT) is estimated to be 4) When a TCP connection first starts up, it doesn't know what the RTT is, so it uses a very large initial timeout value, sometimes on the order of seconds. So... if one of the early TCP handshake packets is dropped, your socket could be waiting around a long time before it decides that the packet didn't get there and it resends it. This would happen randomly, relatively rarely, but certainly many times in a million connections. Try using socket.settimeout() with a relatively short value, and retry it immediately if the connection times out. This way you fake having a shorter initial RTT estimate.
Python Permutation Program Flow help Question: i found this code at activestate, it takes a string and prints permutations of the string. I understand that its a recursive function but i dont really understand how it works, it'd be great if someone could walk me through the program flow, thanks a bunch! import sys def printList(alist, blist=[]): if not len(alist): print ''.join(blist) for i in range(len(alist)): blist.append(alist.pop(i)) printList(alist, blist) alist.insert(i, blist.pop()) if __name__ == '__main__': k = 'love' if len(sys.argv) > 1: k = sys.argv[1] printList(list(k)) Answer: You can figure out how `printList` behaves by drawing a recursion tree. Each node consists of two elements: an `alist` and a `blist`. The root has the `alist` with the initial sequence of items you want to permute, and an empty `blist`. Each node of the tree has one branch for each element of that node's `alist`; you move from a 'father' node to each one of its 'children' by choosing an element from the father's `alist` and: * assigning to the child's `alist` the father's `alist` _minus that element_ ; * assigning to the child's `blist` the father's `blist` plus that element _appended to its end_. The leafs have an empty `alist`, and since following different paths from the root to the leafs you have to choose elements from the root's `alist` in different orders, the `blist` of the leafs themselves contain all the various permutations of the root's `alist`. For example (`[abc],[] == alist,blist`): [abc],[] / | \ a/ b| \c / | \ [bc],[a] [ac],[b] [ab],[c] / \ b/ \c / \ [c],[ab] [b],[ac] | | c| |b | | [],[abc] [],[acb] def printList(alist, blist=[]): # if alist is empty, we are in a 'leaf' in the recursion tree; # then blist contains one permutation; print it if not len(alist): print ''.join(blist) # ELSE, for each possible position in alist, for i in range(len(alist)): # move the element at that position from alist to the end of blist blist.append(alist.pop(i)) # go to the 'children' node and do the printing job for its subtree printList(alist, blist) # then move back the element from the end of blist to its original # position in alist, so we can continue with the for loop # without altering alist alist.insert(i, blist.pop())
How to replace openSSL calls with C# code? Question: Hey there again! Today I ran into a problem when I was making a new theme creator for chrome. As you may know, Chrome uses a "new" file format, called CRX, to manage it's plugins and themes. It is a basic zip file, but a bit modified: "Cr24" + derkey + signature + zipFile And here comes the problem. There are only two CRX creators, written in Ruby or Python. I don't know neither language too much (had some basic experience in Python though, but mostly with PyS60), so I would like to ask you to help me convert this python app to a C# code that doesn't depend on external programs. Also, here is the source of crxmake.py: #!/usr/bin/python # Cribbed from http://github.com/Constellation/crxmake/blob/master/lib/crxmake.rb # and http://src.chromium.org/viewvc/chrome/trunk/src/chrome/tools/extensions/chromium_extension.py?revision=14872&content-type;=text/plain&pathrev;=14872 # from: http://grack.com/blog/2009/11/09/packing-chrome-extensions-in-python/ import sys from array import * from subprocess import * import os import tempfile def main(argv): arg0,dir,key,output = argv # zip up the directory input = dir + ".zip" if not os.path.exists(input): os.system("cd %(dir)s; zip -r ../%(input)s . -x '.svn/*'" % locals()) else: print "'%s' already exists using it" % input # Sign the zip file with the private key in PEM format signature = Popen(["openssl", "sha1", "-sign", key, input], stdout=PIPE).stdout.read(); # Convert the PEM key to DER (and extract the public form) for inclusion in the CRX header derkey = Popen(["openssl", "rsa", "-pubout", "-inform", "PEM", "-outform", "DER", "-in", key], stdout=PIPE).stdout.read(); out=open(output, "wb"); out.write("Cr24") # Extension file magic number header = array("l"); header.append(2); # Version 2 header.append(len(derkey)); header.append(len(signature)); header.tofile(out); out.write(derkey) out.write(signature) out.write(open(input).read()) os.unlink(input) print "Done." if __name__ == '__main__': main(sys.argv) Please could you help me? Answer: For Linux, there are a variety of utilities to do this - including one for bash - but it sounds like you want something for windows (guessing from your C# comment). I had tried to include links to all of them - but I am new stackoverflow user, and can only post 1 link.. Anyway, all of those can work in windows, however they require setup of the language interpreter and OpenSSL - so I spent a few hours and put together a version in C which runs on windows or linux (though, I'm not sure why you would use it in linux). It has OpenSSL statically linked so there are no interpreter or library requirements. The repository can be found here: <http://github.com/kylehuff/buildcrx> It should be noted, I do not use windows - this was written on Linux and the win32 binary was cross-compiled on Linux (as well as the OpenSSL libraries) - I did test it in windows - but not extensively. If you have trouble with it, please don't request support here; I will not respond. Use the issues page at the link above. Also, I will not convert this to C# - I can see no reason to use C# for such a simple utility and that would just perpetuate the need for "other software" in order for it be useful on other platforms.
python MySQLdb got invalid syntax when trying to INSERT INTO table Question: ## COMMENT OUT below just for reference "" cursor.execute (""" CREATE TABLE yellowpages ( business_id BIGINT(20) NOT NULL AUTO_INCREMENT, categories_name VARCHAR(255), business_name VARCHAR(500) NOT NULL, business_address1 VARCHAR(500), business_city VARCHAR(255), business_state VARCHAR(255), business_zipcode VARCHAR(255), phone_number1 VARCHAR(255), website1 VARCHAR(1000), website2 VARCHAR(1000), created_date datetime, modified_date datetime, PRIMARY KEY(business_id) ) """) "" ## TOP COMMENT OUT (just for reference) ## code website1g = "http://www.triman.com" business_nameg = "Triman Sales Inc" business_address1g = "510 E Airline Way" business_cityg = "Gardena" business_stateg = "CA" business_zipcodeg = "90248" phone_number1g = "(310) 323-5410" phone_number2g = "" website2g = "" cursor.execute (""" INSERT INTO yellowpages(categories_name, business_name, business_address1, business_city, business_state, business_zipcode, phone_number1, website1, website2) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s') """, (''gas-stations'', business_nameg, business_address1g, business_cityg, business_stateg, business_zipcodeg, phone_number1g, website1g, website2g)) cursor.close() conn.close() I keep getting this error File "testdb.py", line 51 """, (''gas-stations'', business_nameg, business_address1g, business_cityg, business_stateg, business_zipcodeg, phone_number1g, website1g, website2g)) ^ SyntaxError: invalid syntax any idea why? Thanks for the help in advance * * * Update #2, I have removed the double single quote on the "categories_name", but now even import MySQLdb conn = MySQLdb.connect(host="localhost",port=22008,user="cholestoff",passwd="whoami",db="mydatabase") cursor = conn.cursor() ## Find mysql version cursor.execute ("SELECT VERSION()") row = cursor.fetchone() print "server version:", row[0] website1g = "http://www.triman.com" business_nameg = "Triman Sales Inc" business_address1g = "510 E Airline Way" business_cityg = "Gardena" business_stateg = "CA" business_zipcodeg = "90248" phone_number1g = "(310) 323-5410" phone_number2g = "" cursor.execute (""" INSERT INTO yellowpages(categories_name, business_name) VALUES ('%s','%s') """, ('gas-stations', business_nameg)) cursor.close() conn.close() still gotten this error server version: 5.1.33-community Traceback (most recent call last): File "testdb.py", line 23, in <module> """, ('gas-stations', business_nameg)) File "C:\Python26\lib\site-packages\MySQLdb\cursors.py", line 173, in execute self.errorhandler(self, exc, value) File "C:\Python26\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'gas-stations'',''Triman Sales Inc'')' at line 2") Thanks again for the help Answer: I think your problem is here: ''gas-stations'' This gives a syntax error. You probably want to use one set of quotes: 'gas-stations' If you want to insert the value `'gas-stations'` into the database including the quotes then you can either escape the quotes or surround the string with double-quotes instead of single quotes: "'gas-stations'" The reason why the "up arrow" is pointing at the wrong place is because your lines are so long that it is wrapping on your console. Make your lines shorter, or widen your console window to see where the error really is.
Proper way to reload a python module from the console Question: I'm debugging from the python console and would like to reload a module every time I make a change so I don't have to exit the console and re-enter it. I'm doing: >>> from project.model.user import * >>> reload(user) but I receive: >>>NameError: name 'user' is not defined What is the proper way to reload the entire user class? Is there a better way to do this, perhaps auto-updating while debugging? Thanks. Answer: As asked, the best you can do is >>> from project.models.user import * >>> import project # get module reference for reload >>> reload(project.models.user) # reload step 1 >>> from project.models.user import * # reload step 2 it would be better and cleaner if you used the user module directly, rather than doing `import *` (which is almost never the right way to do it). Then it would just be >>> from project.models import user >>> reload(user) This would do what you want. But, it's not very nice. If you really need to reload modules so often, I've got to ask: why? My suspicion (backed up by previous experience with people asking similar questions) is that you're testing your module. There are lots of ways to test a module out, and doing it by hand in the interactive interpreter is among the worst ways. Save one of your sessions to a file and use [`doctest`](http://docs.python.org/library/doctest.html), for a quick fix. Alternatively, write it out as a program and use `python -i`. The only really great solution, though, is using the [`unittest`](http://docs.python.org/library/unittest.html) module. If that's not it, hopefully it's something better, not worse. There's really no good use of `reload` (in fact, it's removed in 3.x). It doesn't work effectively-- you might reload a module but leave leftovers from previous versions. It doesn't even work on all kinds of modules-- extension modules will not reload properly, or sometimes even break horribly, when reloaded. The context of using it in the interactive interpreter doesn't leave a lot of choices as to what you are doing, and what the real best solution would be. Outside it, sometimes people used `reload()` to implement plugins etc. This is dangerous at best, and can frequently be done differently using either `exec` (ah the evil territory we find ourselves in), or a segregated process.
python: list modules within the package Question: I have a package with a few modules, each module has a class (or a few classes) defined within it. I need to get the list of all modules within the package. Is there an API for this in python? Here is the file structure: \pkg\ \pkg\__init__.py \pkg\module1.py -> defines Class1 \pkg\module2.py -> defines Class2 \pkg\module3.py -> defines Class3 and Class31 from within _module1_ I need to get the list of modules within _pkg_ , and then import all the classes defined in these modules Update 1: Ok, after considering the answers and comments below I figured, that it's not that's easy to achieve my need. In order to have the code I proposed below working, all the modules should be explicitly imported beforehand. So now the new concept: How to get the list of modules within a package without loading the modules? Using python API, i.e. - without listing all the files in the package folder? Thanks ak Answer: One ad-hoc approach is list the files in the directory, import each file dynamically with `__import__` and then list the classes of the resulting module.
Sunrise / set calculations Question: I'm trying to calculate the sunset / rise times using python based on the link provided below. My results done through excel and python do not match the real values. Any ideas on what I could be doing wrong? My Excel sheet can be found under .. <http://transpotools.com/sun_time.xls> # Created on 2010-03-28 # @author: dassouki # @source: [http://williams.best.vwh.net/sunrise_sunset_algorithm.htm][2] # @summary: this is based on the Nautical Almanac Office, United States Naval # Observatory. import math, sys class TimeOfDay(object): def calculate_time(self, in_day, in_month, in_year, lat, long, is_rise, utc_time_zone): # is_rise is a bool when it's true it indicates rise, # and if it's false it indicates setting time #set Zenith zenith = 96 # offical = 90 degrees 50' # civil = 96 degrees # nautical = 102 degrees # astronomical = 108 degrees #1- calculate the day of year n1 = math.floor( 275 * in_month / 9 ) n2 = math.floor( ( in_month + 9 ) / 12 ) n3 = ( 1 + math.floor( in_year - 4 * math.floor( in_year / 4 ) + 2 ) / 3 ) new_day = n1 - ( n2 * n3 ) + in_day - 30 print "new_day ", new_day #2- calculate rising / setting time if is_rise: rise_or_set_time = new_day + ( ( 6 - ( long / 15 ) ) / 24 ) else: rise_or_set_time = new_day + ( ( 18 - ( long/ 15 ) ) / 24 ) print "rise / set", rise_or_set_time #3- calculate sun mean anamoly sun_mean_anomaly = ( 0.9856 * rise_or_set_time ) - 3.289 print "sun mean anomaly", sun_mean_anomaly #4 calculate true longitude true_long = ( sun_mean_anomaly + ( 1.916 * math.sin( math.radians( sun_mean_anomaly ) ) ) + ( 0.020 * math.sin( 2 * math.radians( sun_mean_anomaly ) ) ) + 282.634 ) print "true long ", true_long # make sure true_long is within 0, 360 if true_long < 0: true_long = true_long + 360 elif true_long > 360: true_long = true_long - 360 else: true_long print "true long (360 if) ", true_long #5 calculate s_r_a (sun_right_ascenstion) s_r_a = math.degrees( math.atan( 0.91764 * math.tan( math.radians( true_long ) ) ) ) print "s_r_a is ", s_r_a #make sure it's between 0 and 360 if s_r_a < 0: s_r_a = s_r_a + 360 elif true_long > 360: s_r_a = s_r_a - 360 else: s_r_a print "s_r_a (modified) is ", s_r_a # s_r_a has to be in the same Quadrant as true_long true_long_quad = ( math.floor( true_long / 90 ) ) * 90 s_r_a_quad = ( math.floor( s_r_a / 90 ) ) * 90 s_r_a = s_r_a + ( true_long_quad - s_r_a_quad ) print "s_r_a (quadrant) is ", s_r_a # convert s_r_a to hours s_r_a = s_r_a / 15 print "s_r_a (to hours) is ", s_r_a #6- calculate sun diclanation in terms of cos and sin sin_declanation = 0.39782 * math.sin( math.radians ( true_long ) ) cos_declanation = math.cos( math.asin( sin_declanation ) ) print " sin/cos declanations ", sin_declanation, ", ", cos_declanation # sun local hour cos_hour = ( math.cos( math.radians( zenith ) ) - ( sin_declanation * math.sin( math.radians ( lat ) ) ) / ( cos_declanation * math.cos( math.radians ( lat ) ) ) ) print "cos_hour ", cos_hour # extreme north / south if cos_hour > 1: print "Sun Never Rises at this location on this date, exiting" # sys.exit() elif cos_hour < -1: print "Sun Never Sets at this location on this date, exiting" # sys.exit() print "cos_hour (2)", cos_hour #7- sun/set local time calculations if is_rise: sun_local_hour = ( 360 - math.degrees(math.acos( cos_hour ) ) ) / 15 else: sun_local_hour = math.degrees( math.acos( cos_hour ) ) / 15 print "sun local hour ", sun_local_hour sun_event_time = sun_local_hour + s_r_a - ( 0.06571 * rise_or_set_time ) - 6.622 print "sun event time ", sun_event_time #final result time_in_utc = sun_event_time - ( long / 15 ) + utc_time_zone return time_in_utc #test through main def main(): print "Time of day App " # test: fredericton, NB # answer: 7:34 am long = 66.6 lat = -45.9 utc_time = -4 d = 3 m = 3 y = 2010 is_rise = True tod = TimeOfDay() print "TOD is ", tod.calculate_time(d, m, y, lat, long, is_rise, utc_time) if __name__ == "__main__": main() Answer: You could use [`ephem`](http://pypi.python.org/pypi/pyephem/) python module: #!/usr/bin/env python import datetime import ephem # to install, type$ pip install pyephem def calculate_time(d, m, y, lat, long, is_rise, utc_time): o = ephem.Observer() o.lat, o.long, o.date = lat, long, datetime.date(y, m, d) sun = ephem.Sun(o) next_event = o.next_rising if is_rise else o.next_setting return ephem.Date(next_event(sun, start=o.date) + utc_time*ephem.hour ).datetime().strftime('%H:%M') Example: for town, kwarg in { "Fredericton": dict(d=3, m=3, y=2010, lat='45.959045', long='-66.640509', is_rise=True, utc_time=20), "Beijing": dict(d=29, m=3, y=2010, lat='39:55', long='116:23', is_rise=True, utc_time=+8), "Berlin": dict(d=4, m=4, y=2010, lat='52:30:2', long='13:23:56', is_rise=False, utc_time=+2) , "Moscow": dict(d=4, m=4, y=2010, lat='55.753975', long='37.625427', is_rise=True, utc_time=4) }.items(): print town, calculate_time(**kwarg) Output: Beijing 06:02 Berlin 19:45 Moscow 06:53 Fredericton 07:01
Tell if a given login exists in Linux using Python Question: In Python under Linux, what is the easiest way to check the existence of a user, given his/her login? Anything better than issuing 'ls ~login-name' and checking the exit code? And if running under Windows? Answer: This answer builds upon the [answer by Brian](http://stackoverflow.com/a/2540487/832230). It adds the necessary `try...except` block. Check if a user exists: import pwd try: pwd.getpwnam('someusr') except KeyError: print('User someusr does not exist.') Check if a group exists: import grp try: grp.getgrnam('somegrp') except KeyError: print('Group somegrp does not exist.')
Python-daemon doesn't kill its kids Question: When using [python-daemon](http://pypi.python.org/pypi/python-daemon/), I'm creating subprocesses likeso: import multiprocessing class Worker(multiprocessing.Process): def __init__(self, queue): self.queue = queue # we wait for things from this in Worker.run() ... q = multiprocessing.Queue() with daemon.DaemonContext(): for i in xrange(3): Worker(q) while True: # let the Workers do their thing q.put(_something_we_wait_for()) When I kill the parent daemonic process (i.e. not a Worker) with a Ctrl-C or SIGTERM, etc., the children don't die. How does one kill the kids? My first thought is to use [atexit](http://docs.python.org/library/atexit) to kill all the workers, likeso: with daemon.DaemonContext(): workers = list() for i in xrange(3): workers.append(Worker(q)) @atexit.register def kill_the_children(): for w in workers: w.terminate() while True: # let the Workers do their thing q.put(_something_we_wait_for()) However, the children of daemons are tricky things to handle, and I'd be obliged for thoughts and input on how this ought to be done. Thank you. Answer: Your options are a bit limited. If doing `self.daemon = True` in the constructor for the `Worker` class does not solve your problem and trying to catch signals in the Parent (ie, `SIGTERM, SIGINT`) doesn't work, you may have to try the opposite solution - instead of having the parent kill the children, you can have the children commit suicide when the parent dies. The first step is to give the constructor to `Worker` the `PID` of the parent process (you can do this with `os.getpid()`). Then, instead of just doing `self.queue.get()` in the worker loop, do something like this: waiting = True while waiting: # see if Parent is at home if os.getppid() != self.parentPID: # woe is me! My Parent has died! sys.exit() # or whatever you want to do to quit the Worker process try: # I picked the timeout randomly; use what works data = self.queue.get(block=False, timeout=0.1) waiting = False except queue.Queue.Empty: continue # try again # now do stuff with data The solution above checks to see if the parent PID is different than what it originally was (that is, if the child process was adopted by `init` or `lauchd` because the parent died) - see [reference](http://www.mail- archive.com/[email protected]/msg55718.html). However, if that doesn't work for some reason you can replace it with the following function (adapted from [here](http://stackoverflow.com/questions/568271/check-if-pid-is-not-in- use-in-python)): def parentIsAlive(self): try: # try to call Parent os.kill(self.parentPID, 0) except OSError: # *beeep* oh no! The phone's disconnected! return False else: # *ring* Hi mom! return True Now, when the Parent dies (for whatever reason), the child Workers will spontaneously drop like flies - just as you wanted, you daemon! `:-D`
python mechanize.browser submit() related problem Question: im making some script with mechanize.browser module. one of problem is all other thing is ok, but when submit() form,it not working, so i was found some suspicion source part. in the html source i was found such like following. <form method="post" onsubmit="return loginCheck(this)" name="FRMLOGIN"/> im thinking, loginCheck(this) making problem when submit form. but how to handle this kind of javascript function with mechanize module ,so i can successfully submit form and can receive result? folloing is my current script source. if anyone can help me ..much appreciate!! # -*- coding: cp949-*- import sys,os import mechanize, urllib import cookielib from BeautifulSoup import BeautifulSoup,BeautifulStoneSoup,Tag import datetime, time, socket import re,sys,os,mechanize,urllib,time br = mechanize.Browser() cj = cookielib.LWPCookieJar() br.set_cookiejar(cj) # Browser options br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) # Follows refresh 0 but not hangs on refresh > 0 br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) # Want debugging messages? br.set_debug_http(True) br.set_debug_redirects(True) br.set_debug_responses(True) # User-Agent (this is cheating, ok?) br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6')] br.open('http://user.buddybuddy.co.kr/Login/LoginForm.asp?URL=') html = br.response().read() print html br.select_form(name='FRMLOGIN') print br.viewing_html() br.form['ID']='zero1zero2' br.form['PWD']='012045' br.submit() print br.response().read() Answer: mechanize doesn't support Javascript at all. If you absolutely have to run that Javascript, look into Selenium. It offers python bindings to control a real, running browser like Firefox or IE.
Any way to add my C# project as a reference in IronPython / IronRuby? Question: I know how to reference an existing .dll to IronPython, but is there any way to add my project as a reference like I can between Visual Studio projects? Or is it best practice to create a separate class library? Answer: You can't add reference to a project since it's a Visual Studio thing. I suggest that during the development process, call `import` (IronPython) or `require` (IronRuby) with the full path of your project assembly like c:\dev\MyProject\bin\Debug\MyProject.dll.
python mongokit Connection() AssertionError Question: just installed mongokit and can't figure out why I get AssertionError python console: >>> from mongokit import Connection >>> c = Connection() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.6/dist-packages/mongokit-0.5.3-py2.6.egg/mongokit/connection.py", line 35, in __init__ super(Connection, self).__init__(*args, **kwargs) File "build/bdist.linux-i686/egg/pymongo/connection.py", line 169, in __init__ File "build/bdist.linux-i686/egg/pymongo/connection.py", line 338, in __find_master File "build/bdist.linux-i686/egg/pymongo/connection.py", line 226, in __master File "build/bdist.linux-i686/egg/pymongo/database.py", line 220, in command File "build/bdist.linux-i686/egg/pymongo/collection.py", line 356, in find_one File "build/bdist.linux-i686/egg/pymongo/cursor.py", line 485, in next File "build/bdist.linux-i686/egg/pymongo/cursor.py", line 461, in _refresh File "build/bdist.linux-i686/egg/pymongo/cursor.py", line 429, in __send_message File "build/bdist.linux-i686/egg/pymongo/helpers.py", line 98, in _unpack_response AssertionError >>> mongodb console: Wed Mar 31 10:27:34 connection accepted from 127.0.0.1:60480 #30 Wed Mar 31 10:27:34 end connection 127.0.0.1:60480 db 1.5 pymongo 1.5 (tested also on 1.4.) mongokit 0.5.3 (also 0.5.2) Answer: This is a known issue in PyMongo working against devel (>1.4.0) versions of MongoDB. Just released PyMongo 1.5.2 w/ a fix - try upgrading to that.
What to put in a python module docstring? Question: Ok, so I've read both [PEP 8](http://www.python.org/dev/peps/pep-0008/) and [PEP 257](http://www.python.org/dev/peps/pep-0257/), and I've written lots of docstrings for functions and classes, but I'm a little unsure about what should go in a module docstring. I figured, at a minimum, it should document the functions and classes that the module exports, but I've also seen a few modules that list author names, copyright information, etc. Does anyone have an example of how a good python docstring should be structured? Answer: Think about somebody doing `help(yourmodule)` at the interactive interpreter's prompt -- what do they **want** to know? (Other methods of extracting and displaying the information are roughly equivalent to `help` in terms of amount of information). So if you have in `x.py`: """This module does blah blah.""" class Blah(object): """This class does blah blah.""" then: >>> import x; help(x) shows: Help on module x: NAME x - This module does blah blah. FILE /tmp/x.py CLASSES __builtin__.object Blah class Blah(__builtin__.object) | This class does blah blah. | | Data and other attributes defined here: | | __dict__ = <dictproxy object> | dictionary for instance variables (if defined) | | __weakref__ = <attribute '__weakref__' of 'Blah' objects> | list of weak references to the object (if defined) As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in theit docstrings). I don't see how metadata such as author name and copyright / license helps the module's user -- it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.
Heavy usage of Python at Google Question: Google's heavy usage of Python, is it just a matter of taste or does it give them a competitive advantage? Answer: I can't really give a definitive answer, because by the time I interviewed at Google in 2004 Python was already prominent at Google. Indeed, there's one apparently attractive explanation that I can definitely deny: it's not that Google uses Python because it employs so many prominent Pythonistas -- rather, most "prominent Pythonista" googlers joined Google, at least in part, because we knew about Python's prominence there (possible exceptions include Peter Norvig and Jeremy Hylton, but historically Google's choice of Python predated even them). That's definitely why I first got interested (my publisher let me know about the large amount of copies of my book that Google was purchasing -- at first, I thought of it as a good opportunity to sell my freelance consulting service...;-), how I was later able to convince Guido to join us, and, I believe, part of the motivation for such Pythonistas as Greg Stein, Wesley Chun, Fredrik Lundh, Thomas Wouters, Collin Winters, Jeffrey Yasskin, ... It all got started, I believe, because the very earliest Googlers (Sergey, Larry, Craig, ...) made a good engineering decision: "Python where we can, C++ where we must" -- they used (a subset of) C++ for the parts of the software stack where very low latency and/or tight control of memory were crucial, and Python, allowing more rapid delivery and maintenance of programs, for other parts. At the time, late '90s, the choice for the latter role was essentially between Python and Perl: other scripting languages were either unripe (I don't think Ruby was around yet, for example) or had other issues and limitations. Perl was more mature (especially in terms of its ecosystem of available add- ons via CPAN), but Python was deemed to be more readable and maintainable, and interfacing to C++ libraries (via SWIG) was easier. Java came in later, covering an intermediate niche -- and more recently of course Go was developed (though I don't believe there's much production work in it yet, as it's still evolving and maturing). Some specialized languages such as [sawzall](http://web.archive.org/web/20091222094118/http://labs.google.com/papers/sawzall.html) are also in the mix for very specific tasks, and of course Javascript is very important for browser-side work. Other languages, including the ones that Greg mentioned back in '06, are either "kind of accidental" or used for other specific tasks (e.g., Objective C for clients on iPhones or Macs) -- e.g., when Google hired its first system administrators, those employees inevitably came with very strong mastery of Perl and Bash, and often used either of those languages to develop some complex internal system; recoding those in Python (for easier deployment and maintainability) has often happened. Others (such as C#) may have been in the mix temporarily due to acquisitions, but, again, recoding in one of the "main Google languages" is always a pretty high priority (in C#'s case, recoding would typically be mostly in Java, as the two languages address similar areas in terms of levels of abstraction).
No module named difflib Question: I want to execute python code from C# with following code. static void Main(string[] args) { ScriptEngine engine = Python.CreateEngine(); ScriptSource source = engine.CreateScriptSourceFromFile(@"F:\Script\extracter.py"); source.Execute(); } I have the problem at line source.Execute(), I got error "No module named difflib". What is wrong in my code? This is my python code (extracter.py). import re import itertools import difflib print "Hello" Answer: This looks like your engine does not have access to Python standard library - it does not see `difflib.py`. Either fix the `sys.path` or copy `difflib.py` from Python 2.6 to `f:\script` folder. `re` and `itertools` modules are written in C# and are part of `IronPython.modules.dll` \- that's why importing them work.
How to make a simple cross-platform webbrowser with Python? Question: The <http://code.google.com/p/pywebkitgtk/> looks great but it seems to be running on linux only. Does anybody know if there is something similar but cross-platform? If not what can be the alternatives to make with Python a simple web-browser that can run on Windows, MAC os and linux? Thanks in advance Update: Does anybody has some information about [wxWebKit](http://wxwebkit.wxcommunity.com/index.php?n=Main.HomePage) ? Answer: Qt (which has Python bindings with [PyQt](http://www.riverbankcomputing.co.uk/software/pyqt/intro) or [PySide](http://www.pyside.org/)) offers [Webkit](http://webkit.org/) (the same engine as Safari). Making a simple cross-platform browser is [trivially implemented](http://www.rkblog.rk.edu.pl/w/p/webkit-pyqt-rendering-web-pages/) with this. To show how easy this really is (example taken from the link): #!/usr/bin/env python import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * app = QApplication(sys.argv) web = QWebView() web.load(QUrl("http://www.stackoverflow.com")) web.show() sys.exit(app.exec_())
(Python) algorithm to randomly select a key based on proportionality/weight Question: I'm a bit at a loss as to how to find a clean algorithm for doing the following: Suppose I have a dict k: >>> k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81} I now want to randomly select one of these keys, based on the 'weight' they have in the total (i.e. sum) amount of keys. >>> sum(k.values()) >>> 274 So that there's a >>> 68.0/274.0 >>> 0.24817518248175183 24.81% percent change that A is selected. How would you write an algorithm that takes care of this? In other words, that makes sure that on 10.000 random picks, A will be selected 2.481 times? Answer: This should do the trick: >>> k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81} >>> import random >>> def weighted_pick(dic): ... total = sum(dic.itervalues()) ... pick = random.randint(0, total-1) ... tmp = 0 ... for key, weight in dic.iteritems(): ... tmp += weight ... if pick < tmp: ... return key
Using CookieJar in Python to log in to a website from "Google App Engine". What's wrong here? Question: I've been trying to find a python code that would log in to my mail box on yahoo.com from ["Google App Engine"](http://code.google.com/intl/en/appengine/docs/whatisgoogleappengine.html) . [Here (click here to see that page)](http://stackoverflow.com/questions/1914275/googles-app-engine-python- how-to-get-parameters-from-a-log-in-pages) I was given this code: import urllib, urllib2, cookielib url = "https://login.yahoo.com/config/login?" form_data = {'login' : 'my-login-here', 'passwd' : 'my-password-here'} jar = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar)) form_data = urllib.urlencode(form_data) # data returned from this pages contains redirection resp = opener.open(url, form_data) # yahoo redirects to http://my.yahoo.com, so lets go there instead resp = opener.open('http://mail.yahoo.com') print resp.read() The author of this script looked into HTML script of [yahoo log-in form](https://login.yahoo.com/config/login_verify2?&.src=ym) and came up with this script. That log-in form contains two fields, one for users' Yahoo! ID and another one is for users' password. Here is how HTML code of that page for both of those fields looks like: User ID field: <input type="text" maxlength="96" class="yreg_ipt" size="17" value="" id="username" name="login"> Password field: <input type="password" maxlength="64" class="yreg_ipt" size="17" value="" id="passwd" name="passwd"> However, when I uploaded this code to Google App Engine I discovered that this log-in form keeps coming back to me, which, I assume, means that logging-in process didn't succeed. Why is it so? Answer: You send MD5 hash and not plain password. Also you'd have to play along with all kinds of CSRF protections etc. that they're implementing. Look: <input type="hidden" name=".tries" value="1"> <input type="hidden" name=".src" value="ym"> <input type="hidden" name=".md5" value=""> <input type="hidden" name=".hash" value=""> <input type="hidden" name=".js" value=""> <input type="hidden" name=".last" value=""> <input type="hidden" name="promo" value=""> <input type="hidden" name=".intl" value="us"> <input type="hidden" name=".bypass" value=""> <input type="hidden" name=".partner" value=""> <input type="hidden" name=".u" value="bd5tdpd5rf2pg"> <input type="hidden" name=".v" value="0"> <input type="hidden" name=".challenge" value="5qUiIPGVFzRZ2BHhvtdGXoehfiOj"> <input type="hidden" name=".yplus" value=""> <input type="hidden" name=".emailCode" value=""> <input type="hidden" name="pkg" value=""> <input type="hidden" name="stepid" value=""> <input type="hidden" name=".ev" value=""> <input type="hidden" name="hasMsgr" value="0"> <input type="hidden" name=".chkP" value="Y"> <input type="hidden" name=".done" value="http://mail.yahoo.com"> <input type="hidden" name=".pd" value="ym_ver=0&c=&ivt=&sg="> Launch Wireshark and play with it. Good luck :) However if you intend to use it w/ App Engine keep in my mind that using Google IP will almost surely result w/ Captcha challenge. Also Yahoo might block your `User-Agent` that is being set permanently by Google.
Sorting a list of dot sparated numbers, like software versions Question: I have a list containing version strings, such as things: versions_list = ["1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"] I would like to sort it, so the result would be something like this: versions_list = ["1.0.0", "1.0.2", "1.0.12", "1.1.2", "1.3.3"] The order of precendece for the digits should obviously be from left to right, and it should be descending. So `1.2.3` comes before `2.2.3` and `2.2.2` comes before `2.2.3`. How do I do this in Python? Answer: You can also use `distutils.version` module of standard library: from distutils.version import StrictVersion versions = ["1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"] versions.sort(key=StrictVersion) Gives you: ['1.0.0', '1.0.2', '1.0.12', '1.1.2', '1.3.3'] It can also handle versions with pre-release tags, for example: versions = ["1.1", "1.1b1", "1.1a1"] versions.sort(key=StrictVersion) Gives you: ["1.1a1", "1.1b1", "1.1"]
wxWidgets/wxPython: Do two identical events cause two handlings? Question: When there are two identical events in the event loop, will wxPython handle both of them, or will it call the handler only once for them both? I mean, in my widget I want to have an event like `EVT_NEED_TO_RECALCULATE_X`. I want this event to be posted in all kinds of different circumstances that require `x` to be recalculated. However, even if there are two different reasons to recalculate `x`, only one recalculation needs to be done. How do I do this? **EDIT:** I tried this code: import wx class Frame(wx.Frame): def __init__(self, parent=None): wx.Frame.__init__(self, parent) self.Bind(wx.EVT_COLOURPICKER_CHANGED, self.on_event) self.Centre() self.Show(True) self.i = 0 self.event_all() def on_event(self, event): print self.i self.i += 1 def event_all(self): for j in range(1000): event = wx.PyEvent() event.SetEventType(wx.EVT_COLOURPICKER_CHANGED.evtType[0]) wx.PostEvent(self, event) app = wx.App() Frame(None) app.MainLoop() If the events _do_ get grouped together, I'd expect it not to count all the way to 1000. But it does. Do they get grouped or not? Answer: you're talking about three things * the event * the source of the event * the event handling The event is a single one (X needs to be recalculated). It has multiple sources. But it has only a single handler. So it should just work. You make it a single event, add a single handler to it, but signal/raise the event whenever you want - every time you raise the **need X recalculated** flag, the handler should run one time. * * * **EDIT:** This line... event = wx.PyEvent() ...creates a **new** event. That means something happened, and must be reacted upon. If you create 1000 events, then sure, the event handler will be called 1000 times. The handler will be called once for each time the event happens, that is, once for each `PyEvent` instance that gets posted on the event queue. If you want to **group** them, one way is to not create a new `PyEvent` instance if one is pending: class Frame(wx.Frame): def __init__(self, parent=None): wx.Frame.__init__(self, parent) self.Bind(wx.EVT_COLOURPICKER_CHANGED, self.on_event) self.Centre() self.Show(True) self.i = 0 self.recalculating = False self.event_all() def on_event(self, event): self.recalculating = False print self.i self.i += 1 def event_all(self): for j in range(1000): if not self.recalculating: event = wx.PyEvent() event.SetEventType(wx.EVT_COLOURPICKER_CHANGED.evtType[0]) wx.PostEvent(self, event) self.recalculating = True
Python lookup hostname from IP with 1 second timeout Question: How can I look up a hostname given an IP address? Furthermore, how can I specify a timeout in case no such reverse DNS entry exists? Trying to keep things as fast as possible. Or is there a better way? Thank you! Answer: >>> import socket >>> socket.gethostbyaddr("69.59.196.211") ('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211']) For implementing the timeout on the function, [this stackoverflow thread](http://stackoverflow.com/questions/492519/timeout-on-a-python- function-call) has answers on that.
How can I include custom modules in a Django app Question: I'm really new to Python and Django. I created a class in Python that I would like to use in a Django application. It doesn't seem like it belongs in it's own application, how can I include it in my django app? Thank you! Answer: Put it [in a module somewhere](http://docs.python.org/tutorial/modules.html) and import it.
Do alternate python implementation version numbers imply that they provide the same syntax? Question: for example Jython is at version 2.5.1, does that imply a parallel fidelity to cpython syntax when it was at version 2.5.1? Answer: Generally yes, but there's technically nothing stopping alternate implementations from choosing whatever version numbers they want. It's also important to note that just because Jython 2.5.1 is intended to match CPython 2.5.1, doesn't mean that they're going to behave exactly the same or be entirely compatible -- consider C-based modules, for example, and facilities for getting at the underlying bytecode. The lack of any real standards body or formal specification for the Python language means that there are no clear rules on what constitutes "Python" and what is "implementation defined".
Handling import errors when using doctest Question: every now and then when I code in Python, I have to do without certain third- party modules. Eg. when I'm writing user authentication, it can be done in several ways and one of them is by using LDAP. However if the user does not want to use LDAP auth., he can choose a different option in a config file and in that case he should not have to have ldap module installed. Generally I solve this by: if config.foo: import ldap_auth as auth elif config.foo2: import other_auth as auth ... auth.do_stuff(...) and I import ldap module in ldap_auth module only. I personally find this quite nice, however, of course, doctests raise an ImportError when trying to execute ldap_auth. Now, I know I could catch it by try-ing to import the ldap module in ldap_auth, but that just kinda messes up the nice looking code (the whole point of doing the whole "import ldap_auth as auth" bussiness was to avoid ImportErrors). Is there any more elegant way to prevent doctests from raising ImportErrors when using this "pattern"? Cheers, Tom Answer: The recommended way is try: import foo as auth except ImportError: import bar as auth It avoids race conditions and I don't think it looks bad.
python: can't terminate a thread hung in socket.recvfrom() call Question: I cannot get a way to terminate a thread that is hung in a socket.recvfrom() call. For example, ctrl+c that should trigger KeyboardInterrupt exception can't be caught. Here is a script I've used for testing: from socket import * from threading import Thread from sys import exit class TestThread(Thread): def __init__(self,host="localhost",port=9999): self.sock = socket(AF_INET,SOCK_DGRAM) self.sock.bind((host,port)) super(TestThread,self).__init__() def run(self): while True: try: recv_data,addr = self.sock.recvfrom(1024) except (KeyboardInterrupt, SystemExit): sys.exit() if __name__ == "__main__": server_thread = TestThread() server_thread.start() while True: pass The main thread (the one that executes infinite loop) exits. However the thread that I explicitly create, keeps hanging in recvfrom(). Please, help me resolve this. Answer: Keyboard interrupts are always caught on the main thread -- never on "child" threads. To avoid `server_thread` keeping the process alive when the main thread exits, do server_thread.daemon = True before you call `server_thread.start()`. BTW, your `while True: pass` in the main thread is needlessly burning CPU cycles. You should at least change it to something like `while True: time.sleep(1.0)`. But that doesn't change the semantics of your code -- just gets it down from 99% CPU or so, to (I'd guess) < 5%;-).
float change from python 3.0.1 to 3.1.2 Question: I'm trying to learn python. I am using 3.1.2 and the o'reilly book is using 3.0.1 here is my code: import urllib.request price = (99.99) while price > 4.74: page = urllib.request.urlopen ("http://www.beans-r-us.biz/prices-loyalty.html") text = page.read().decode("utf8") where = text.find('>$') start_of_price = where + 2 end_of_price = start_of_price + 6 price = float(text[start_of_price:end_of_price]) print ("Buy!") Here is my error: Traceback (most recent call last): File "/Users/odin/Desktop/Coffe.py", line 14, in <module> price = float(text[start_of_price:end_of_price]) ValueError: invalid literal for float(): 4.59</ >>> What is wrong? Answer: The problem is that you have extra characters at the end of your float, probably because the content of the page changed since the code was written (the number appears to change every fifteen minute). You could try changing the following line to make the code slightly more robust: end_of_price = text.find('<', start_of_price) For an even better solution you should use something like [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) to parse the HTML.
Python Ephem / Datetime calculation Question: the output should process the first date as "day" and second as "night". I've been playing with this for a few hours now and can't figure out what I'm doing wrong. Any ideas? **Edit** I assume that the problem is due to my date comparison implementation **Output:** $ python time_of_day.py * should be day: event date: 2010/4/6 16:00:59 prev rising: 2010/4/6 09:24:24 prev setting: 2010/4/5 23:33:03 next rise: 2010/4/7 09:22:27 next set: 2010/4/6 23:34:27 day * should be night: event date: 2010/4/6 00:01:00 prev rising: 2010/4/5 09:26:22 prev setting: 2010/4/5 23:33:03 next rise: 2010/4/6 09:24:24 next set: 2010/4/6 23:34:27 day **time_of_day.py** import datetime import ephem # install from http://pypi.python.org/pypi/pyephem/ #event_time is just a date time corresponding to an sql timestamp def type_of_light(latitude, longitude, event_time, utc_time, horizon): o = ephem.Observer() o.lat, o.long, o.date, o.horizon = latitude, longitude, event_time, horizon print "event date ", o.date print "prev rising: ", o.previous_rising(ephem.Sun()) print "prev setting: ", o.previous_setting(ephem.Sun()) print "next rise: ", o.next_rising(ephem.Sun()) print "next set: ", o.next_setting(ephem.Sun()) if o.previous_rising(ephem.Sun()) <= o.date <= o.next_setting(ephem.Sun()): return "day" elif o.previous_setting(ephem.Sun()) <= o.date <= o.next_rising(ephem.Sun()): return "night" else: return "error" print "should be day: ", type_of_light('45.959','-66.6405','2010/4/6 16:01','-4', '-6') print "should be night: ", type_of_light('45.959','-66.6405','2010/4/6 00:01','-4', '-6') Answer: o.date will always be between o.previous_settings and o.next_rising ;), so you can check it this way: if o.previous_rising(ephem.Sun()) > o.previous_setting(ephem.Sun()): return "day" elif: return "night"
How can I remove all words that end in ":" from a string in Python? Question: I'm wondering how to remove a dynamic word from a string within Python. It will always have a ":" at the end of the word, and sometimes there's more than one within the string. I'd like to remove all occurrences of "word:". Thanks! :-) Answer: Use regular expressions. import re blah = "word word: monty py: thon" answer = re.sub(r'\w+:\s?','',blah) print answer This will also pull out a single optional space after the colon.
MySQLdb not INSERTING, _mysql does fine Question: Okay, I log onto the MySQL command-line client as root. I then open or otherwise run a python app using the MySQLdb module as root. When I check the results using python (IDLE), everything looks fine. When I use the MySQL command-line client, no INSERT has occurred. If I change things around to _mysql instead of MySQLdb, everything works fine. I'd appreciate any clarification(s). "Works" until IDLE/Virtual machine is reset: import MySQLdb db = MySQLdb.connect(user='root', passwd='*******',db='test') cursor = db.cursor() cursor.execute("""INSERT INTO test VALUES ('somevalue');""",) Works: import _mysql db = _mysql.connect(user='root', passwd='*******',db='test') db.query("INSERT INTO test VALUES ('somevalue');") System info: Intel x86 WinXP Python 2.5 MySQL 5.1.41 MySQL-Python 1.2.2 Answer: You can use `db.commit()` to submit data or set `db.autocommit()` after `_mysql.connect(...)` to autocommit requests.
Non-ASCII character Syntax Error in Python while calling URL Question: How can data can be sent to the server? For example, I have retrieve MAC address, so I want send to the server (e.g. <http://211.21.24.43:8080/data?mac=00-0C-F1-56-98-AD>) I found this snippet on the Internet: from urllib2 import Request, urlopen from binascii import b2a_base64 def b64open(url, postdata): req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'}) return urlopen(req) conn = b64open("http://211.21.24.43:8080/data","mac=00-0C-F1-56-98-AD") but when I run it, I get: File "send2.py", line 8 SyntaxError: Non-ASCII character '\xc3' in file send2.py on line 8, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details Can anyone help me send data to the server? Thanks in advance Answer: put the encoding at the top of .py file example: #!/usr/bin/env python #coding: utf8 import os ... This probably happened because you copied/pasted some unicode character that is not visible in your text editor.
Scope of "library" methods Question: I'm apparently laboring under a poor understanding of Python scoping. Perhaps you can help. Background: I'm using the if __name__ == "__main__" construct to perform "self-tests" in my module(s). Each self test makes calls to the various public methods and prints their results for visual checking as I develop the modules. To keep things "purdy" and manageable, I've created a small method to simplify the testing of method calls: def pprint_vars(var_in): print("%s = '%s'" % (var_in, eval(var_in))) When foo = "bar" Calling pprint_vars with: pprint_vars('foo') prints: foo = 'bar' All fine and good. Problem statement: Not happy to just KISS, I had the brain-drizzle to move my handy-dandy 'pprint_vars' method into a separate file named 'debug_tools.py' and simply import 'debug_tools' whenever I wanted access to 'pprint_vars'. Here's where things fall apart. I would expect import debug_tools foo = bar debug_tools.pprint_vars('foo') to continue working its magic and print: foo = 'bar' Instead, it greets me with: NameError: name 'some_var' is not defined Irrational belief: I believed (apparently mistakenly) that import puts imported methods (more or less) "inline" with the code, and thus the variable scoping rules would remain similar to if the method were defined inline. Plea for help: Can someone please correct my (mis)understanding of scoping regards imports? Thanks, JS Answer: "Global scope" doesn't actually exist in Python. What is commonly called "global scope" is actually **module scope**. That is to say, names defined at the module level. Putting the function in another module means that its module scope changes.