text
stringlengths
226
34.5k
How do I abort a socket.recv() from another thread in Python Question: I have a main thread that waits for connection. It spawns client threads that will echo the response from the client (telnet in this case). But say that I want to close down all sockets and all threads after some time, like after 1 connection. How would I do? If I do clientSocket.close() from the main thread, it won't stop doing the recv. It will only stop if I first send something through telnet, then it will fail doing further sends and recvs. My code look like this: # Echo server program import socket from threading import Thread import time class ClientThread(Thread): def __init__(self, clientSocket): Thread.__init__(self) self.clientSocket = clientSocket def run(self): while 1: try: # It will hang here, even if I do close on the socket data = self.clientSocket.recv(1024) print "Got data: ", data self.clientSocket.send(data) except: break self.clientSocket.close() HOST = '' PORT = 6000 serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serverSocket.bind((HOST, PORT)) serverSocket.listen(1) clientSocket, addr = serverSocket.accept() print 'Got a new connection from: ', addr clientThread = ClientThread(clientSocket) clientThread.start() time.sleep(1) # This won't make the recv in the clientThread to stop immediately, # nor will it generate an exception clientSocket.close() Answer: I know this is an old thread and that Samuel probably fixed his issue a long time ago. However, I had the same problem and came across this post while google'ing. Found a solution and think it is worthwhile to add. You can use the shutdown method on the socket class. It can prevent further sends, receives or both. > socket.shutdown(socket.SHUT_WR) The above prevents future sends, as an example. [See Python docs for more info.](http://docs.python.org/py3k/library/socket.html?highlight=socket#socket)
Python: What is the hard recursion limit for Linux, Mac and Windows? Question: Python's `sys` module [provides a function](http://docs.python.org/library/sys.html#sys.setrecursionlimit) `setrecursionlimit` that lets you change Python's maximum recursion limit. The docs say: > The highest possible limit is platform-dependent. My question is: What is the highest possible limits for various platforms, under CPython? I would like to know the values for Linux, Mac and Windows. **UPDATE:** Can we please avoid "You're doing it wrong" answers? I know that trying to do very deep recursion is usually a bad idea. I've considered the pros and cons in my specific situation and decided that I want to do it. Answer: On Windows (at least), `sys.setrecursionlimit` isn't the full story. The hard limit is on a per-thread basis and you need to call `threading.stack_size` and create a new thread once you reach a certain limit. (I think 1MB, but not sure) I've used this approach to increase it to a 64MB stack. import sys import threading threading.stack_size(67108864) # 64MB stack sys.setrecursionlimit(2 ** 20) # something real big # you actually hit the 64MB limit first # going by other answers, could just use 2**32-1 # only new threads get the redefined stack size thread = threading.Thread(target=main) thread.start() I haven't tried to see what limits there might be on `threading.stack_size`, but feel free to try... that's where you need to look. In summary, `sys.setrecursionlimit` is just a limit enforced by the interpreter itself. `threading.stack_size` lets you manipulate the actual limit imposed by the OS. If you hit the latter limit first, Python will just crash completely.
How do I do this in Python (File Manipulation)? Question: I have a bunch of HTML files in HTML folder. Those HTML files have unicode characters which I solved by using `filter(lambda x: x in string.printable, line)`. Now how do I write the changes back to the original file? What is the best way of doing it? Each HTML file is of 30 kb in size. 1 import os, string 2 3 for file in os.listdir("HTML/"): 4 print file 5 myfile = open('HTML/' + file) 6 fileList = myfile.readlines() 9 for line in fileList: 10 #print line 11 line = filter(lambda x: x in string.printable, line) 12 myfile.close() Answer: Use the [fileinput](http://docs.python.org/library/fileinput.html#module- fileinput) module. It allows you to read and write to the same file in place: import fileinput,sys,os files=[os.path.join('HTML',filename) for filename in os.listdir("HTML/")] for line in fileinput.input(files, inplace=True): line = filter(lambda x: x in string.printable, line) sys.stdout.write(line)
What is a simple fuzzy string matching algorithm in Python? Question: I'm trying to find some sort of a good, fuzzy string matching algorithm. Direct matching doesn't work for me — this isn't too good because unless my strings are a 100% similar, the match fails. The [Levenshtein](http://en.wikipedia.org/wiki/Levenshtein_distance) method doesn't work too well for strings as it works on a character level. I was looking for something along the lines of word level matching e.g. > String A: The quick brown fox. > > String B: The quick brown fox jumped over the lazy dog. > > These should match as all words in string A are in string B. Now, this is an oversimplified example but would anyone know a good, fuzzy string matching algorithm that works on a word level. Answer: I like [Drew's answer](http://stackoverflow.com/questions/2923420/fuzzy- string-matching-algorithm-in-python/2923488#2923488). You can use [difflib](http://docs.python.org/library/difflib.html) to find the longest match: >>> a = 'The quick brown fox.' >>> b = 'The quick brown fox jumped over the lazy dog.' >>> import difflib >>> s = difflib.SequenceMatcher(None, a, b) >>> s.find_longest_match(0,len(a),0,len(b)) Match(a=0, b=0, size=19) # returns NamedTuple (new in v2.6) Or pick some minimum matching threshold. Example: >>> difflib.SequenceMatcher(None, a, b).ratio() 0.61538461538461542
What's a good equivalent to python's subprocess.check_call that returns the contents of stdout? Question: I'd like a good method that matches the interface of `subprocess.check_call` \-- ie, it throws `CalledProcessError` when it fails, is synchronous, &c -- but instead of returning the return code of the command (if it even does that) returns the program's output, either only stdout, or a tuple of (stdout, stderr). Does somebody have a method that does this? Answer: ### Python 2.7+ from subprocess import check_output as qx ### Python < 2.7 From [subprocess.py](http://hg.python.org/cpython/file/2.7/Lib/subprocess.py): import subprocess def check_output(*popenargs, **kwargs): if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise subprocess.CalledProcessError(retcode, cmd, output=output) return output class CalledProcessError(Exception): def __init__(self, returncode, cmd, output=None): self.returncode = returncode self.cmd = cmd self.output = output def __str__(self): return "Command '%s' returned non-zero exit status %d" % ( self.cmd, self.returncode) # overwrite CalledProcessError due to `output` keyword might be not available subprocess.CalledProcessError = CalledProcessError See also [Capturing system command output as a string](http://stackoverflow.com/questions/236737/capturing-system-command- output-as-a-string/236909#236909) for another example of possible `check_output()` implementation.
How to debug ctypes call of c++ dll? Question: in my python project I call a c++ dll using ctypes library. That c++ dll consists on a wrapper dll that calls methods of a c# com interop dll. Sometimes I have a COM exception. I like to see what it corresponds exactlly but I don't know how to do it? How can I attach the c++ debugger to this situation? Thanks in advance Answer: I don't know about your direct question, but maybe you could get around it by using [comtypes](http://sourceforge.net/projects/comtypes/) to go straight from COM to Python instead sticking C++ in between. Then all you have to do is: >>> from comtypes import client, COMError >>> myclassinst = client.CreateObject('MyCOMClass.MyCOMClass') >>> try: ... myclassinst.DoInvalidOperation() ... except COMError as e: ... print e.args ... print e.hresult ... print e.text ... (-2147205118, None, (u'MyCOMClass: An Error Message', u'MyCOMClass.MyCOMClass.1', None, 0, None)) -2147205118 None
dynamic module creation Question: I'd like to dynamically create a module from a dictionary, and I'm wondering if adding an element to `sys.modules` is really the best way to do this. EG context = { a: 1, b: 2 } import types test_context_module = types.ModuleType('TestContext', 'Module created to provide a context for tests') test_context_module.__dict__.update(context) import sys sys.modules['TestContext'] = test_context_module My immediate goal in this regard is to be able to provide a context for timing test execution: import timeit timeit.Timer('a + b', 'from TestContext import *') It seems that there are other ways to do this, since the Timer constructor takes objects as well as strings. I'm still interested in learning how to do this though, since a) it has other potential applications; and b) I'm not sure exactly how to use objects with the Timer constructor; doing so may prove to be less appropriate than this approach in some circumstances. ### EDITS/REVELATIONS/PHOOEYS/EUREKAE: 1. I've realized that the example code relating to running timing tests won't actually work, because `import *` only works at the _module_ level, and the context in which that statement is executed is that of a _function_ in the `testit` module. In other words, the globals dictionary used when executing that code is that of `__main__`, since that's where I was when I wrote the code in the interactive shell. So that rationale for figuring this out is a bit botched, but it's still a valid question. 2. I've discovered that the code run in the first set of examples has the undesirable effect that the namespace in which the newly created module's code executes is that of the module in which it was _declared_ , **_not_** _its own module_. This is like way weird, and could lead to all sorts of unexpected rattlesnakeic sketchiness. So I'm pretty sure that this is **not** how this sort of thing is meant to be done, if it is in fact something that the Guido doth shine upon. 3. The similar-but-subtly-different case of dynamically loading a module from a file that is not in python's include path is quite easily accomplished using `imp.load_source('NewModuleName', 'path/to/module/module_to_load.py')`. This does load the module into `sys.modules`. However this doesn't really answer my question, because really, what if you're running python on an [embedded platform with no filesystem](http://thedailywtf.com/Articles/The-cbitmap.aspx)? I'm battling a considerable case of information overload at the moment, so I could be mistaken, but there doesn't seem to be anything in the `imp` module that's capable of this. But the question, essentially, at this point is how to set the global (ie module) context for an object. Maybe I should ask that more specifically? And at a larger scope, how to get Python to do this while shoehorning objects into a given module? Answer: Hmm, well one thing I can tell you is that the `timeit` function actually executes its code using the module's global variables. So in your example, you could write import timeit timeit.a = 1 timeit.b = 2 timeit.Timer('a + b').timeit() and it would work. But that doesn't address your more general problem of defining a module dynamically. Regarding the module definition problem, it's definitely possible and I think you've stumbled on to pretty much the best way to do it. For reference, the gist of what goes on when Python imports a module is basically the following: module = imp.new_module(name) execfile(file, module.__dict__) That's kind of the same thing you do, except that you load the contents of the module from an existing dictionary instead of a file. (I don't know of any difference between `types.ModuleType` and `imp.new_module` other than the docstring, so you can probably use them interchangeably) What you're doing is somewhat akin to writing your own importer, and when you do that, you can certainly expect to mess with `sys.modules`. As an aside, even if your `import *` thing was legal within a function, you might still have problems because oddly enough, the statement you pass to the `Timer` doesn't seem to recognize its own local variables. I invoked a bit of Python voodoo by the name of `extract_context()` (it's a function I wrote) to set `a` and `b` at the local scope and ran print timeit.Timer('print locals(); a + b', 'sys.modules["__main__"].extract_context()').timeit() Sure enough, the printout of `locals()` included `a` and `b`: {'a': 1, 'b': 2, '_timer': <built-in function time>, '_it': repeat(None, 999999), '_t0': 1277378305.3572791, '_i': None} but it still complained `NameError: global name 'a' is not defined`. Weird.
Setting System.Drawing.Color through .NET COM Interop Question: I am trying to use Aspose.Words library through COM Interop. There is one critical problem: I cannot set color. It is supposed to work by assigning to DocumentBuilder.Font.Color, but when I try to do it I get OLE error 0x80131509. My problem is pretty much like [this one](http://www.aspose.com/community/forums/81588/font.color/showthread.aspx#81588). update: Code Sample: from win32com.client import Dispatch Doc = Dispatch("Aspose.Words.Document") Builder = Dispatch("Aspose.Words.DocumentBuilder") Builder.Document = Doc print Builder.Font.Size print Builder.Font.Color Result: 12.0 Traceback (most recent call last): File "aaa.py", line 6, in <module> print Builder.Font.Color File "D:\Python26\lib\site-packages\win32com\client\dynamic.py", line 501, in __getattr__ ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1) pywintypes.com_error: (-2146233079, 'OLE error 0x80131509', None, None) Using something like Font.Color = 0xff0000 fails with same error message While this code works ok: using Aspose.Words; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Font.Color = System.Drawing.Color.Blue; builder.Write("aaa"); doc.Save("c:\\1.doc"); } } } So it looks like COM Interop problem. Answer: Please, check the answer provided here: <http://www.aspose.com/community/forums/thread/240901/create-a-pivot-table- from-multiple-data-ranges.aspx> I think, this approach should help you to resolve the problem.
Python Access Parallel Port Question: I've been trying to access the parallel port with pyParallel, which is in the same sourceforge as PySerial: <http://sourceforge.net/projects/pyserial/files/> I'm getting a WidowsError: exception: priviledged instruciton. Has anyone used this module before? import parallel p = parallel.Parallel() Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "C:\Python26\lib\site-packages\parallel\parallelwin32.py", line 74, in __init__ self.ctrlReg = _pyparallel.inp(self.ctrlRegAdr) WindowsError: exception: priviledged instruction Answer: Yep -- as I pondered in my comment, it's all about better sandboxing in today's Windows versions -- there's a discussion [here](http://forums.bit- tech.net/showthread.php?t=150570). There's also a possible solution [here](http://logix4u.net/Legacy_Ports/Parallel_Port/Inpout32.dll_for_Windows_98/2000/NT/XP.html) (at least up to XP, you'll need to try it if you have a newer Windows version) with a Python example [here](http://logix4u.net/inpout32py.zip). I can't try it out since I don't have any Windows around, but I hope it can help!
Printing python tkinter output Question: I am trying to print the contents of a python tkinter canvas. I have tried using the postscript method of canvas to create a postscript file, but I get a blank page. I know this is because I have embedded widgets, and these do not get rendered by the postscript method. Before I rewrite my program to create a more printer-friendly layout, can someone suggest a way to approach this problem? All of the programming books I have ever read approach the problem of sending output to a printer with a bit of hand-waving, something along the lines of: "It's a difficult problem that depends on interacting with the operating system." I also have a hard time finding resources about this because of all the pages related to printing to the screen. I am using Python 2.6, on Ubuntu 9.04. Answer: Turns out that you have to update the canvas before exporting the postscript. Like so: from Tkinter import * root = Tk() canvas = Canvas(bg='white', width = 200, height = 200) canvas.pack() canvas.create_line(0, 0, 199, 199, fill="blue", width = 5) canvas.create_line(0, 199, 199, 0, fill="blue", width = 5) canvas.update() canvas.postscript(file = "x.ps") root.mainloop() Thanks to Rio [here](http://www.python- forum.org/pythonforum/viewtopic.php?f=15&t=12793#p59927) for the solution.
Problems trying to format currency with Python (Django) Question: I have the following code in Django: import locale locale.setlocale( locale.LC_ALL, '' ) def format_currency(i): return locale.currency(float(i), grouping=True) It work on some computers in dev mode, but as soon as I try to deploy it on production I get this error: Exception Type: TemplateSyntaxError Exception Value: Caught ValueError while rendering: Currency formatting is not possible using the 'C' locale. Exception Location: /usr/lib/python2.6/locale.py in currency, line 240 The weird thing is that I can do this on the production server and it will work without any errors: python manage.py shell >>> import locale >>> locale.setlocale( locale.LC_ALL, '' ) 'en_CA.UTF-8' >>> locale.currency(1, grouping=True) '$1.00' I .. don't get it.i Answer: On the production server, try locale.setlocale( locale.LC_ALL, 'en_CA.UTF-8' ) instead of locale.setlocale( locale.LC_ALL, '' ) When you use `''`, the locale is set to the user's default (usually specified by the `LANG` environment variable). On the production server, that appears to be 'C', while as a test user it appears to be 'en_CA.UTF-8'.
Python PEP8: Blank lines convention Question: I am interested in knowing what is the Python convention for new lines between the program? For example, consider this: import os def func1(): def func2(): What should be the ideal new line separation between: 1. the `import` modules and the functions? 2. the functions themselves? I have read PEP8, but I wanted to confirm the above two points. Answer: 1. two blank lines between the import statements and other code 2. two blank lines between each function
CherryPy configuration tools.staticdir.root problem Question: How can I make my static-file root directories relative to my application root folder (instead of a hard-coded path)? In accordance with CP instructions (http://www.cherrypy.org/wiki/StaticContent) I have tried the following in my configuration file: tree.cpapp = cherrypy.Application(cpapp.Root()) tools.staticdir.root = cpapp.current_dir but when I run `cherrpy.quickstart(rootclass, script_name='/', config=config_file)` I get the following error _builtins.ValueError: ("Config error in section: 'global', option: 'tree.cpapp', value: 'cherrypy.Application(cpapp.Root())'. Config values must be valid Python.", 'TypeError', ("unrepr could not resolve the name 'cpapp'",))_ I know I can do configuration from within the main.py file just before quickstart is called (eg. using os.path.abspath(os.path.dirname(**file**))), but I prefer using the idea of a separate configuration file if possible. Any help would be appreciated (in case it is relevant, I am using CP 3.2 with Python 3.1) TIA Alan Answer: When you refer to a module inside configuration entries, CherryPy first looks for that module in `sys.modules`. So one solution would be to `import cpapp` just before you call quickstart. But if that lookup in `sys.modules` fails, CherryPy tries to `__import__` the module. Since that is also failing, you might need to investigate whether your `cpapp.py` module is indeed importable at all. See the `lib/reprconf.py` module for all the gory details.
How to make item view render rich (html) text in PyQt? Question: I'm trying to translate code from [this thread](http://stackoverflow.com/questions/1956542/how-to-make-item-view- render-rich-html-text-in-qt) in python: import sys from PyQt4.QtCore import * from PyQt4.QtGui import * __data__ = [ "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." ] def get_html_box(text): return '''<table border="0" width="100%"><tr width="100%" valign="top"> <td width="1%"><img src="softwarecenter.png"/></td> <td><table border="0" width="100%" height="100%"> <tr><td><b><a href="http://www.google.com">titolo</a></b></td></tr> <tr><td>{0}</td></tr><tr><td align="right">88/88/8888, 88:88</td></tr> </table></td></tr></table>'''.format(text) class HTMLDelegate(QStyledItemDelegate): def paint(self, painter, option, index): model = index.model() record = model.listdata[index.row()] doc = QTextDocument(self) doc.setHtml(get_html_box(record)) doc.setTextWidth(option.rect.width()) painter.save() ctx = QAbstractTextDocumentLayout.PaintContext() ctx.clip = QRectF(0, option.rect.top(), option.rect.width(), option.rect.height()) dl = doc.documentLayout() dl.draw(painter, ctx) painter.restore() def sizeHint(self, option, index): model = index.model() record = model.listdata[index.row()] doc = QTextDocument(self) doc.setHtml(get_html_box(record)) doc.setTextWidth(option.rect.width()) return QSize(doc.idealWidth(), doc.size().height()) class MyListModel(QAbstractListModel): def __init__(self, parent=None, *args): super(MyListModel, self).__init__(parent, *args) self.listdata = __data__ def rowCount(self, parent=QModelIndex()): return len(self.listdata) def data(self, index, role=Qt.DisplayRole): return index.isValid() and QVariant(self.listdata[index.row()]) or QVariant() class MyWindow(QWidget): def __init__(self, *args): super(MyWindow, self).__init__(*args) # listview self.lv = QListView() self.lv.setModel(MyListModel(self)) self.lv.setItemDelegate(HTMLDelegate(self)) self.lv.setResizeMode(QListView.Adjust) # layout layout = QVBoxLayout() layout.addWidget(self.lv) self.setLayout(layout) if __name__ == "__main__": app = QApplication(sys.argv) w = MyWindow() w.show() sys.exit(app.exec_()) Element's size and position are not calculated correctly I guess, perhaps because I haven't understand at all the style related parts from original code. Can someone help me? Answer: The code doesn't respect the desired target drawing area (`option.rect`): ctx.clip = QRectF(0, option.rect.top(), option.rect.width(), option.rect.height()) The above clips the portion of the `QTextDocument` drawn to the specified region. You really want to translate the painter so that the it starts painting at the `topLeft()` of the rectangle and then extends for the specified width and height. Since `documentLayout()` assumes the painter is at the origin (i.e. in the position where it should draw), this is the fix: def paint(self, painter, option, index): model = index.model() record = model.listdata[index.row()] doc = QTextDocument(self) doc.setHtml(get_html_box(record)) doc.setTextWidth(option.rect.width()) ctx = QAbstractTextDocumentLayout.PaintContext() painter.save() painter.translate(option.rect.topLeft()); painter.setClipRect(option.rect.translated(-option.rect.topLeft())) dl = doc.documentLayout() dl.draw(painter, ctx) painter.restore()
Removing minimize/maximize buttons in Tkinter Question: I have a python program which opens a new windows to display some 'about' information. This window has its own close button, and I have made it non- resizeable. However, the buttons to maximize and minimize it are still there, and I want them gone. I am using Tkinter, wrapping all the info to display in the Tk class. The code so far is given below. I know its not pretty, and I plan on expanding the info making it into a class, but I want to get this problem sorted before moving along. Anyone know how I can govern which of the default buttons are shown by the windows manager? def showAbout(self): if self.aboutOpen==0: self.about=Tk() self.about.title("About "+ self.programName) Label(self.about,text="%s: Version 1.0" % self.programName ,foreground='blue').pack() Label(self.about,text="By Vidar").pack() self.contact=Label(self.about,text="Contact: adress@gmail.com",font=("Helvetica", 10)) self.contact.pack() self.closeButton=Button(self.about, text="Close", command = lambda: self.showAbout()) self.closeButton.pack() self.about.geometry("%dx%d+%d+%d" % (175,\ 95,\ self.myParent.winfo_rootx()+self.myParent.winfo_width()/2-75,\ self.myParent.winfo_rooty()+self.myParent.winfo_height()/2-35)) self.about.resizable(0,0) self.aboutOpen=1 self.about.protocol("WM_DELETE_WINDOW", lambda: self.showAbout()) self.closeButton.focus_force() self.contact.bind('<Leave>', self.contactMouseOver) self.contact.bind('<Enter>', self.contactMouseOver) self.contact.bind('<Button-1>', self.mailAuthor) else: self.about.destroy() self.aboutOpen=0 def contactMouseOver(self,event): if event.type==str(7): self.contact.config(font=("Helvetica", 10, 'underline')) elif event.type==str(8): self.contact.config(font=("Helvetica", 10)) def mailAuthor(self,event): import webbrowser webbrowser.open('mailto:adress@gmail.com',new=1) Answer: In general, what decorations the WM (window manager) decides to display can not be easily dictated by a toolkit like Tkinter. So let me summarize what I know plus what I found: import Tkinter as tk root= tk.Tk() root.title("wm min/max") # this removes the maximize button root.resizable(0,0) # # if on MS Windows, this might do the trick, # # but I wouldn't know: # root.attributes(toolwindow=1) # # for no window manager decorations at all: # root.overrideredirect(1) # # useful for something like a splash screen root.mainloop() There is also the possibility that, for a `Toplevel` window other than the root one, you can do: toplevel.transient(1) and this will remove the min/max buttons, but it also depends on the window manager. From what I read, the MS Windows WM does remove them.
pythonic way to do something N times without an index variable? Question: Every day I love python more and more. Today, I was writing some code like: for i in xrange(N): do_something() I had to do something N times. But each time didn't depend on the value of `i` (index variable). I realized that I was creating a variable I never used (`i`), and I thought "There surely is a more pythonic way of doing this without the need for that useless index variable." So... the question is: do you know how to do this simple task in a more (pythonic) beautiful way? Answer: A slightly faster approach than looping on `xrange(N)` is: import itertools for _ in itertools.repeat(None, N): do_something()
Available disk space on an SMB share, via Python Question: Does anyone know a way to get the amount of space available on a Windows (Samba) share via Python 2.6 with its standard library? (also running on Windows) e.g. >>> os.free_space("\\myshare\folder") # return free disk space, in bytes 1234567890 Answer: If [PyWin32](http://sourceforge.net/projects/pywin32/) is available: free, total, totalfree = win32file.GetDiskFreeSpaceEx(r'\\server\share') Where _free_ is a amount of free space available to the current user, and _totalfree_ is amount of free space total. Relevant documentation: [PyWin32 docs](http://docs.activestate.com/activepython/2.4/pywin32/win32file__GetDiskFreeSpaceEx_meth.html), [MSDN](http://msdn.microsoft.com/en-us/library/aa364937%28VS.85%29.aspx). If PyWin32 is not guaranteed to be available, then for Python 2.5 and higher there is [ctypes module](http://docs.python.org/library/ctypes.html) in stdlib. Same function, using ctypes: import sys from ctypes import * c_ulonglong_p = POINTER(c_ulonglong) _GetDiskFreeSpace = windll.kernel32.GetDiskFreeSpaceExW _GetDiskFreeSpace.argtypes = [c_wchar_p, c_ulonglong_p, c_ulonglong_p, c_ulonglong_p] def GetDiskFreeSpace(path): if not isinstance(path, unicode): path = path.decode('mbcs') # this is windows only code free, total, totalfree = c_ulonglong(0), c_ulonglong(0), c_ulonglong(0) if not _GetDiskFreeSpace(path, pointer(free), pointer(total), pointer(totalfree)): raise WindowsError return free.value, total.value, totalfree.value Could probably be done better but I'm not really familiar with ctypes.
Call another classes method in Python Question: I'm tying to create a class that holds a reference to another classes method. I want to be able to call the method. It is basically a way to do callbacks. My code works until I try to access a class var. When I run the code below, I get the error What am I doing wrong? Brian import logging class yRunMethod(object): """ container that allows method to be called when method run is called """ def __init__(self, method, *args): """ init """ self.logger = logging.getLogger('yRunMethod') self.logger.debug('method <%s> and args <%s>'%(method, args)) self.method = method self.args = args def run(self): """ runs the method """ self.logger.debug('running with <%s> and <%s>'%(self.method,self.args)) #if have args sent to function if self.args: self.method.im_func(self.method, *self.args) else: self.method.im_func(self.method) if __name__ == "__main__": import sys #create test class class testClass(object): """ test class """ def __init__(self): """ init """ self.var = 'some var' def doSomthing(self): """ """ print 'do somthing called' print 'self.var <%s>'%self.var #test yRunMethod met1 = testClass().doSomthing run1 = yRunMethod(met1) run1.run() Answer: I think you're making this **WAY** too hard on yourself (which is easy to do ;-). Methods of classes and instances are first-class objects in Python. You can pass them around and call them like anything else. Digging into a method's instance variables is something that should almost never be done. A simple example to accomplish your goal is: class Wrapper (object): def __init__(self, meth, *args): self.meth = meth self.args = args def runit(self): self.meth(*self.args) class Test (object): def __init__(self, var): self.var = var def sayHello(self): print "Hello! My name is: %s" % self.var t = Test('FooBar') w = Wrapper( t.sayHello ) w.runit()
I'm getting an error when trying to open a website url with Python 3.1, urllib & json: operation was attempted on something that is not a socket Question: I'm getting an error when trying to open a website url with Python 3.1, urllib & json urllib.error.URLError: Here's the code. The first website loads fine. The second one import json import urllib.request import urllib.parse import util # This one works fine response = urllib.request.urlopen('http://python.org/') html = response.read() print(html) # parms - CSV filename, company, .... p_filename = "c:\\temp\\test.csv" jg_token = "zzzzzzzzzzzzzzzzzzzzzzzzz" jg_proto = "https://" jg_webst = "www.jigsaw.com/rest/" jg_cmd_searchContact = "searchContact.json" jg_key_companyName = "companyName" jg_key_levels = "levels" jg_key_departments = "departments" jg_args = { "token":jg_token, jg_key_companyName: "Technical Innovations", jg_key_departments: "HR" } jg_url = jg_proto + jg_webst + jg_cmd_searchContact + "?" + urllib.parse.urlencode(jg_args) # This one generates teh error result = json.load(urllib.request.urlopen(jg_url)) urllib.error.URLError: File "c:\dev\xdev\PyJigsaw\searchContact.py", line 46, in result = json.load(urllib.request.urlopen(jg_url)) File "c:\dev\tdev\Python31\Lib\urllib\request.py", line 121, in urlopen return _opener.open(url, data, timeout) File "c:\dev\tdev\Python31\Lib\urllib\request.py", line 349, in open response = self._open(req, data) File "c:\dev\tdev\Python31\Lib\urllib\request.py", line 367, in _open '_open', req) File "c:\dev\tdev\Python31\Lib\urllib\request.py", line 327, in _call_chain result = func(*args) File "c:\dev\tdev\Python31\Lib\urllib\request.py", line 1098, in https_open return self.do_open(http.client.HTTPSConnection, req) File "c:\dev\tdev\Python31\Lib\urllib\request.py", line 1075, in do_open raise URLError(err) Answer: Please edit the title and tags and maybe even the question body: This has nothing to do with JSON and everything to do with Windows. It's also at a lower level than urllib. (Probably in the SSL code.) Distilled: Both of the following approaches fail on Python 3.1.2 for Vista, but work fine on Linux (Python 3.1.3) print( HTTPSConnection(hostname).request('GET',url).getresponse().read() ) print( urllib.request.urlopen('https://'+hostname+url).read() ) Change them to not use SSL, and then they work fine on Windows: print( HTTPConnection(hostname).request('GET',url).getresponse().read() ) print( urllib.request.urlopen('http://'+hostname+url).read() )
how to pass an xml file to lxml to parse? Question: I'm trying to parse an xml file using lxml. xml.etree allowed me to simply pass the file name as a parameter to the `parse` function, so I attempted to do the same with lxml. My code: from lxml import etree from lxml import objectify file = "C:\Projects\python\cb.xml" tree = etree.parse(file) but I get the error: Traceback (most recent call last): File "cb.py", line 5, in <module> tree = etree.parse(file) File "lxml.etree.pyx", line 2698, in lxml.etree.parse (src/lxml/lxml.etree.c:4 9590) File "parser.pxi", line 1491, in lxml.etree._parseDocument (src/lxml/lxml.etre e.c:71205) File "parser.pxi", line 1520, in lxml.etree._parseDocumentFromURL (src/lxml/lx ml.etree.c:71488) File "parser.pxi", line 1420, in lxml.etree._parseDocFromFile (src/lxml/lxml.e tree.c:70583) File "parser.pxi", line 975, in lxml.etree._BaseParser._parseDocFromFile (src/ lxml/lxml.etree.c:67736) File "parser.pxi", line 539, in lxml.etree._ParserContext._handleParseResultDo c (src/lxml/lxml.etree.c:63820) File "parser.pxi", line 625, in lxml.etree._handleParseResult (src/lxml/lxml.e tree.c:64741) File "parser.pxi", line 565, in lxml.etree._raiseParseError (src/lxml/lxml.etr ee.c:64084) lxml.etree.XMLSyntaxError: AttValue: " or ' expected, line 2, column 26 What am I doing wrong? Answer: What you are doing wrong is (1) not checking whether you got the same outcome by using `xml.etree` on the same file (2) not reading the error message, which indicates a syntax error in line 2 of the file, way down stream from any file- opening issue
Do you use Python mostly for its functional or object-oriented features? Question: I see what seems like a majority of Python developers on StackOverflow endorsing the use of concise functional tools like lambdas, maps, filters, etc., while others say their code is clearer and more maintainable by not using them. What is your preference? Also, if you are a die-hard functional programmer or hardcore into OO, what other specific programming practices do you use that you think are best for your style? Thanks in advance for your opinions! Answer: I mostly use Python using object-oriented and procedural styles. Python is actually not particularly well-suited to functional programming. A lot of people think they are writing functional Python code by using lots of `lambda`, `map`, `filter`, and `reduce`, but this is a bit over-simplified. The hallmark feature of functional programming is a lack of state or side effects. Important elements of a functional style are pure functions, recursive algorithms, and first class functions. Here are my thoughts on functional programming and Python: * **Pure functions are great.** I do my best to make my module-level functions pure. * Pure functions can be tested. Since they do not depend on outside state, they are much easier to test. * Pure functions are able to support other optimizations, such as memoization and trivial parallelization. * **Class-based programming can be pure.** If you want an equivalent to pure functions using Python classes (which is sometimes but not always what you want), * Make your instances immutable. In particular, this mainly means to make your methods always return new instances of your class rather than changing the current one. * Use dependency injection rather than getting stuff (like imported module) from global scope. * This might not always be exactly what you want. * **Don't try to avoid state all together.** This isn't a reasonable strategy in Python. For example, use `some_list.append(foo)` rather than `new_list = some_list + [foo]`, the former of which is more idiomatic and efficient. (Indeed, a ton of the "functional" solutions I see people use in Python are algorithmically suboptimal compared to just-as-simple or simpler solutions that are not functional or are just as functional but don't use the functional-looking tools.) * Learn the best lessons from functional programming, for example **mutable state is dangerous.** Ask yourself, _Do I really want to change this X or do I want a new X?_ * One really common place this comes up is when processing a list. I would use foo = [bar(item.baz()) for item in foo] rather than for index, _ in enumerate(foo): foo[index] = bar(foo[index].baz()) and stuff like it. This avoids confusing bugs where the same list object is stored elsewhere and shouldn't be changed. (If it _should_ be changed, then there is a decent chance you have a design error. Mutating some list you have referenced multiple places isn't a great way to share state.) * **Don't use`map` and friends gratuitously.** There is nothing more functional about doing this. * `map`/`filter` are **not** more functional than list comprehensions. List comprehensions were borrowed from Haskell, a pure functional language. `map` and especially `filter` can be harder to understand than a list comprehension. I would never use `map` or `filter` with a lambda but might if I had a function that already existed; I use `map` a decent bit. * The same goes for `itertools.imap`/`ifilter` compared to generator expressions. (These things are somewhat lazy, which is something great we can borrow from the functional world.) * Don't use `map` and `filter` for side effects. I see this with `map` a lot, which both makes hard-to-understand code, unneeded lists, and is decidedly not functional (despite people thinking it must be because of `map`.) Just use a for loop. * `reduce` is confusing except for very simple cases. Python has for loops and there is no hurt in using them. * **Don't use recursive algorithms.** This is one part of functional programming Python just does not support well. CPython (and I think all other Pythons) do not support tail call optimization. **Use iteration instead.** * **Only use`lambda` when you are defining functions on the fly.** Anonymous functions aren't better than named functions, the latter of which are often more robust, maintainable, and documented.
python floating number Question: i am kind of confused why python add some additional decimal number in this case, please help to explain >>> mylist = ["list item 1", 2, 3.14] >>> print mylist ['list item 1', 2, 3.1400000000000001] Answer: Floating point numbers are an approximation, they cannot store decimal numbers exactly. Because they try to represent a very large range of numbers in only 64 bits, they must approximate to some extent. It is very important to be aware of this, because it results in some weird side-effects. For example, you might very reasonably think that the sum of ten lots of `0.1` would be `1.0`. While this seems logical, it is also wrong when it comes to floating point: >>> f = 0.0 >>> for _ in range (10): ... f += 0.1 ... >>> print f == 1.0 False >>> f 0.99999999999999989 >>> str(f) 1.0 You might think that `n / m * m == n`. Once again, floating-point world disagrees: >>> (1.0 / 103.0) * 103.0 0.99999999999999989 Or perhaps just as strangely, one might think that for all `n`, `n + 1 != n`. In floating point land, numbers just don't work like this: >>> 10.0**200 9.9999999999999997e+199 >>> 10.0**200 == 10.0**200 + 1 True # How much do we have to add to 10.0**200 before its # floating point representation changes? >>> 10.0**200 == 10.0**200 + 10.0**183 True >>> 10.0**200 == 10.0**200 + 10.0**184 False See [What every computer scientist should know about floating point numbers](http://docs.sun.com/source/806-3568/ncg_goldberg.html) for an excellent summary of the issues. If you need exact decimal representation, check out the [decimal](http://docs.python.org/library/decimal.html) module, part of the python standard library since 2.4. It allows you to specify the number of significant figures. The downside is, it is much slower than floating point, because floating point operations are implemented in hardware whereas decimal operations happen purely in software. It also has its own imprecision issues, but if you need exact representation of decimal numbers (e.g. for a financial application) it's ideal. For example: >>> 3.14 3.1400000000000001 >>> import decimal >>> decimal.Decimal('3.14') >>> print decimal.Decimal('3.14') 3.14 # change the precision: >>> decimal.getcontext().prec = 6 >>> decimal.Decimal(1) / decimal.Decimal(7) Decimal('0.142857') >>> decimal.getcontext().prec = 28 >>> decimal.Decimal(1) / decimal.Decimal(7) Decimal('0.1428571428571428571428571429')
Use LaTeX Listings to correctly detect and syntax highlight embedded code of a different language in a script Question: I have scripts that have one-liners or sort scripts from other languages within them. How can I have LaTeX listings detect this and change the syntax formating language within the script? This would be especially useful for awk within bash I believe. Bash #!/bin/bash echo "hello world" R --vanilla << EOF # Data on motor octane ratings for various gasoline blends x <- c(88.5,87.7,83.4,86.7,87.5,91.5,88.6,100.3, 95.6,93.3,94.7,91.1,91.0,94.2,87.5,89.9, 88.3,87.6,84.3,86.7,88.2,90.8,88.3,98.8, 94.2,92.7,93.2,91.0,90.3,93.4,88.5,90.1, 89.2,88.3,85.3,87.9,88.6,90.9,89.0,96.1, 93.3,91.8,92.3,90.4,90.1,93.0,88.7,89.9, 89.8,89.6,87.4,88.9,91.2,89.3,94.4,92.7, 91.8,91.6,90.4,91.1,92.6,89.8,90.6,91.1, 90.4,89.3,89.7,90.3,91.6,90.5,93.7,92.7, 92.2,92.2,91.2,91.0,92.2,90.0,90.7) x length(x) mean(x);var(x) stem(x) EOF perl -n -e ' @t = split(/\t/); %t2 = map { $_ => 1 } split(/,/,$t[1]); $t[1] = join(",",keys %t2); print join("\t",@t); ' knownGeneFromUCSC.txt awk -F'\t' '{ n = split($2, t, ","); _2 = x split(x, _) # use delete _ if supported for (i = 0; ++i <= n;) _[t[i]]++ || _2 = _2 ? _2 "," t[i] : t[i] $2 = _2 }-3' OFS='\t' infile Python #!/usr/local/bin/python print "Hello World" os.system(""" VAR=even; sed -i "s/$VAR/odd/" testfile; for i in `cat testfile` ; do echo $i; done; echo "now the tr command is removing the vowels"; cat testfile |tr 'aeiou' ' ' """) UPDATE: These are my current Listings settings in the preamble: % This gives syntax highlighting in the python environment \renewcommand{\lstlistlistingname}{Code Listings} \renewcommand{\lstlistingname}{Code Listing} \definecolor{gray}{gray}{0.5} \definecolor{key}{rgb}{0,0.5,0} \lstloadlanguages{Fortran,C++,C,[LaTeX]TeX,Python,bash,R, Perl} \lstnewenvironment{python}[1][]{ \lstset{ language=python, basicstyle=\ttfamily\small, otherkeywords={1, 2, 3, 4, 5, 6, 7, 8 ,9 , 0, -, =, +, [, ], (, ), \{, \}, :, *, !}, keywordstyle=\color{blue}, stringstyle=\color{red}, showstringspaces=false, emph={class, pass, in, for, while, if, is, elif, else, not, and, or, def, print, exec, break, continue, return}, emphstyle=\color{black}\bfseries, emph={[2]True, False, None, self}, emphstyle=[2]\color{key}, emph={[3]from, import, as}, emphstyle=[3]\color{blue}, upquote=true, morecomment=[s]{"""}{"""}, commentstyle=\color{gray}\slshape, rulesepcolor=\color{blue},#1 } }{} \lstnewenvironment{bash}{% \lstset{% language=bash, otherkeywords={=, +, [, ], (, ), \{, \}, *}, % bash commands from: %http://www.math.montana.edu/Rweb/Rhelp/00Index.html emph={addgroup,adduser,alias, ant, apropos,apt-get,aptitude,aspell,awk, basename,bash,bc,bg,break,builtin,bzip2,cal,case,cat,cd,cfdisk,chgrp, chkconfig,chmod,chown,chroot,cksum,clear,cmp,comm,command,continue, cp,cron,crontab,csplit,cut,date,dc,dd,ddrescue,declare,df,diff,diff3, dig,dir,dircolors,dirname,dirs,dmesg,du,echo,egrep,eject,enable,env, ethtool,eval,exec,exit,expand,expect,export,expr,false,fdformat, fdisk,fg,fgrep,file,find,fmt,fold,for,format,free,fsck,ftp,function, fuser,gawk,getopts, git, grep,groups,gzip, gunzip, ,hash,head,help,history,hostname, id,if,ifconfig,ifdown,ifup,import,install, java, java6, java_cur join,kill,killall,less, let,ln,local,locate,logname,logout,look,lpc,lpr,lprint,lprintd, lprintq,lprm,ls,lsof,make,man,mkdir,mkfifo,mkisofs,mknod,mmv,more, mount,mtools,mtr,mv, mysql, netstat,nice,nl,nohup,notify-send, noweb,noweave, nslookup,op, open,passwd,paste,pathchk,ping,pkill,popd,pr,printcap,printenv, printf,ps,pushd,pwd,quota,quotacheck,quotactl,ram,rcp,read, readarray,readonly,reboot,remsync,rename,renice,return,rev,rm,rmdir, rsync,scp,screen,sdiff,sed,select,seq,set,sftp,shift,shopt,shutdown, sleep,slocate,sort,source,split,ssh,strace,su,sudo,sum, svn, svn2git, symlink,sync, tail,tar,tee,test,time,times,top,touch,tr,traceroute,trap,true, tsort,tty,type,ulimit,umask,umount,unalias,uname,unexpand,uniq, units, unrar, unset,unshar,until,useradd,usermod,users,uudecode,uuencode, vdir,vi,vmstat,watch,wc,Wget,whereis,which,while,who,whoami,write, zcat}, breaklines=true, keywordstyle=\color{blue}, stringstyle=\color{red}, emphstyle=\color{black}\bfseries, commentstyle=\color{gray}\slshape, } }{} \lstnewenvironment{latexCode}[1]{\lstset{language=[latex]tex} \lstset{#1}}{} \lstnewenvironment{Rcode}{ \lstset{% language={R}, basicstyle=\small, % print whole listing small keywordstyle=\color{black}, % style for keyword % Function list from: % http://www.math.montana.edu/Rweb/Rhelp/00Index.html emph={abbreviate, abline, abs, acos, acosh, all, all.names, all.vars, anova, anova.glm, anova.lm, any, aperm, append, apply, approx, approxfun, apropos, Arg, args, Arithmetic, array, arrows, as.array, as.call, as.character, as.complex, as.data.frame, as.double, as.expression, as.factor, asin, asinh, as.integer, as.list, as.logical, as.matrix, as.na, as.name, as.null, as.numeric, as.ordered, as.qr, as.real, assign, as.ts, as.vector, atan, atan2, atanh, attach, attr, attributes, autoload, .AutoloadEnv, axis, backsolve, barplot, beta, binomial, box, boxplot, boxplot.stats, break, browser, bw.bcv, bw.sj, bw.ucv, bxp, c, .C, call, cat, cbind, ceiling, character, charmatch, chisq.test, chol, chol2inv, choose, class, class<-, codes, coef, coefficients, coefficients.glm, coefficients.lm, co.intervals, col, colnames, colors, colours, Comparison, complete.cases, complex, Conj, contour, contrasts, contr.helmert, contr.poly, contr.sum, contr.treatment, convolve, cooks.distance, coplot, cor, cos, cosh, count.fields, cov, covratio, crossprod, cummax, cummin, cumprod, cumsum, curve, cut, D, data, data.class, data.entry, dataentry, data.frame, data.matrix, dbeta, dbinom, dcauchy, dchisq, de, debug, delay, demo, de.ncols, density, deparse, de.restore, deriv, deriv.default, deriv.formula, de.setup, detach, deviance, deviance.glm, deviance.lm, device, Devices, dev.off, dexp, df, dfbetas, dffits, df.residual, df.residual.glm, df.residual.lm, dgamma, dgeom, dget, dhyper, diag, diff, digamma, dim, dim<-, dimnames, dimnames<-, dlnorm, dlogis, dnbinom, dnchisq, dnorm, do.call, dotplot, double, dpois, dput, drop, dt, dump, dunif, duplicated, dweibull, dyn.load, edit, effects.glm, effects.lm, eigen, else, emacs, end, environment, environment<-, eval, exists, exp, expression, Extract, factor, family, family.glm, fft, finite, fitted, fitted.values, fitted.values.glm, fitted.values.lm, fivenum, fix, floor, for, formals, format, formatC, format.default, formula.default, formula.formula, formula.terms, .Fortran, frame, frequency, function, Gamma, gamma, gaussian, gc, gcinfo, get, getenv, gl, glm, glm.control, glm.fit, .GlobalEnv, graphics.off, gray, grep, grid, gsub, hat, heat.colors, help, hist, hsv, identify, if, ifelse, Im, image, \%in\%, influence.measures, inherits, integer, interactive, .Internal, inverse.gaussian, invisible, invisible, IQR, is.array, is.atomic, is.call, is.character, is.complex, is.data.frame, is.double, is.environment, is.expression, is.factor, is.function, is.integer, is.language, is.list, is.loaded, is.logical, is.matrix, is.na, is.name, is.null, is.numeric, is.ordered, is.qr, is.real, is.recursive, is.single, is.ts, is.unordered, is.vector, lapply, lbeta, lchoose, legend, length, LETTERS, letters, levels, levels<-, lgamma, .lib.loc, .Library, library, library.dynam, license, lines, lines.default, list, lm, lm.fit, lm.influence, lm.wfit, load, locator, log, log10, log2, Logic, logical, lower.tri, lowess, ls, ls.diag, lsfit, lsf.str, ls.print, ls.str, .Machine, Machine, machine, macintosh, mad, match, match.arg, match.call, matlines, mat.or.vec, matplot, matpoints, matrix, max, mean, median, menu, methods, min, missing, Mod, mode, mode<-, model.frame, model.frame.default, model.matrix, model.matrix.default, month.abb, month.name, mtext, mvfft, NA, na.action, na.action.default, na.fail, names, na.omit, nargs, nchar, NCOL, ncol, next, NextMethod, nextn, nlevels, nlm, [.noquote, noquote, NROW, nrow, NULL, numeric, objects, on.exit, optimize, options, order, ordered, outer, pairs, palette, par, parse, paste, pbeta, pbinom, pcauchy, pchisq, pentagamma, pexp, pf, pgamma, pgeom, phyper, pi, pictex, piechart, plnorm, plogis, plot, plot.default, plot.density, plot.ts, plot.xy, pmatch, pmax, pmin, pnbinom, pnchisq, pnorm, points, points.default, poisson, polygon, polyroot, postscript, ppoints, ppois, pretty, print, print.anova.glm, print.anova.lm, print.data.frame, print.default, print.density, print.formula, print.glm, print.lm, print.noquote, print.plot, print.summary.glm, print.summary.lm, print.terms, print.ts, proc.time, prod, prompt, prompt.default, prop.test, provide, .Provided, ps.options, pt, punif, pweibull, q, qbeta, qbinom, qcauchy, qchisq, qexp, qf, qgamma, qgeom, qhyper, qlnorm, qlogis, qnbinom, qnchisq, qnorm, qpois, qqline, qqnorm, qqplot, qr, qr.coef, qr.fitted, qr.Q, qr.qty, qr.qy, qr.R, qr.resid, qr.solve, qr.X, qt, quantile, quasi, quit, qunif, quote, qweibull, rainbow, .Random.seed, range, rank, rbeta, rbind, rbinom, rcauchy, rchisq, Re, readline, read.table, real, rect, remove, rep, repeat, replace, require, resid, residuals, residuals.glm, residuals.lm, return, rev, rexp, rf, rgamma, rgb, rgeom, rhyper, RLIBS, rlnorm, rlogis, rm, rnbinom, rnchisq, rnorm, round, row, row.names, rownames, rpois, rstudent, rt, runif, rweibull, sample, sapply, save, save.plot, scale, scan, sd, segments, seq, sequence, sign, signif, sin, sinh, sink, solve, solve.qr, sort, source, spline, splinefun, split, sqrt, start, stem, stop, storage.mode, storage.mode<-, str, str.data.frame, str.default, strheight, stripplot, strsplit, structure, strwidth, sub, Subscript, substitute, substr, substring, sum, summary, summary.glm, summary.lm, svd, sweep, switch, symbol.C, symbol.For, symnum, sys.call, sys.calls, sys.frame, sys.frames, sys.function, sys.nframe, sys.on.exit, sys.parent, sys.parents, system, system.date, system.time, t, table, tabulate, tan, tanh, tapply, tempfile, terms, terms.default, terms.formula, terms.terms, terrain.colors, tetragamma, text, time, title, topo.colors, trace, traceback, trigamma, trunc, ts, tsp, t.test, typeof, unclass, undebug, unique, uniroot, unlink, unlist, untrace, update, update.formula, update.glm, update.lm, upper.tri, UseMethod, var, vector, Version, version, vi, warning, weighted.mean, weights.lm, while, window, windows, write, x11, xedit, xemacs, xinch, xor, xy.coords, yinch}, % define a list of word to emphasis stringstyle=\color{red}, emphstyle=\color{black}\bfseries, % define the way to emphase showspaces=false, % show the space in code, or not stringstyle=\ttfamily, % style of the string (like "hello word") showstringspaces=false, % show the space in string, on not #1 commentstyle=\color{gray}\slshape, tabsize=2, % sets default tabsize to 2 spaces breaklines=true, % sets automatic line breaking breakatwhitespace=false, % sets if automatic breaks should only happen at whitespace } }{} \lstnewenvironment{Perl}{ \lstset{% language={perl}, basicstyle=\small, % print whole listing small keywordstyle=\color{black}, % style for keyword emph={% From http://www.sdsc.edu/~moreland/courses/IntroPerl/docs/manual/pod/perlfunc.html -X, run, abs, absolute, accept, accept, alarm, schedule, atan2, arctangent, bind, binds, binmode, prepare, bless, create, caller, get, chdir, change, chmod, changes, chomp, remove, chop, remove, chown, change, chr, get, chroot, make, close, close, closedir, close, connect, connect, continue, optional, cos, cosine, crypt, one-way, dbmclose, breaks, dbmopen, create, defined, test, delete, deletes, die, raise, do, turn, dump, create, each, retrieve, endgrent, be, endhostent, be, endnetent, be, endprotoent, be, endpwent, be, endservent, be, eof, test, eval, catch, exec, abandon, exists, test, exit, terminate, exp, raise, fcntl, file, fileno, return, flock, lock, fork, create, format, declare, formline, internal, getc, get, getgrent, get, getgrgid, get, getgrnam, get, gethostbyaddr, get, gethostbyname, get, gethostent, get, getlogin, return, getnetbyaddr, get, getnetbyname, get, getnetent, get, getpeername, find, getpgrp, get, getppid, get, getpriority, get, getprotobyname, get, getprotobynumber, get, getprotoent, get, getpwent, get, getpwnam, get, getpwuid, get, getservbyname, get, getservbyport, get, getservent, get, getsockname, retrieve, getsockopt, get, glob, expand, gmtime, convert, goto, create, grep, locate, hex, convert, import, patch, int, get, ioctl, system-dependent, join, join, keys, retrieve, kill, send, last, exit, lc, return, lcfirst, return, length, return, link, create, listen, register, local, create, localtime, convert, log, retrieve, lstat, stat, m//, match, map, apply, mkdir, create, msgctl, SysV, msgget, get, msgrcv, receive, msgsnd, send, my, declare, next, iterate, no, unimport, oct, convert, open, open, opendir, open, ord, find, pack, convert, package, declare, pipe, open, pop, remove, pos, find, print, output, printf, output, prototype, get, push, append, q/STRING/, singly, qq/STRING/, doubly, quotemeta, quote, qw/STRING/, quote, qx/STRING/, backquote, rand, retrieve, read, fixed-length, readdir, get, readlink, determine, recv, receive, redo, start, ref, find, rename, change, require, load, reset, clear, return, get, reverse, flip, rewinddir, reset, rindex, right-to-left, rmdir, remove, s///, replace, scalar, force, seek, reposition, seekdir, reposition, select, reset, semctl, SysV, semget, get, semop, SysV, send, send, setgrent, prepare, sethostent, prepare, setnetent, prepare, setpgrp, set, setpriority, set, setprotoent, prepare, setpwent, prepare, setservent, prepare, setsockopt, set, shift, remove, shmctl, SysV, shmget, get, shmread, read, shmwrite, write, shutdown, close, sin, return, sleep, block, socket, create, socketpair, create, sort, sort, splice, add, split, split, sprintf, formatted, sqrt, square, srand, seed, stat, get, study, optimize, sub, declare, substr, get, symlink, create, syscall, execute, sysread, fixed-length, system, run, syswrite, fixed-length, tell, get, telldir, get, tie, bind, time, return, times, return, tr///, transliterate, truncate, shorten, uc, return, ucfirst, return, umask, set, undef, remove, unlink, remove, unpack, convert, unshift, prepend, untie, break, use, load, utime, set, values, return, vec, test, wait, wait, waitpid, wait, wantarray, get, warn, print, write, print, y///, transliterate}, % define a list of word to emphasis stringstyle=\color{red}, emphstyle=\color{black}\bfseries, % define the way to emphase showspaces=false, % show the space in code, or not stringstyle=\ttfamily, % style of the string (like "hello word") showstringspaces=false, % show the space in string, on not #1 commentstyle=\color{gray}\slshape, tabsize=2, % sets default tabsize to 2 spaces breaklines=true, % sets automatic line breaking breakatwhitespace=false, % sets if automatic breaks should only happen at whitespace } }{} \lstnewenvironment{plaintext}{ \lstset{ tabsize=2, % sets default tabsize to 2 spaces breaklines=true, % sets automatic line breaking breakatwhitespace=false, % sets if automatic breaks should only happen at whitespace basicstyle=\normalfont\ttfamily, } }{} Answer: It is almost certainly easier to modify the Bash/Python highlighters than to write a context-sensitive highlighter. I'm guessing that just adding the keywords to the other highlighters should give acceptable results. Modifying Pygments doesn't look too difficult, from Pygments' [Write your own lexer](http://pygments.org/docs/lexerdevelopment/) documentation.
What is the difference between a module and a script in Python? Question: Think the title summarizes the question :-) Answer: A script is generally a directly executable piece of code, run by itself. A module is generally a library, imported by other pieces of code. Note that there's no internal distinction -- both are executable and importable, although library code often won't do anything (or will just run its unit tests) when executed directly and importing code designed to be a script will cause it to execute, hence the common `if __name__ == "__main__"` test.
Xml comparison in Python Question: Building on [another SO question](http://stackoverflow.com/questions/794331/xml-comparison-in-c), how can one check whether two well-formed XML snippets are semantically equal. All I need is "equal" or not, since I'm using this for unit tests. In the system I want, these would be equal (note the order of 'start' and 'end'): <?xml version='1.0' encoding='utf-8' standalone='yes'?> <Stats start="1275955200" end="1276041599"> </Stats> # Reordered start and end <?xml version='1.0' encoding='utf-8' standalone='yes'?> <Stats end="1276041599" start="1275955200" > </Stats> I have lmxl and other tools at my disposal, and a simple function that only allows reordering of attributes would work fine as well! * * * Working snippet based on IanB's answer: from formencode.doctest_xml_compare import xml_compare # have to strip these or fromstring carps xml1 = """ <?xml version='1.0' encoding='utf-8' standalone='yes'?> <Stats start="1275955200" end="1276041599"></Stats>""" xml2 = """ <?xml version='1.0' encoding='utf-8' standalone='yes'?> <Stats end="1276041599" start="1275955200"></Stats>""" xml3 = """ <?xml version='1.0' encoding='utf-8' standalone='yes'?> <Stats start="1275955200"></Stats>""" from lxml import etree tree1 = etree.fromstring(xml1.strip()) tree2 = etree.fromstring(xml2.strip()) tree3 = etree.fromstring(xml3.strip()) import sys reporter = lambda x: sys.stdout.write(x + "\n") assert xml_compare(tree1,tree2,reporter) assert xml_compare(tree1,tree3,reporter) is False Answer: You can use [formencode.doctest_xml_compare](http://bitbucket.org/ianb/formencode/src/tip/formencode/doctest_xml_compare.py#cl-70) \-- the xml_compare function compares two ElementTree or lxml trees.
IDLE wont start Python 2.6.5 Question: I was using it as my primary text editor for quite sometime. However, one day it just stopped working. This had happened to me several times before, so I simply tried to end all procceses using windows task manager. However that didn't work. I've recently tried getting it to work again. Whenever I try to reopen it it informs me that it's subprocess couldn't connect. I tried uninstalling it and reinstalling it, yet the problem persists. Anyone have any other solutions? Important facts: Windows 7, Python 2.6.5 Answer: Honestly I would advise you to stop using IDLE, the fact that it runs program code in the same process as itself caused me a lot of problems when I used it, including things like not refreshing imported modules that were modified. Personally I switched to emacs, but you might like to try something like Notepad++.
Counting the number of messages in an e-mail account with python Question: is there any way, in Python, to have access to an e-mail account (I'll need this for gmail but better if any works) and be able to see the number of messages in the inbox (maybe even unread messages only)? Thank you. Answer: **u Can Try This One** import imaplib obj = imaplib.IMAP4_SSL('imap.gmail.com', 993) obj.login('username', 'password') obj.select('Inbox') <\-- it will return total number of mail in Inbox i.e ('OK', ['50']) obj.search(None,'UnSeen') <\-- it will return the list of uids for Unseen mails
In Django : How to serialize dict object to json? Question: I have this very basic problem, >>> from django.core import serializers >>> serializers.serialize("json", {'a':1}) Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/lib/pymodules/python2.6/django/core/serializers/__init__.py", line 87, in serialize s.serialize(queryset, **options) File "/usr/lib/pymodules/python2.6/django/core/serializers/base.py", line 40, in serialize for field in obj._meta.local_fields: AttributeError: 'str' object has no attribute '_meta' >>> How can this be done? Answer: Also, since you seem to be using Python 2.6, you could just use the `json` module directly: import json data = json.dumps({'a': 1})
Validating and filling default values in XML based on XSD in Python Question: How do I fill the default value in my XML during validation against XSD? If my attribute is not defined as `use="require"` and have `default="1"`, it could be possible to fill these default values from the XSD to the XML. Example: Original XML: <a> <b/> <b c="2"/> </a> XSD scheme: <xs:element name="a"> <xs:complexType> <xs:sequence> <xs:element name="b" maxOccurs="unbounded"> <xs:attribute name="c" default="1"/> </xs:element> </xs:sequence> </xs:complexType> </xs:element> I want to validate the original XML using XSD and to fill all default values: <a> <b c="1"/> <b c="2"/> </a> How do I get it in Python? With validation there is no problem (e.g. XMLSchema). The problem are the default values. Answer: To follow up on my comment, here's some code from lxml import etree from lxml.html import parse schema_root = etree.XML('''\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="a"> <xs:complexType> <xs:sequence> <xs:element name="b" maxOccurs="unbounded"> <xs:complexType> <xs:attribute name="c" default="1" type="xs:string"/> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>''') xmls = '''<a> <b/> <b c="2"/> </a>''' schema = etree.XMLSchema(schema_root) parser = etree.XMLParser(schema = schema, attribute_defaults = True) root = etree.fromstring(xmls, parser) result = etree.tostring(root, pretty_print=True, method="xml") print result will give you <a> <b c="1"/> <b c="2"/> </a> I've modified your XSD slightly, wrapped `xs:attribute` in `xs:complexType` and added schema namespace. To have your defaults filled in, you need to pass `attribute_defaults=True` to `etree.XMLParser()` and it should work.
2nd Year College - Learning - Microsoft Server Products Question: As the title says, I just finished my first year of college (majoring in Software Engineering). Fortunately my school likes Microsoft enough, and I can get pretty much anything I want that Microsoft sells. I also can get IBM Websphere and the like for free as well. Earlier this year, I set up an oldish computer (2.6 Pentium D, x64) to run ubuntu server headless. I'm predominately a Java developer, so Apache, Maven, Nexus, Sonar, SVN, etc made it onto the machine. It worked really well for personal and school projects, especially team projects (quick ramp up). Anyways, I started to pick up C# to complement my Java knowledge (don't judge me :P), and am interested in working with some of the associated Microsoft equivalents. The machine currently has the Ubuntu install, as well as Windows 7 Ultimate. I do all of my actual development work off my laptop, also running Windows 7 Ultimate. I was wondering what software you would recommend putting on the machine. I’m not actually serving anything off the machine itself, but in Ubuntu I had it doing integration tests with Hudson on every commit, and profiling my applications, etc, etc. The machine would be running headless, and I would remote into it. Here is what I am currently leaning towards / wondering about: * Windows 7 Ultimate vs Windows Server 2008 (R2) (no one is really clear why I should go with one over the other) * Windows Team Foundation * Sharepoint (Never used it before, kind of meh about it) * IBM Websphere or Glassfish (Some Java EE web server) * SQL Server 2008 * A DVCS In order to better control product conflicts / limit resource use, I’m wondering if I should install things into virtual machines (I can get VmWare or Microsoft Virtualization Products) I also plan on installing everything I had running under Linux (it’s almost entirely Java based development software, so it’ll run on both, only reason I went with ubuntu during the year was because the apache build seemed better). I’m primarily looking to become familiar with enterprise software development tools, as well as get something functional that will help my development process. (IE, I’ll still use project and assign tasks even though I might be the only one to assign tasks to, just to practice doing so). Is there any other software / configuration details I should explore? Opinions on my current list? I primarily use C#, Java, and PHP. I'm familiar with ruby, and python as well. Thanks! Answer: I can confirm that as long as you have the resources for VMs, then that is a very smart way to go with installing many test environments, Windows does well in these. I want to tell you from personal experience, that Windows Server 2008 (and the like) is a much better way to go than Windows 7/Vista. Microsoft puts a great deal more efforts into building their server OS's than they do into the client-side counterparts. My experience goes as far back as alpha testing for Microsoft for Windows Vista, and Server Longhorn. In every situation and setup I had/used/built, Windows Server was always a more stable system. As for viruses, they don't exist in Windows Server, they do however find themselves into relatively clean/un used Vista/7 systems (not mine however). I can give you many more reasons and examples from my experience if you like. I would be happy to help, as security/stability is important and in my business I put it first, and will gladly help someone else. Use Windows Defender! its impressively successful in Windows Server, and use freeware software such as spybot Search & Destroy for your Windows OS protection. As for coding, I highly recommend using Notepad++ as it has code coloring and supports a huge assortment of coding languages. Great interface and awesome to use. ...Feel free to ask for more. I specialize in Windows/Windows Server in my business.
Python : get all exe files in current directory and run them? Question: First of all this is not homework, I'm in a desperate need for a script that will do the following, my problem is, I've never had to deal with python before so I barely know how to use it - and I need it to launch unit tests in TeamCity via a commandline build runner What I need exactly is : a *.bat file that will run the script a python script that will : * get all *_test.exe files in the current working directory * run all the files which were the result of the search Best regards Answer: import glob, os def solution(): for fn in glob.glob("*_text.exe"): os.startfile(fn)
Can Python ctypes load a 32bit C library on x86-64? Question: I have a 64 bit RHEL host with 32 bit libraries installed. One vendor has a 32 bit .so I'd like to load into Python using ctypes. from ctypes import CDLL CDLL('32bitdinosaur.so') OSError: 32bitdinosaur.so: wrong ELF class: ELFCLASS32 Of course 64 bit libraries are OK. Eg: CDLL('libc.so.6') Works fine. Answer: It looks like the best way to do this is to have a 32 bit python in a separate process load the .so, and call the 32 bit python from a 64 bit Python.
How exactly does a python (django) request happen? does it have to reparse all the codebase? Question: With a scripting language like python (or php), things are not compiled down to bytecode like in .net or java. So does this mean that on every request, it has to go through the entire application and parse/compile it? Or at least all the code required for the given call stack? Answer: > With a scripting language like python (or php), things are not compiled down > to bytecode like in .net or java. Wrong: everything you `import` in Python gets compiled to bytecode (and saved as `.pyc` files if you can write to the directory containing the source you're importing -- standard libraries &c are generally pre-compiled, depending on the installation choices of course). Just keep the main script short and simple (importing some module and calling a function in it) and you'll be using compiled bytecode throughout. (Python's compiler is designed to be extremely fast -- with implications including that it doesn't do a lot of otherwise reasonable optimizations -- but avoiding it altogether is still faster;-).
Python script to delete old SVN files lacks permission Question: I'm trying to delete old SVN files from directory tree. `shutil.rmtree` and `os.unlink` raise `WindowsError`s, because the script doesn't have permissions to delete them. How can I get around that? Here is the script: # Delete all files of a certain type from a direcotry import os import shutil dir = "c:\\" verbosity = 0; def printCleanMsg(dir_path): if verbosity: print "Cleaning %s\n" % dir_path def cleandir(dir_path): printCleanMsg(dir_path) toDelete = [] dirwalk = os.walk(dir_path) for root, dirs, files in dirwalk: printCleanMsg(root) toDelete.extend([root + os.sep + dir for dir in dirs if '.svn' == dir]) toDelete.extend([root + os.sep + file for file in files if 'svn' in file]) print "Items to be deleted:" for candidate in toDelete: print candidate print "Delete all %d items? [y|n]" % len(toDelete) choice = raw_input() if choice == 'y': deleted = 0 for filedir in toDelete: if os.path.exists(filedir): # could have been deleted already by rmtree try: if os.path.isdir(filedir): shutil.rmtree(filedir) else: os.unlink(filedir) deleted += 1 except WindowsError: print "WindowsError: Couldn't delete '%s'" % filedir print "\nDeleted %d/%d files." % (deleted, len(toDelete)) exit() if __name__ == "__main__": cleandir(dir) Not a single file is able to be deleted. What am I doing wrong? Answer: Subversion usually makes all the `.svn` directories (and everything in them) write protected. Probably you have to remove the write protection before you can remove the files. I'm not really sure how to do this best with Windows, but you should be able to use [`os.chmod()`](http://docs.python.org/library/os.html?highlight=chmod#os.chmod) with the `stat.S_IWRITE` flag. Probably you have to iterate through all the files in the `.svn` directories and make them all writable individually.
what is a fast way to output h5py dataset to text? Question: I am using the h5py python package to read files in HDF5 format. (e.g. somefile.h5) I would like to write the contents of a dataset to a text file. For example, I would like to create a text file with the following contents: 1,20,31,75,142,324,78,12,3,90,8,21,1 I am able to access the dataset in python using this code: import h5py f = h5py.File('/Users/Me/Desktop/thefile.h5', 'r') group = f['/level1/level2/level3'] dset = group['dsetname'] My naive approach is too slow, because my dataset has over 20000 entries: # write all values to file for index in range(len(dset)): # do not add comma after last value if index == len(dset)-1: txtfile.write(repr(dset[index])) else: txtfile.write(repr(dset[index])+',') txtfile.close() return None Is there a faster way to write this to a file? Perhaps I could convert the dataset into a NumPy array or even a Python list, and then use some file- writing tool? (I could experiment with concatenating the values into a larger string before writing to file, but I'm hoping there's something entirely more elegant) Answer: Building a large string has the huge advantage of saving the need for the goofy "last-time switch" thanks to the excellent `join` method of strings: to replace your whole loop, txtfile.write(','.join(repr(item) for item in dset)) I'm not sure how much more elegant you demand your code to be...;-)
Problem about python import with error Question: I have write a small python module with one class and two functions. The skeleton of the module is as following: #file name: test_module.py class TestClass: @classmethod def method1(cls, param1): #to do something pass def __init__(self, param1): #to do something ... def fun1(*params): #to do something ... def fun2(*params): #to do something ... Another py file is a small script which imports function and class from the module, as following: import sys from test_module import TestClass, fun1, fun2 def main(sys_argv): li = range(5) inst1 = TestClass(li) fun1(inst1) fun2(inst1) return if __name__ == "__main__": main(sys.argv) But when I execute the script, it is broken with following message: * from: can't read /var/mail/test_module * ./script.py: line 4: syntax error near unexpected token `(' * ./script.py: line 4: `def main(sys_argv):' I am not sure what the problem is. Is it a problem with import? But when I try to import the module in ipython, everything is just ok. Answer: Add a proper shebang line to your "small script". It's being interpreted as a shell script.
PySerial and IronPython - get strange error Question: I have a device connected to COM31. And the code that I need to create a serial connection looks very simple port = 31 trex_serial = serial.Serial(port - 1, baudrate=19200, stopbits=serial.STOPBITS_ONE, timeout=1) The foollowing code works when I run it using Python2.6, but when executed by IronPython2.6.1, this is what I get: Traceback (most recent call last): File "c:\Python26\lib\site-packages\serial\serialutil.py", line 188, in __init__ File "c:\Python26\lib\site-packages\serial\serialutil.py", line 236, in setPort File "c:\Python26\lib\site-packages\serial\serialcli.py", line 139, in makeDeviceName File "c:\Python26\lib\site-packages\serial\serialcli.py", line 17, in device IndexError: index out of range: 30 I am not sure what is going on. PySerial clearly says that it is IronPython compliant. Any ideas what am I doing wrong? Answer: IronPython is asking .NET what the ports are. They are enumerated differently. Most likely you are asking to open a connection that doesn't exist as far as IronPython/.NET is concerned. To find out the "real" port number, use the following code modified from the pySerial scan examples. Then use the number next to the listed COM. import serial def scan(): #scan for available ports. return a list of tuples (num, name) available = [] for i in range(256): try: s = serial.Serial(i) available.append( (i, s.portstr)) s.close() # explicit close 'cause of delayed GC in java except serial.SerialException: pass #You must add this check, otherwise the scan won't complete except IndexError as Error: pass for n,s in available: print "(%d) %s" % (n,s) return available The output looks like this for me: (0) COM9 (1) COM15 (2) COM16 (3) COM1 (4) COM15 Then when you try to open the connection, use the number on the left NOT the actual COMportNumber - 1. For instance I need to open a connection to COM15, so using the above scan: def IOCardConnect(): try: connection = serial.Serial(4, 115200, timeout=1, parity=serial.PARITY_NONE) print "Connection Succesful" return connection except serial.SerialException as Error: print Error Also, once you are connected, pySerial will expect bytes to write to the connectio, not strings. So make sure you send like this: #Use the built in bytes function to convert to a bytes array. connection.write(bytes('Data_To_Send'))
create a class attribute without going through __setattr__ Question: What I have below is a class I made to easily store a bunch of data as attributes. They wind up getting stored in a dictionary. I override `__getattr__` and `__setattr__` to store and retrieve the values back in different types of units. When I started overriding `__setattr__` I was having trouble creating that initial dicionary in the 2nd line of `__init__` like so... `super(MyDataFile, self).__setattr__('_data', {})` **My question...** Is there an easier way to create a class level attribute with going through `__setattr__`? Also, should I be concerned about keeping a separate dictionary or should I just store everything in `self.__dict__`? #!/usr/bin/env python from unitconverter import convert import re special_attribute_re = re.compile(r'(.+)__(.+)') class MyDataFile(object): def __init__(self, *args, **kwargs): super(MyDataFile, self).__init__(*args, **kwargs) super(MyDataFile, self).__setattr__('_data', {}) # # For attribute type access # def __setattr__(self, name, value): self._data[name] = value def __getattr__(self, name): if name in self._data: return self._data[name] match = special_attribute_re.match(name) if match: varname, units = match.groups() if varname in self._data: return self.getvaras(varname, units) raise AttributeError # # other methods # def getvaras(self, name, units): from_val, from_units = self._data[name] if from_units == units: return from_val return convert(from_val, from_units, units), units def __str__(self): return str(self._data) d = MyDataFile() print d # set like a dictionary or an attribute d.XYZ = 12.34, 'in' d.ABC = 76.54, 'ft' # get it back like a dictionary or an attribute print d.XYZ print d.ABC # get conversions using getvaras or using a specially formed attribute print d.getvaras('ABC', 'cm') print d.XYZ__mm Answer: Your `__setattr__` in the example doesn't _do_ anything except put things in `_data` instead of `__dict__` Remove it. Change your `__getattr__` to use `__dict__`. Store your value and units as a simple 2-tuple.
Python, dictionaries, and chi-square contingency table Question: This is a problem I've been racking my brains on for a long time, so any help would be great. I have a file which contains several lines in the following format (word, time that the word occurred in, and frequency of documents containing the given word within the given instance in time). Below is an example of what the inputfile looks like. #inputfile <word, time, frequency> apple, 1, 3 banana, 1, 2 apple, 2, 1 banana, 2, 4 orange, 3, 1 I have Python class below that I used to create 2-D dictionaries to store the above file using as the key, and frequency as the value: class Ddict(dict): ''' 2D dictionary class ''' def __init__(self, default=None): self.default = default def __getitem__(self, key): if not self.has_key(key): self[key] = self.default() return dict.__getitem__(self, key) wordtime=Ddict(dict) # Store each inputfile entry with a <word,time> key timeword=Ddict(dict) # Store each inputfile entry with a <time,word> key # Loop over every line of the inputfile for line in open('inputfile'): word,time,count=line.split(',') # If <word,time> already a key, increment count try: wordtime[word][time]+=count # Otherwise, create the key except KeyError: wordtime[word][time]=count # If <time,word> already a key, increment count try: timeword[time][word]+=count # Otherwise, create the key except KeyError: timeword[time][word]=count The question that I have pertains to calculating certain things while iterating over the entries in this 2D dictionary. For each word 'w' at each time 't', calculate: 1. The number of documents **with** word 'w' **within** time 't'. (a) 2. The number of documents **without** word 'w' **within** time 't'. (b) 3. The number of documents **with** word 'w' **outside** time 't'. (c) 4. The number of documents **without** word 'w' **outside** time 't'. (d) Each of the items above represents one of the cells of a chi-square contingency table for each word and time. Can all of these be calculated within a single loop or do they need to be done one at a time? Ideally, I would like the output to be what's below, where a,b,c,d are all the items calculated above: print "%s, %s, %s, %s" %(a,b,c,d) In the case of the input file above, the result of trying to find the contingency table for the word 'apple' at time '1' would be `(3,2,1,6)`. I'll explain how each cell is calculated: * '3' documents contain 'apple' within time '1'. * There are '2' documents within time '1' that don't contain 'apple'. * There is '1' document containing 'apple' outside time '1'. * There are 6 documents outside time '1' that don't contain the word 'apple' (1+4+1). Answer: Your 4 numbers for apple/1 add up to 12, more than the total number of observations (11)! There are only 5 documents outside time '1' that don't contain the word 'apple'. You need to partition the observations into 4 disjoint subsets: a: apple and 1 => 3 b: not-apple and 1 => 2 c: apple and not-1 => 1 d: not-apple and not-1 => 5 Here is some code that shows one way of doing it: from collections import defaultdict class Crosstab(object): def __init__(self): self.count = defaultdict(lambda: defaultdict(int)) self.row_tot = defaultdict(int) self.col_tot = defaultdict(int) self.grand_tot = 0 def add(self, r, c, n): self.count[r][c] += n self.row_tot[r] += n self.col_tot[c] += n self.grand_tot += n def load_data(line_iterator, conv_funcs): ct = Crosstab() for line in line_iterator: r, c, n = [func(s) for func, s in zip(conv_funcs, line.split(','))] ct.add(r, c, n) return ct def display_all_2x2_tables(crosstab): for rx in crosstab.row_tot: for cx in crosstab.col_tot: a = crosstab.count[rx][cx] b = crosstab.col_tot[cx] - a c = crosstab.row_tot[rx] - a d = crosstab.grand_tot - a - b - c assert all(x >= 0 for x in (a, b, c, d)) print ",".join(str(x) for x in (rx, cx, a, b, c, d)) if __name__ == "__main__": # inputfile # <word, time, frequency> lines = """\ apple, 1, 3 banana, 1, 2 apple, 2, 1 banana, 2, 4 orange, 3, 1""".splitlines() ct = load_data(lines, (str.strip, int, int)) display_all_2x2_tables(ct) and here is the output: orange,1,0,5,1,5 orange,2,0,5,1,5 orange,3,1,0,0,10 apple,1,3,2,1,5 apple,2,1,4,3,3 apple,3,0,1,4,6 banana,1,2,3,4,2 banana,2,4,1,2,4 banana,3,0,1,6,4
Sum of Digits, properties, hint please Question: This is the problem: > How many integers 0 ≤ n < 10^18 have the property that the sum of the digits > of n equals the sum of digits of 137n? This solution is grossly inefficient. What am I missing? #!/usr/bin/env python #coding: utf-8 import time from timestrings import * start = time.clock() maxpower = 18 count = 0 for i in range(0, 10 ** maxpower - 1): if i % 9 == 0: result1 = list(str(i)) result2 = list(str(137 * i)) sum1 = 0 for j in result1: sum1 += int(j) sum2 = 0 for j in result2: sum2 += int(j) if sum1 == sum2: print (i, sum1) count += 1 finish = time.clock() print ("Project Euler, Project 290") print () print ("Answer:", count) print ("Time:", stringifytime(finish - start)) Answer: You are trying to solve a Project Euler problem by brute force. That may work for the first few problems, but for most problems you need think of a more sophisticated approach. Since it is IMHO not OK to give advice specific to this problem, take a look at the general advice in [this answer](http://stackoverflow.com/questions/1537306/recommended-reading-for- solving-project-euler-problems/1537531#1537531).
Python Threading, loading one thread after another Question: I'm working on a media player and am able to load in a single .wav and play it. As seen in the code below. foo = wx.FileDialog(self, message="Open a .wav file...", defaultDir=os.getcwd(), defaultFile="", style=wx.FD_MULTIPLE) foo.ShowModal() queue = foo.GetPaths() self.playing_thread = threading.Thread(target=self.playFile, args=(queue[0], 'msg')) self.playing_thread.start() But the problem is, when I try to make the above code into a loop for multiple .wav files. Such that while playing_thread.isActive == True, create and .start() the thread. Then if .isActive == False, pop queue[0] and load the next .wav file. Problem is, my UI will lock up and I'll have to terminate the program. Any ideas would be appreciated. Answer: Since is using wx.python, use a Delayedresult, look at wx demos for a complete example. Full minimal example: import wx import wx.lib.delayedresult as inbg import time class Player(wx.Frame): def __init__(self): self.titulo = "Music Player" wx.Frame.__init__(self, None, -1, self.titulo,) self.jobID = 0 self.Vb = wx.BoxSizer(wx.VERTICAL) self.panel = wx.Panel(self,-1) self.playlist = ['one','two'] self.abortEvent = inbg.AbortEvent() self.msg = wx.StaticText(self.panel, -1, "...",pos=(30,-1)) self.msg.SetFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD)) self.action = wx.Button(self.panel, -1,"Play Playlist") self.Bind(wx.EVT_BUTTON, self.StartPlaying,self.action) self.Vb.Add(self.msg, 0, wx.EXPAND|wx.ALL, 3) self.Vb.Add(self.action, 0, wx.EXPAND|wx.ALL, 3) self.panel.SetSizer(self.Vb) self.Show() def StartPlaying(self,evt): self.BgProcess(self.Playme) def Playme(self,jobID, abortEvent): print "in bg" list = self.getPlayList() print list for music in list: self.msg.SetLabel('Playing: %s' % music) stop = 100 while stop > 0: print stop stop -=1 self.msg.SetLabel('Playing: %s [%s ]' % (music,stop)) def _resultConsumer(self, inbg): jobID = inbg.getJobID() try: result = inbg.get() return result except Exception, exc: return False def getPlayList(self): return self.playlist def setPlayList(self,music): self.playlist.appdend(music) def BgProcess(self,executar): self.abortEvent.clear() self.jobID += 1 inbg.startWorker(self._resultConsumer, executar, wargs=(self.jobID,self.abortEvent), jobID=self.jobID) app = wx.App(False) demo = Player() app.MainLoop()
How to call IronPython function from C#/F#? Question: This is kind of follow up questions of <http://stackoverflow.com/questions/2969194/integration-of-c-f-ironpython-and- ironruby> In order to use C/C++ function from Python, SWIG is the easiest solution. The reverse way is also possible with Python C API, for example, if we have a python function as follows def add(x,y): return (x + 10*y) We can come up with the wrapper in C to use this python as follows. double Add(double a, double b) { PyObject *X, *Y, *pValue, *pArgs; double res; pArgs = PyTuple_New(2); X = Py_BuildValue("d", a); Y = Py_BuildValue("d", b); PyTuple_SetItem(pArgs, 0, X); PyTuple_SetItem(pArgs, 1, Y); pValue = PyEval_CallObject(pFunc, pArgs); res = PyFloat_AsDouble(pValue); Py_DECREF(X); Py_DECREF(Y); Py_DECREF(pArgs); return res; } How about the IronPython/C# or even F#? * How to call the C#/F# function from IronPython? Or, is there any SWIG equivalent tool in IronPython/C#? * How to call the IronPython function from C#/F#? I guess I could use "engine.CreateScriptSourceFromString" or similar, but I need to find a way to call IronPython function look like a C#/F# function, not writing the code in a string, but reading from a file. Answer: You say 'now writing the code in a string, but reading from a file', so ok, read the file. Python from F#: let s = File.ReadAllLines("foo.py") let engine = Python.CreateEngine() let scriptSource = engine.CreateScriptSourceFromString(s, SourceCodeKind.Statements) ... F# from Python: import clr clr.AddReferenceToFile("SomeFsLib.dll") I just got these from the links in this question. Have not tried it, but, like, it's straightforward, I think it 'just works'. Dunno what else you are asking for.
Convert a GTK python script to C Question: The following script will take a screenshot on a Gnome desktop. import gtk.gdk w = gtk.gdk.get_default_root_window() sz = w.get_size() pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False, 8, sz[0], sz[1]) pb = pb.get_from_drawable(w, w.get_colormap(), 0, 0, 0, 0, sz[0], sz[1]) if (pb != None): pb.save("screenshot.png", "png") print "Screenshot saved to screenshot.png." else: print "Unable to get the screenshot." Now, I've been trying to convert this to C and use it in one of the apps I am writing but so far i've been unsuccessful. Is there any what to do this in C (on Linux)? Thanks! Jess. Answer: I tested this and it does work, but there might be a simpler way to go from GdkPixbuf to a png this was just the first one I found. (There's no `gdk_pixbuf_save()`) #include <unistd.h> #include <stdio.h> #include <gdk/gdk.h> #include <cairo.h> int main(int argc, char **argv) { gdk_init(&argc, &argv); GdkWindow *w = gdk_get_default_root_window(); gint width, height; gdk_drawable_get_size(GDK_DRAWABLE(w), &width, &height); GdkPixbuf *pb = gdk_pixbuf_get_from_drawable(NULL, GDK_DRAWABLE(w), NULL, 0,0,0,0,width,height); if(pb != NULL) { cairo_surface_t *surf = cairo_image_surface_create(CAIRO_FORMAT_RGB24, width, height); cairo_t *cr = cairo_create(surf); gdk_cairo_set_source_pixbuf(cr, pb, 0, 0); cairo_paint(cr); cairo_surface_write_to_png(surf, "screenshot.png"); g_print("Screenshot saved to screenshot.png.\n"); } else { g_print("Unable to get the screenshot.\n"); } return 0; } you'd compile like this: (assuming you save it as screenshot.c) gcc -std=gnu99 `pkg-config --libs --cflags gdk-2.0` screenshot.c -o screenshot Edit: the stuff to save the pixbuf could also look like: (note I didn't try this out, but it's only one line...) Thanks to kaizer.se for pointing out my fail at doc reading :P gdk_pixbuf_save(pb, "screenshot.png", "png", NULL, NULL);
A simple Python extension in C Question: I am trying to create a simple python extension module. I compiled the following code into a transit.so dynamic module #include <python2.6/Python.h> static PyObject* _print(PyObject* self, PyObject* args) { return Py_BuildValue("i", 10); } static PyMethodDef TransitMethods[] = { {"print", _print, METH_VARARGS, ""}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC inittransit(void) { Py_InitModule("transit", TransitMethods); } However, trying to call this from python import transit transit.print() I obtain an error message File "test.py", line 2 transit.print() ^ SyntaxError: invalid syntax What's wrong with my code? Answer: I'm guessing that it has to do with using a keyword as a function name. I tried defining a function `print()` in a module just now for testing and got the same sort of error. Try changing the name of this function slightly and see if it fixes the problem.
How can I paste some string to the active window in Python? Question: > **Possible Duplicate:** > [How do I copy a string to the clipboard on Windows using > Python?](http://stackoverflow.com/questions/579687/how-do-i-copy-a-string- > to-the-clipboard-on-windows-using-python) Can someone make me an example or explain to me how can I paste something to the active window with Python? Answer: It is easiest if you **use the[SendKeys](http://pypi.python.org/pypi/SendKeys) package**. You can find a Windows installer for various Python versions [here](http://www.rutherfurd.net/python/sendkeys/#dowloads). The simplest use case, sending plain text, is very simple: import SendKeys SendKeys.SendKeys("Hello world") You can do all sorts of nifty things **using key-codes to represent for unprintable characters** : import SendKeys SendKeys.SendKeys(""" {LWIN} {PAUSE .25} r Notepad.exe{ENTER} {PAUSE 1} Hello{SPACE}World! {PAUSE 1} %{F4} n """) **Read[the documentation](http://www.rutherfurd.net/python/sendkeys/) for full details.** If for whatever reason you don't want to introduce a dependency on a non- standard library package, you can [do the same thing](http://code.activestate.com/recipes/65107-sendkeys-from-the-windows- script-host-wsh-com/) using COM: import win32api import win32com.client shell = win32com.client.Dispatch("WScript.Shell") shell.Run("calc") win32api.Sleep(100) shell.AppActivate("Calculator") win32api.Sleep(100) shell.SendKeys("1{+}") win32api.Sleep(500) shell.SendKeys("2") win32api.Sleep(500) shell.SendKeys("~") # ~ is the same as {ENTER} win32api.Sleep(500) shell.SendKeys("*3") win32api.Sleep(500) shell.SendKeys("~") win32api.Sleep(2500)
defining precision in python(2.6) division Question: from __future__ import division To perform a division in which I need some percision. However, it gives a long number, like: 1.876543820098765 I only need the the first two numbers after "." => 1.87 How can I do that? Answer: "%0.2f" % yournumber As you said you don't want a rounded number, you might want to try def twoDigits(x): return int(100*x)/100.0
Terminate a python script from another python script Question: I've got a long running python script that I want to be able to end from another python script. Ideally what I'm looking for is some way of setting a process ID to the first script and being able to see if it is running or not via that ID from the second. Additionally, I'd like to be able to terminate that long running process. Any cool shortcuts exist to make this happen? Also, I'm working in a Windows environment. I just recently found an alternative answer here: <http://stackoverflow.com/questions/788411/check-to-see-if-python-script-is- running> Answer: You could get your own PID (Process Identifier) through import os os.getpid() and to kill a process in Unix import os, signal os.kill(5383, signal.SIGKILL) to kill in Windows use import subprocess as s def killProcess(pid): s.Popen('taskkill /F /PID {0}'.format(pid), shell=True) You can send the PID to the other programm or you could search in the process- list to find the name of the other script and kill it with the above script. I hope that helps you.
MS SQL + Python (IronPython) timing out Question: I'm querying MS SQL using python using the source code from <http://www.ironpython.info/index.php/Accessing_SQL_Server>: import clr clr.AddReference('System.Data') from System.Data import * TheConnection = SqlClient.SqlConnection ("server=yourserver;database=News;uid=sa;password=password;timeout=0") TheConnection.Open() MyAction = SqlClient.SqlCommand("Select Headline from News", TheConnection) MyReader = MyAction.ExecuteReader() while MyReader.Read(): print MyReader[0] MyReader.Close() TheConnection.Close() I just added `timeout=0`, but still I got : EnvironmentError: System.Data.SqlClient.SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. I tried it with `timeout=1000000`, but still got the same error. If I run the same SQL in the same machine using the MSSQL Client, it's totally fine. Do you know how to avoid this timeout exception? Answer: Try increasing the CommandTimeout property on the SqlCommand as described here: <https://msdn.microsoft.com/en- us/library/system.data.sqlclient.sqlcommand.commandtimeout(v=vs.110).aspx> The timeout value in the connection string only controls the timeout for the initial connection to the database. That will not help if your SQL query takes a long time to execute so you need to use CommandTimeout instead.
How can I get href links from HTML using Python? Question: import urllib2 website = "WEBSITE" openwebsite = urllib2.urlopen(website) html = getwebsite.read() print html So far so good. But I want only href links from the plain text HTML. How can I solve this problem? Answer: Try with [Beautifulsoup](http://www.crummy.com/software/BeautifulSoup/): from BeautifulSoup import BeautifulSoup import urllib2 import re html_page = urllib2.urlopen("http://www.yourwebsite.com") soup = BeautifulSoup(html_page) for link in soup.findAll('a'): print link.get('href') In case you just want links starting with `http://`, you should use: soup.findAll('a', attrs={'href': re.compile("^http://")})
akntextutils installation on mobile Question: I tried to use akntextutils which ran successfully on emualator but trying to run this on mobile device is a problem... We using python 1.4.5 with a 2nd edition FP2 can u help us in this... Answer: Traceback(most recent call last): File "", line 1, in? File "c:\resource\site.py", line 109,in platsec_ import return imp.load_dynamic(name,name+'.pyd') Symbian error:[errno-20] KErrCorrupt this was the error when we placed the file in e:\sys\bin. at other places we got no module named akntextutils kind of error. ya, mobile is s60 ed2 fp2. nokia e63
How do you create a python package with a built in "test/main.py" main function? Question: Desired directory tree: Fibo |-- src | `-- Fibo.py `-- test `-- main.py What I want is to call `python main.py` after cd'ing into test and executing main.py will run all the unit tests for this package. Currently if I do: import Fibo def main(): Fibo.fib(100) if __name__ == "__main__": main() I get an error: "`ImportError: No module named Fibo`". But if I do: import sys def main(): sys.path.append("/home/tsmith/svn/usefuldsp/trunk/Labs/Fibo/src") import Fibo Fibo.fib(100) if __name__ == "__main__": main() This seems to fix my error. And I could move forward... but this isn't a python package. This is more of a "collection of files" approach. **How would you setup your testing to work in this directory structure?** Answer: If I want to import a module that lives at a fixed, relative location to the file I'm evaluating, I often do something like this: try: import Fibo except ImportError: import sys from os.path import join, abspath, dirname parentpath = abspath(join(dirname(__file__), '..')) srcpath = join(parentpath, 'src') sys.path.append(srcpath) import Fibo def main(): Fibo.fib(100) if __name__ == "__main__": main() If you want to be a good namespace-citizen, you could `del` the no longer needed symbols at the end of the `except` block.
Python not opening Japanese filenames Question: I've been working on a python script to open up a file with a unicode name (Japanese mostly) and save to a randomly generated (Non-unicode) filename in Windows Vista 64-bit, and I'm having issues... It just doesn't work, it works fine with non-unicode filenames (Even if it has unicode content), but the second you try to pass a unicode filename in - it doesn't work. Here's the code: try: import sys, os inpath = sys.argv[1] outpath = sys.argv[2] filein = open(inpath, "rb") contents = filein.read() fileSave = open(outpath, "wb") fileSave.write(contents) fileSave.close() testfile = open(outpath + '.test', 'wb') testfile.write(inpath) testfile.close() except: errlog = open('G:\\log.txt', 'w') errlog.write(str(sys.exc_info())) errlog.close() And the error: (<type 'exceptions.IOError'>, IOError(2, 'No such file or directory'), <traceback object at 0x01092A30>) Answer: You have to convert your `inpath` to unicode, like this: inpath = sys.argv[1] inpath = inpath.decode("UTF-8") filein = open(inpath, "rb") I'm guessing you are using Python 2.6, because in Python 3, all strings are unicode by default, so this problem wouldn't happen.
GUI tools and APIs for small/medium hierarchical data structures Question: I'm trying to find a tool and library to edit, write and read data in a hierarchical structure, similar to an LDAP tree, a Windows registry or a Berkeley DB structure. The keys should represent some hierarchy, and the values should have a relatively flexible format (typing is optional, but could be useful). Here is an example: Items/item_1/shape = "rectangle" Items/item_1/top = 10 Items/item_1/left = 10 Items/item_1/width = 30 Items/item_1/height = 40 Items/item_2/shape = "square" Items/item_2/top = 10 Items/item_2/left = 10 Items/item_2/width = 30 Items/item_3/shape = "circle" Items/item_3/centre_x = 40 Items/item_3/centre_y = 50 Items/item_3/radius = 20 Items/item_3/colour = blue The use-case would be: 1. Edit the data store via a convenient GUI. This could look like Windows Regedit or [Apache Directory Studio (LDAP Browser)](http://directory.apache.org/studio/screenshots.html). 2. Save that data into some store (e.g. a file). 3. Load this store from another application, which would be able to query it from an API. The library for this would ideally be callable from Python. I'd like these operations to be reasonably fast for reading, but not have it all loaded in memory in advance. The data store would be updated into the application more or less manually, much less often than the data is read. Being able to write to that data from the API would be a plus, but it's not a strict requirement. Queries would be good. For example (in pseudo query), "List Items/* where top == 10" would return: * Items/item_1 * Items/item_2 Ease of edition (via a good GUI) is one of the most important features. I've considered a few options: 1. _An LDAP server_ answers most requirements (especially with the help of Apache Directory Studio). However, deploying an LDAP server just for that is too heavy. However good Apache Directory Studio is, the user still needs a reasonable understanding of LDAP (more than just explaining the tree hierachy). I'd also like some flexibility in the creation of schemas (or no schemas at all) rather than having to rely on an administrator to do this. 2. _Windows Regedit_. I'm not sure if it's possible, but I guess it's conceivable to have a registry-like file that has nothing to do with the actual windows registry, editable with custom content via Regedit. I would however like this GUI application to be available on non-Windows platforms and I'm not even sure there's a Python API to read a Windows registry file. 3. _RDF_. That could work. I'm sure there are fairly good Python libraries for semantic web. However, I don't need any reasoning capabilities. I'd rather have something fast and that doesn't use much memory. I'm not sure there are any good GUI tools to view and edit the tree (since it's geared towards webs and graphs). There are certainly ways to build this sort of data structures on top of existing systems like SQLite (for example), and this would be fine but I'm not sure whether there's a good GUI that would come with it. I'd appreciate comments and suggestions, thank you. Answer: Forgive my densitosity, but if your hierarchy is anything but the roughest kind of example, there must be hugely compelling, overpowering reasons for your choosing that over, say, JSON or even (gulp!) XML: <items> <item> <number>1</number> <shape>rectangle</shape> <top>10</top> <left>10</left> <width>30</width> <height>40</height> </item> <item> <number>2</number> <shape>triangle</shape> <top>20</top> <left>50</left> <width>30></width> <height>40</height> </item> </items> For XML, you know there are tons of editors that answer your needs. Same with JSON. And I think there are also XML-> MySQL -> XML libraries. Why not take that kind of approach?
issue while matching special char '\' in regular expression using '\\' Question: I have very simple python script to match some special characters like -,+,-,. But Im not getting expected result while using regex \ to match a single '\' char. import re pat = r'[-+*\\]' text = 'fdkjdfk\sdsdd' if re.search(pat,text): print re.search(pat,text).group() else: print "not found" On running above code , it prints 'not found' It seems I am doing some mistake here , any help appreciated !!! Answer: `\` is an escape character. Try escaping it: text = 'fdkjdfk\\sdsdd'
Really simple way to deal with XML in Python? Question: Musing over a [recently asked question](http://stackoverflow.com/questions/3063319/), I started to wonder if there is a _really simple_ way to deal with XML documents in Python. A pythonic way, if you will. Perhaps I can explain best if i give example: let's say the following - which i think is a good example of how XML is (mis)used in web services - is the response i get from http request to <http://www.google.com/ig/api?weather=94043> <xml_api_reply version="1"> <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" > <forecast_information> <city data="Mountain View, CA"/> <postal_code data="94043"/> <latitude_e6 data=""/> <longitude_e6 data=""/> <forecast_date data="2010-06-23"/> <current_date_time data="2010-06-24 00:02:54 +0000"/> <unit_system data="US"/> </forecast_information> <current_conditions> <condition data="Sunny"/> <temp_f data="68"/> <temp_c data="20"/> <humidity data="Humidity: 61%"/> <icon data="/ig/images/weather/sunny.gif"/> <wind_condition data="Wind: NW at 19 mph"/> </current_conditions> ... <forecast_conditions> <day_of_week data="Sat"/> <low data="59"/> <high data="75"/> <icon data="/ig/images/weather/partly_cloudy.gif"/> <condition data="Partly Cloudy"/> </forecast_conditions> </weather> </xml_api_reply> After loading/parsing such document, i would like to be able to access the information as simple as say >>> xml['xml_api_reply']['weather']['forecast_information']['city'].data 'Mountain View, CA' or >>> xml.xml_api_reply.weather.current_conditions.temp_f['data'] '68' From what I saw so far, seems that `ElementTree` is the closest to what I dream of. But it's not there, there is still some fumbling to do when consuming XML. OTOH, what I am thinking is not that complicated - probably just thin veneer on top of a parser - and yet it can decrease annoyance of dealing with XML. Is there such a magic? (And if not - why?) PS. Note I have tried `BeautifulSoup` already and while I like its approach, it has real issues with empty `<element/>`s - see below in comments for examples. Answer: lxml has been mentioned. You might also check out [lxml.objectify](http://codespeak.net/lxml/objectify.html) for some really simple manipulation. >>> from lxml import objectify >>> tree = objectify.fromstring(your_xml) >>> tree.weather.attrib["module_id"] '0' >>> tree.weather.forecast_information.city.attrib["data"] 'Mountain View, CA' >>> tree.weather.forecast_information.postal_code.attrib["data"] '94043'
In-place substitution of PyGTK widgets Question: The code below creates a column of three labels. I would like to take the middle label, and replace it with another widget using the text from the label _after the initial creation of the UI_. My actual use case is to take a GTKBuilder populated UI, and replace any particular named label with a [dynamically wrapped label](http://stackoverflow.com/questions/1893748/pygtk-dynamic-label- wrapping) at run time. (I used a button here because it's simple but distinct.) Then I can still use Glade to set up the UI, including the labels, and not pepper my Python code with errant labels and strings if I later want to make a label wrap. The code as it stands does not work - the new button gets added to the end of the column, and I want it to remain in the middle, where `label2` was to begin with. What can I do, preferably in `wrap_in_button`, to make sure it ends up in the correct place? I'd rather keep it general, since the parent may be a `Box` or a `Table` or any general `Container`. import pygtk import gtk def destroy(widget, data=None): gtk.main_quit() def wrap_in_button(label): text = label.get_text() button = gtk.Button(text) parent = label.get_parent() if parent: parent.remove(label) parent.add(button) def Main(): # Pretend that this chunk is actually replaced by GTKBuilder work # From here... window = gtk.Window() window.connect('destroy', destroy) box = gtk.VBox() window.add(box) label1 = gtk.Label("Label 1") label2 = gtk.Label("Label 2") label3 = gtk.Label("Label 3") box.pack_start(label1) box.pack_start(label2) box.pack_start(label3) # ...up to here # Comment this to see the original layout wrap_in_button(label2) window.show_all() gtk.main() if __name__ == "__main__": Main() Answer: I found the solution in the code of the _gazpacho_ interface designer. You can use this function: def replace_widget(current, new): """ Replace one widget with another. 'current' has to be inside a container (e.g. gtk.VBox). """ container = current.parent assert container # is "current" inside a container widget? # stolen from gazpacho code (widgets/base/base.py): props = {} for pspec in gtk.container_class_list_child_properties(container): props[pspec.name] = container.child_get_property(current, pspec.name) gtk.Container.remove(container, current) container.add(new) for name, value in props.items(): container.child_set_property(new, name, value) The key seems to be to transfer the child properties from the old widget to the new one after running `gtk.Container.add()`. Applied to your example, this would be: import pygtk import gtk def replace_widget(current, new): """ Replace one widget with another. 'current' has to be inside a container (e.g. gtk.VBox). """ container = current.parent assert container # is "current" inside a container widget? # stolen from gazpacho code (widgets/base/base.py): props = {} for pspec in gtk.container_class_list_child_properties(container): props[pspec.name] = container.child_get_property(current, pspec.name) gtk.Container.remove(container, current) container.add(new) for name, value in props.items(): container.child_set_property(new, name, value) def destroy(widget, data=None): gtk.main_quit() def wrap_in_button(label): text = label.get_text() button = gtk.Button(text) replace_widget(label, button) def Main(): # Pretend that this chunk is actually replaced by GTKBuilder work # From here... window = gtk.Window() window.connect('destroy', destroy) box = gtk.VBox() window.add(box) label1 = gtk.Label("Label 1") label2 = gtk.Label("Label 2") label3 = gtk.Label("Label 3") box.pack_start(label1) box.pack_start(label2) box.pack_start(label3) # ...up to here wrap_in_button(label2) window.show_all() gtk.main() if __name__ == "__main__": Main() This works for me using Python 2.6.6 and PyGTK 2.17. As a solution to your original problem, I used `label_set_autowrap()` [from here](http://stackoverflow.com/questions/1893748/pygtk-dynamic-label- wrapping/2016849#2016849) and it worked most of the time. However, it's not a perfect solution as I wasn't able to correctly right-align auto-wrapped text.
Making Python sockets visible for outside world? Question: i already have a post which is quite similiar, but i am getting more and more frustrated because it seems nothing is wrong with my network setup. Other software can be seen from the outside (netcat listen servers etc.) but not my scripts.. How can this be?? Note: It works on LAN but not over the internet. Server: import socket host = '' port = 80001 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(1) print 'Listening..' conn, addr = s.accept() print 'is up and running.' print addr, 'connected.' s.close() print 'shut down.' Client: import socket host = '80.xxx.xxx.xxx' port = 80001 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host,port)) s.close() Somebody please help me. Any help is greatly appreciated. Jake Answer: **Edited again to add:** I think you may be missing some basics on socket communication. In order for sockets to work, you need to ensure that the sockets on both your client and server will meet. With your latest revision, your server is now bound to port 63001, but on the local loopback adapter: 127.0.0.1 Computers have multiple network adapters, at least 2: one is the local loopback, which allows you to make network connections to the same machine in a fast, performant manner (for testing, ipc etc), and a network adapter that lets you connect to an actual network. Many computers may have many more adapters (virtual adapters for vlans, wireless vs wired adapters etc), but they will have at least 2. So in your server application, you need to instruct it to bind the socket to the proper network adapter. host = '' port = 63001 bind(host,port) What this does in python is binds the socket to the loopback adapter (or 127.0.0.1/localhost). In your client application you have: host = '80.xxx.xxx.xxx' port = 63001 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host,port)) Now what your client attempts to do is to connect to a socket to port 63001 on 80.xxx.xxx.xxx (which is your wireless internet adapter). Since your server is listening on your loopback adapter, and your client is trying to connect on your wireless adapter, it's failing, because the two ends don't meet. So you have two solutions here: 1. Change the client to connect to localhost by `host = 127.0.0.1` 2. Change the server to bind to your internet adapter by changing `host = 80.xxx.xxx.xxx` Now the first solution, using localhost, will only work when your server and client are on the same machine. Localhost always points back to itself (hence loopback), no matter what machine you try. So if/when you decide to take your client/server to the internet, you will have to bind to a network adapter that is on the internet. Edited to add:** Okay with your latest revision it still won't work because `65535` is the largest post available. **Answer below was to the original revision of the question.** In your code posted, you're listening (bound) on port `63001`, but your client application is trying to connect to port `80`. Thats why your client can't talk to your server. Your client needs to connect using port `63001` not port `80`. Also, unless you're running an HTTP server (or your python server will handle HTTP requests), you really shouldn't bind to port `80`. In your client code change: import socket host = '80.xxx.xxx.xxx' port = 63001 And in your Server Code: import socket host = '' port = 63001 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((socket.gethostbyname(socket.gethostname()), port ))
datetime issue with xlrd & xlwt python libs Question: I'm trying to write some dates from one excel spreadsheet to another. Currently, I'm getting a representation in excel that isn't quite what I want such as this: "40299.2501157407" I can get the date to print out fine to the console, however it doesn't seem to work right writing to the excel spreadsheet -- the data must be a date type in excel, I can't have a text version of it. Here's the line that reads the date in: date_ccr = xldate_as_tuple(sheet_ccr.cell(row_ccr_index, 9).value, book_ccr.datemode) Here's the line that writes the date out: row.set_cell_date(11, datetime(*date_ccr)) There isn't anything being done to date_ccr in between those two lines other than a few comparisons. Any ideas? Answer: You can write the floating point number directly to the spreadsheet and set the number format of the cell. Set the format using the `num_format_str` of an `XFStyle` object when you write the value. <https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/doc/xlwt.html#xlwt.Worksheet.write- method> The following example writes the date 01-05-2010. (Also includes time of 06:00:10, but this is hidden by the format chosen in this example.) import xlwt # d can also be a datetime object d = 40299.2501157407 wb = xlwt.Workbook() sheet = wb.add_sheet('new') style = xlwt.XFStyle() style.num_format_str = 'DD-MM-YYYY' sheet.write(5, 5, d, style) wb.save('test_new.xls') There are examples of number formats (num_formats.py) in the examples folder of the xlwt source code. On my Windows machine: C:\Python26\Lib\site- packages\xlwt\examples You can read about how Excel stores dates (third section on this page): <https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html>
How to create a parser which tokenizes a list of words taken from a file? Question: I am trying to do a sintax text corrector for my compilers' class. The idea is: I have some rules, which are inherent to the language (in my case, Portuguese), like "A valid phrase is SUBJECT VERB ADJECTIVE", as in "Ruby is great". Ok, so first I have to tokenize the input "Ruby is great". So I have a text file "verbs", with a lot of verbs, one by line. Then I have one text "adjectives", one "pronouns", etc. I am trying to use Ragel to create a parser, but I don't know how I could do something like: %%{ machine test; subject = <open-the-subjects-file-and-accept-each-one-of-them>; verb = <open-the-verbs-file-and-accept-each-one-of-them>; adjective = <open-the-adjective-file-and-accept-each-one-of-them>; main = subject verb adjective @ { print "Valid phrase!" } ; }%% I looked at ANTLR, Lex/Yacc, Ragel, etc. But couldn't find one that seemed to solve this problem. The only way to do this that I could think of was to preprocess Ragel's input file, so that my program reads the file and writes its contents at the right place. But I don't like this solution either. Does anyone knows how I could do this? There's no problem if it isn't with Ragel, I just want to solve this problem. I would like to use Ruby or Python, but that's not really necessary either. Thanks. Answer: If you want to read the files at compile time .. make them be of the format: subject = \ ruby|\ python|\ c++ then use ragel's 'include' or 'import' statement (I forget which .. must check the manual) to import it. * * * If you want to check the list of subjects at run time, maybe just make ragel read 3 words, then have an action associated with each word. The action can read the file and lookup if the word is good or not at runtime. The action reads the text file and compares the word's contents. %%{ machine test action startWord { lastWordStart = p; } action checkSubject { word = input[lastWordStart:p+1] for possible in open('subjects.txt'): if possible == word: fgoto verb # If we get here do whatever ragel does to go to an error or just raise a python exception raise Exception("Invalid subject '%s'" % word) } action checkVerb { .. exercise for reader .. ;) } action checkAdjective { .. put adjective checking code here .. } subject = ws*.(alnum*)>startWord%checkSubject verb := : ws*.(alnum*)>startWord%checkVerb adjective := ws*.)alnum*)>startWord%checkAdjective main := subject; }%%
howoto fix working directory is always home? (python) Question: This is my first question. My python script opens and reads from a present text file using the following simple funct: open("config.ini", "r") As this is a relative path it is supposed to work because config.ini is placed in the same directory like the script is when it is launched, that should be the current working dir. In fact this works perfectly on all of my 3 linux boxes, but I have one user who demands support because he gets an error while opening config.ini. The error raises because os.path.exists("config.ini") returns false even if the file is there! Trying to fix this problem we found out that the only way to make it work is to place config.ini in his home directory despite the supposed working directory is another. Also, if my script tries to create a file in the present working directory, the file is always created in his home dir instead, and so I think that for some reason his working dir is always home! How can I troubleshoot this problem? Maybe I could introduce absolute paths, but I am afraid that os.getcwd() would return the homedir instead of the correct one. Should I maybe suggest this user to fix his machine in some way? Sorry for this long question but english is not my first language and I am a beginner in coding, so have some difficulties to explain. Thank you very much in advance! =) Answer: Could it be that the user is executing your script _from_ his home directory? I.e. suppose the script is in: /home/user/test/foo/foo.py But the user calls it thus: /home/user> python test/foo/foo.py In this case, the "current directory" the script sees is `/home/user`. What you can do is find out the directory the script itself resides in by calling this function: import os def script_dir(): return os.path.dirname(os.path.realpath(__file__)) It will always return the directory in which the script lives, not the current directory which may be different. You can then store your configuration file there safely.
Why can't I in python call HDIO_GETGEO? Question: #!/usr/bin/env python # -*- coding: utf-8 -*- ########## THIS NOW WORKS! ########## UNSUITABLE_ENVIRONMENT_ERROR = \ "This program requires at least Python 2.6 and Linux" import sys import struct import os from array import array # +++ Check environment try: import platform # Introduced in Python 2.3 except ImportError: print >>sys.stderr, UNSUITABLE_ENVIRONMENT_ERROR if platform.system() != "Linux": print >>sys.stderr, UNSUITABLE_ENVIRONMENT_ERROR if platform.python_version_tuple()[:2] < (2, 6): print >>sys.stderr, UNSUITABLE_ENVIRONMENT_ERROR # --- Check environment HDIO_GETGEO = 0x301 # Linux import fcntl def get_disk_geometry(fd): geometry = array('c',"XXXXXXXX") fcntl.ioctl(fd, HDIO_GETGEO, geometry, True) heads, sectors, cylinders, start = \ struct.unpack("BBHL",geometry.tostring()) return { 'heads' : heads, 'cylinders': cylinders, 'sectors': sectors, "start": start } from pprint import pprint fd=os.open("/dev/sdb", os.O_RDWR) pprint(get_disk_geometry(fd)) Answer: Nobody seems to be able to tell me why you can't do this, but you can do it with ctypes so it doesn't really matter. #!/usr/bin/env python from ctypes import * import os from pprint import pprint libc = CDLL("libc.so.6") HDIO_GETGEO = 0x301 # Linux class HDGeometry(Structure): _fields_ = (("heads", c_ubyte), ("sectors", c_ubyte), ("cylinders", c_ushort), ("start", c_ulong)) def __repr__(self): return """Heads: %s, Sectors %s, Cylinders %s, Start %s""" % ( self.heads, self.sectors, self.cylinders, self.start) def get_disk_geometry(fd): """ Returns the heads, sectors, cylinders and start of disk as rerpoted by BIOS. These us usually bogus, but we still need them""" buffer = create_string_buffer(sizeof(HDGeometry)) g = cast(buffer, POINTER(HDGeometry)) result = libc.ioctl(fd, HDIO_GETGEO, byref(buffer)) assert result == 0 return g.contents if __name__ == "__main__": fd = os.open("/dev/sdb", os.O_RDWR) print repr(get_disk_geometry(fd))
how to integrate spiders and scrapy-ctl.py Question: I am new to python and scrapy and hence am getting some basic doubts(please spare my ignorance about some fundamentals,which i m willing to learn :D). Right now I am writing some spiders and implementing them using scrapy-ctl.py from the command line by typing: C:\Python26\dmoz>python scrapy-ctl.py crawl spider But I do not want two separate python codes and a command line to implement this.I want to somehow define a spider and make it crawl urls by writing and running a single python code.I could notice that in the file scrapy-ctl.py, 'execute' of type _function_ is imported,but i am clueless as to how this function can be defined in the code containing spider.Could someone explain me how to do this, if it is possible because it greatly reduces the work. Thanks in advance!! Answer: > But I do not want two separate python codes and a command line to implement > this. I want to somehow define a spider and make it crawl urls by writing > and running a single python code. I'm not sure the effort pays out, if you just want to scrape something. You have at least two options: * Dig into `scrapy/cmdline.py`. You'll see that this is a kind of dispatch script, finally handing over the work to the `run` method for the specified command, here `crawl` (in `scrapy/commands/crawl.py`). Look at line 54, I think `scrapymanager.start()` will begin your actual command, after some setup. * A little hacky method: use pythons [`subprocess`](http://docs.python.org/library/subprocess.html) module to have one your project and execution in one file (or project).
Python Google App Engine: Call specific method from yaml file? Question: I am new to database programming with Google App Engine and am programming in Python. I was wondering if I am allowed to have one Python file with several request handler classes, each of which has get and post methods. I know that the yaml file allows me to specify which scripts are run with specific urls, like the example below: handlers: - url: /.* script: helloworld.py How would I tell it to run a specific method that is in one of the classes in the .py file? Is that even possible/allowed? Do I need to separate the different request handler classes into different python files? My understanding of databases is rather shallow at the moment, so I could be making no sense. Thanks. Answer: > I was wondering if I am allowed to have one Python file with several request > handler classes, each of which has get and post methods. Sure! That `app.yaml` just transfers control to `helloworld.py`, which will run the `main` function defined in that file -- and that function typically sets up a WSGI app which dispatches appropriately, depending on the URL, to the right handler class. For example, look at the sample code [here](http://code.google.com/appengine/docs/python/gettingstarted/handlingforms.html), very early on in the tutorial: application = webapp.WSGIApplication( [('/', MainPage), ('/sign', Guestbook)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main() I'm not copying the `import` statements and class definitions, because they don't matter: this is an example of how a single `.py` file dispatches to various handler classes (two in this case). This doesn't mean the yaml file lets you call any method whatsoever, of course: rather, it hands control to a `.py` file, whose `main` is responsible for all that follows (and e.g. with the `webapp` mini-framework that comes with App Engine, it will always be `get` or `post` method [[or `put`, `delete`, ..., etc, if you also support those -- few do unless they're being especially RESTful;-)]] being called depending on the exact HTTP method and URL in the incoming request.
Shutting down gracefully from ThreadingTCPServer Question: I've created a simple test app (Python 2.6.1) that runs a ThreadingTCPServer, based on the example [here](http://danieldandrada.blogspot.com/2007/09/python- socketserverthreadingtcpserver.html). If the client sends a command "bye" I want to shut down the server and exit cleanly from the application. The exit part works OK, but when I try to re-run the app, I get: socket.error: [Errno 48] Address already in use I tried the solution given [here](http://stackoverflow.com/questions/2274320/socketserver- threadingtcpserver-cannot-bind-to-address-after-program-restart) for setting the socket options but that didn't seem to help. I've tried various ways to close the server down, but always get the same error. Any idea what I'm doing wrong? import SocketServer import socket import sys import threading import time class RequestHandler(SocketServer.BaseRequestHandler): def setup(self): print("Connection received from %s" % str(self.client_address)) self.request.send("Welcome!\n") def handle(self): while 1: data = self.request.recv(1024) if (data.strip() == 'bye'): print("Leaving server.") self.finish() self.server.shutdown() # None of these things seem to work either #time.sleep(2) #del self.server.socket #self.server.socket.shutdown(socket.SHUT_WR) #self.server.socket.close() #self.server.server_close() break def finish(self): self.request.send("Goodbye! Please come back soon.") if __name__ == "__main__": server = SocketServer.ThreadingTCPServer(("localhost", 9999), RequestHandler) # This doesn't seem to help. #server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) #server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.serve_forever() print("Exiting program.") Answer: If you have not already found an answer, I believe this may assist... [How to close a socket left open by a killed program?](http://stackoverflow.com/questions/5875177/how-to-close-a-socket- left-open-by-a-killed-program/5875178#5875178) However, this is the same solution offered by Alex, so perhaps this is just an opportunity to close an old question.
Converting from utf-16 to utf-8 in Python 3 Question: I'm programming in Python 3 and I'm having a small problem which I can't find any reference to it on the net. As far as I understand the default string in is utf-16, but I must work with utf-8, I can't find the command that will convert from the default one to utf-8. I'd appreciate your help very much. Answer: In Python 3 there are two different datatypes important when you are working with string manipulation. First there is the string class, an object that represents unicode code points. Important to get is that this string is not some bytes, but really a sequence of characters. Secondly, there is the bytes class, which is just a sequence of bytes, often representing an string stored in an encoding (like utf-8 or iso-8859-15). What does this mean for you? As far as I understand you want to read and write utf-8 files. Let's make a program that replaces all 'ć' with 'ç' characters def main(): # Let's first open an output file. See how we give an encoding to let python know, that when we print something to the file, it should be encoded as utf-8 with open('output_file', 'w', encoding='utf-8') as out_file: # read every line. We give open() the encoding so it will return a Unicode string. for line in open('input_file', encoding='utf-8'): #Replace the characters we want. When you define a string in python it also is automatically a unicode string. No worries about encoding there. Because we opened the file with the utf-8 encoding, the print statement will encode the whole string to utf-8. print(line.replace('ć', 'ç'), out_file) So when should you use bytes? Not often. An example I could think of would be when you read something from a socket. If you have this in an bytes object, you could make it a unicode string by doing bytes.decode('encoding') and visa versa with str.encode('encoding'). But as said, probably you won't need it. Still, because it is interesting, here the hard way, where you encode everything yourself: def main(): # Open the file in binary mode. So we are going to write bytes to it instead of strings with open('output_file', 'wb') as out_file: # read every line. Again, we open it binary, so we get bytes for line_bytes in open('input_file', 'rb'): #Convert the bytes to a string line_string = bytes.decode('utf-8') #Replace the characters we want. line_string = line_string.replace('ć', 'ç') #Make a bytes to print out_bytes = line_string.encode('utf-8') #Print the bytes print(out_bytes, out_file) Good reading about this topic (string encodings) is <http://www.joelonsoftware.com/articles/Unicode.html>. Really recommended read! Source: <http://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data- instead-of-unicode-vs-8-bit> (P.S. As you see, I didn't mention utf-16 in this post. I actually don't know whether python uses this as internal decoding or not, but it is totally irrelevant. At the moment you are working with a string, you work with characters (code points), not bytes.
associative list python Question: i am parsing some html form with Beautiful soup. Basically i´ve around 60 input fields mostly radio buttons and checkboxes. So far this works with the following code: from BeautifulSoup import BeautifulSoup x = open('myfile.html','r').read() out = open('outfile.csv','w') soup = BeautifulSoup(x) values = soup.findAll('input',checked="checked") # echoes some output like ('name',1) and ('value',4) for cell in values: # the following line is my problem! statement = cell.attrs[0][1] + ';' + cell.attrs[1][1] + ';\r' out.write(statement) out.close() x.close() As indicating in the code my problem ist where the attributes are selected, because the HTML template is ugly, mixing up the sequence of arguments that belong to a input field. I am interested in name="somenumber" value="someothernumber" . Unfortunately my attrs[1] approach does not work, since name and value do not occur in the same sequence in my html. Is there any way to access the resulting BeautifulSoup list associatively? Thx in advance for any suggestions! Answer: I'm fairly sure you can use the attribute name like a key for a hash: print cell['name']
How to get Field names from a SQL database into a list in python Question: Here is a the code I have so far: from ConfigParser import * import MySQLdb configuration = ConfigParser() configuration.read('someconfigfile.conf') db = MySQLdb.connect( host = configuration.get('DATABASE', 'MYSQL_HOST'), user = configuration.get('DATABASE', 'MYSQL_USER'), passwd = configuration.get('DATABASE', 'MYSQL_PASS'), db = configuration.get('DATABASE', 'MYSQL_DB'), port = configuration.getint('DATABASE', 'MYSQL_PORT'), ssl = { 'ca': configuration.get('SSL_SETTINGS', 'SSL_CA'), 'cert': configuration.get('SSL_SETTINGS', 'SSL_CERT'), 'key': configuration.get('SSL_SETTINGS', 'SSL_KEY') }, ) cursor = db.cursor() sql = "SELECT column_name FROM information_schema.columns WHERE table_name='met';" cursor.execute(sql) list = cursor.fetchall() print list this is what prints: (('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('pk_wind_spd2',), ('field',)) And I am getting a tuple instead of a list. I would prefer to have a list of strings Answer: Don't shadow built-ins (list), change to `alist = cursor.fetchall()` This generator expression will get you the column names in a tuple: `tuple(i[0] for i in alist)`
python: validate kerberos ticket Question: I'm wondering - if anyone has an elegant solution to checking for a valid Kerberos ticket using Python. I'm not seeing anyway with `kinit` or `klist` that will show if a ticket is expired with a return code but I could run `klist` and use a regex for the output . Answer: You've got two options: the first is to use 'klist -s' and check the return code. The nicer option is to use the [python- krbV](https://pypi.python.org/pypi/python-krbV) module: import krbV def has_ticket(): ''' Checks to see if the user has a valid ticket. ''' ctx = krbV.default_context() cc = ctx.default_ccache() try: princ = cc.principal() retval = True except krbV.Krb5Error: retval = False return retval
error in connecting to a smtp server with python Question: import smtplib SERVER = "my.smtp.server.com" FROM = "myemail@somehost.ca" TO = ["someemail@somehost.mun.ca"] # must be a list SUBJECT = "Hello!" TEXT = "hello" Here is my code: # Prepare actual message message = """\ From: %s To: %s Subject: %s %s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) # Send the mail server = smtplib.SMTP(SERVER) server.login('loginname','password') and this is the error I get: Traceback (most recent call last): File "C:\Documents and Settings\Desktop\New Text Document.py", line 24, in ? server = smtplib.SMTP(SERVER) File "C:\Python24\lib\smtplib.py", line 241, in __init__ (code, msg) = self.connect(host, port) File "C:\Python24\lib\smtplib.py", line 289, in connect for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): gaierror: (11001, 'getaddrinfo failed') what do I do next? Answer: There is no ip for `my.smtp.server.com` in your **dns** or **/etc/hosts** ? -> [DNS Wikipedia](http://en.wikipedia.org/wiki/Domain_Name_System) is `my.smtp.server.com` a real (smtp-)server ? have tried a telnet to port 25 of `my.smtp.server.com` ? firewall problems ? if you need a test-server -> [lamson](http://lamsonproject.org/)
Netbeans + sqlite3 = Fail? Question: I've decided to give Python a try on Netbeans. The problem so far is when try to run program _I know_ works, i.e. if I ran it through the terminal. For the project I selected the correct Python version (2.6.5). And received the following error: > Traceback (most recent call last): File > "/Users/XXX/NetBeansProjects/NewPythonProject3/src/newpythonproject3.py", > line 4, in import sqlite3 ImportError: No module named sqlite3 Answer: Search for PYTHONPATH. You probably have different settings in your OS and Netbeans.
Python splitting list based on missing numbers in a sequence Question: I am looking for the most pythonic way of splitting a list of numbers into smaller lists based on a number missing in the sequence. For example, if the initial list was: seq1 = [1, 2, 3, 4, 6, 7, 8, 9, 10] the function would yield: [[1, 2, 3, 4], [6, 7, 8, 9, 10]] or seq2 = [1, 2, 4, 5, 6, 8, 9, 10] would result in: [[1, 2], [4, 5, 6], [8, 9, 10]] Answer: From the [python documentation](http://docs.python.org/library/itertools.html#itertools- example): >>> # Find runs of consecutive numbers using groupby. The key to the solution >>> # is differencing with a range so that consecutive numbers all appear in >>> # same group. >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] >>> for k, g in groupby(enumerate(data), lambda (i,x):i-x): ... print map(itemgetter(1), g) ... [1] [4, 5, 6] [10] [15, 16, 17, 18] [22] [25, 26, 27, 28] The groupby() function from the itertools module generates a break every time the key function changes its return value. The trick is that the return value is the number in the list minus the position of the element in the list. This difference changes when there is a gap in the numbers. The itemgetter() function is from the [operator module](http://docs.python.org/library/operator.html#operator.itemgetter), you'll have to import this and the itertools module for this example to work. Full example with your data: >>> from operator import itemgetter >>> from itertools import * >>> seq2 = [1, 2, 4, 5, 6, 8, 9, 10] >>> list = [] >>> for k, g in groupby(enumerate(seq2), lambda (i,x):i-x): ... list.append(map(itemgetter(1), g)) ... >>> print list [[1, 2], [4, 5, 6], [8, 9, 10]] Or as a list comprehension: >>> [map(itemgetter(1), g) for k, g in groupby(enumerate(seq2), lambda (i,x):i-x)] [[1, 2], [4, 5, 6], [8, 9, 10]]
How do I pipe the output of file to a variable in Python? Question: How do I pipe the output of file to a variable in Python? Is it possible? Say to pipe the output of `netstat` to a variable x in Python? Answer: It is possible. See: <http://docs.python.org/library/subprocess.html#replacing-bin-sh-shell- backquote> In Python 2.4 and above: from subprocess import * x = Popen(["netstat", "-x", "-y", "-z"], stdout=PIPE).communicate()[0]
python human readable large numbers Question: is there a python library that would make numbers such as this more human readable $187,280,840,422,780 edited: for example iw ant the output of this to be 187 Trillion not just comma separated. So I want output to be trillions, millions, billions etc Answer: As I understand it, you only want the 'most significant' part. To do so, use `floor(log10(abs(n)))` to get number of digits and then go from there. Something like this, maybe: import math millnames = ['',' Thousand',' Million',' Billion',' Trillion'] def millify(n): n = float(n) millidx = max(0,min(len(millnames)-1, int(math.floor(0 if n == 0 else math.log10(abs(n))/3)))) return '{:.0f}{}'.format(n / 10**(3 * millidx), millnames[millidx]) Running the above function for a bunch of different numbers: for n in (1.23456789 * 10**r for r in range(-2, 19, 1)): print('%20.1f: %20s' % (n,millify(n))) 0.0: 0 0.1: 0 1.2: 1 12.3: 12 123.5: 123 1234.6: 1 Thousand 12345.7: 12 Thousand 123456.8: 123 Thousand 1234567.9: 1 Million 12345678.9: 12 Million 123456789.0: 123 Million 1234567890.0: 1 Billion 12345678900.0: 12 Billion 123456789000.0: 123 Billion 1234567890000.0: 1 Trillion 12345678900000.0: 12 Trillion 123456789000000.0: 123 Trillion 1234567890000000.0: 1235 Trillion 12345678899999998.0: 12346 Trillion 123456788999999984.0: 123457 Trillion 1234567890000000000.0: 1234568 Trillion
Python regex confused by brackets ([])? Question: Is python confused, or is the programmer? I've got a lot of lines of this: some_dict[0x2a] = blah some_dict[0xab] = blah, blah What I'd like to do is to convert the hex codes into all uppercase to look like this: some_dict[0x2A] = blah some_dict[0xAB] = blah, blah So I decided to call in the regular expressions. Normally, I'd just do this using my editor's regexps (xemacs), but the need to convert to uppercase pushes one into Lisp. ....ok... how about Python? So I whip together a short script which doesn't work. I've condensed the code into this example, which doesn't work either. It looks to me like Python's regexps are getting confused by the brackets in the code. Is it me or Python? import fileinput import sys import re this = "0x2a" that = "[0x2b]" for line in [this, that]: found = re.match("0x([0-9,a-f]{2})", line) if found: print("Found: %s" % found.group(0)) (I'm using the () grouping constructs so I don't capitalize the 'x' in '0x'.) This example only prints the 0x2a value, not the 0x2b. Is this correct behavior? I can easily work around this by changing the match expression to: found = re.match("\[0x([0-9,a-f]{2}\])", line) but I'm just wondering if someone can give me some insight into what's going on here. Running Python 2.6.2 on Linux. Answer: `re.match` matches from the _start_ of the string. Use `re.search` instead to "match the first occurrence anywhere in the string". The key bit about this in the docs is [here](https://docs.python.org/2/library/re.html#search-vs-match).
How to create a Cocoa library and use it in python Question: I've been making a game and the python library I was used is terrible (Pyglet). I want to try using Cocoa for the OSX version. I'll be able to figure out using the objects from classes like NSWindow and NSOpenGLView and then put these objects in my own class for the game loop. I have no idea how I can use PyObjC to load a dynamic Objective-C library I can make and then use the class I will make in python to setup the game which I suppose can be looped by NSTimer. However, the loop method will also need to call a python method from one of many python classes. My game consists of many python classes which are used for different sections of the game (Mapmaker,GameSession,AnacondaGame etc.). The game loop will need to call a loop method in any of these classes depending on the current section and pass even information. PyObjC is "bi-directional" apparently so how is that done? Alternatively I could create two methods to be called by python and I add the python code in-between, where the loop is controlled by python. The "documentation" on the PyObjC website only seem to explain how to use Cocoa in python and nothing else. What I can't do is make a fixed GUI with the interface builder because the library will need to create windows based on the python input to an initialisation method of my class. Knowing the syntax of Objective-C isn't a big problem and I can reefer to the Cocoa documentation to make the objects I require. Thank you for any help. It will be appreciated very much. I'm sick of using broken libraries like pygame and pyglet, using the platform specific OS APIs seems to be the best method to ensure quality. Answer: PyObjC bridges Python to the Objective-C runtime, so if you create NSObject subclasses in Python, they'll be accessible from Objective-C code running in the same process. What this means is that you'll need to encapsulate all of your Python functionality in a subclass of NSObject that you can access over the bridge. The way I'd do this is by having a singleton controller class on the Objective-C side that has a method like `-(void)pythonReady:(PythonClass *)pythonObject`, and also handles the loading of the Python code (which ensures that the controller class exists when your Python code is loaded). Then, in your Python code, after creating an instance of your PythonClass, you can call `pythonReady:` on your controller singleton. Then, in `pythonReady:` on the Objective-C side, you can call whatever methods you need on `pythonObject`, which will run the code on the Python side. To load the Python code from your controller class, you can do something like this: #import <Python/Python.h> @implementation PythonController (Loading) - (void)loadPython { NSString *pathToScript = @"/some/path/to/script.py"; setenv("PYTHONPATH", [@"/some/path/to/" UTF8String], 1); Py_SetProgramName("/usr/bin/python"); Py_Initialize(); FILE *pyScript = fopen([pathToScript UTF8String], "r"); int result = PyRun_SimpleFile(pyScript, [[pathToScript lastPathComponent] UTF8String]); if (result != 0) { NSLog(@"Loading Python Failed!"); } } @end Basically, we simply use the Python C API to run the script inside the current process. The script itself starts the bridge to the runtime in the current process, where you can then use the Cocoa API to access your controller singleton.
Django web interface to store queries and define context Question: I'm open to persuasion that this is a bad idea. But if not, here's the general draw: 1. Web interface to maintain data (django.contrib.admin). 2. Web interface to create pages (django.contrib.flatpages) 3. Web interface to create templates ([dbtemplates](http://packages.python.org/django-dbtemplates/index.html)) 4. **Where is the web interface to create queries and define context?** (contexts?) **EDIT** * * * Here's the normal situation for Django site development. You have a new page to make, figure out the url for it, figure out what data is needed to support the page, then create the appropriate templates so the data is presented the way you intend. What I'd like is to be able to do is define what data is needed to support the page from the admin interface; essentially what you put into a views.py file. I imagine there being a wrapper view that handles auth, but receives all of its context from a model (table). from dbcontext import DBContext # this is fictitious def db_context_view(request, **args, **kwargs): # ...some code to handle auth context = DBContext.objects.get_context_for_request(request, **args, **kwargs) return render_to_response('mydbtemplates/example.html', context) I would be happy to still edit the urls.py file to ensure enough gets passed to the view so that the DBContext manager can locate the appropriate context record, perform the desired queries (satisfying any query parameters), and return the appropriate dictionary for the template to succeed. Answer: I believe you're looking for the [contenttypes framework](http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/). With the contenttypes framework, you would be able to do something like this: def db_context_view(request, *args, **kwargs): # ...some code to handle auth ct = ContentType.objects.get_for_id(kwargs['content_type_id']) obj = ct.get_object_for_this_type(pk=kwargs['object_id']) Using this approach, you could build the view you desire.
cannot change font to Helvetica in Matplotlib in Python on Mac OS X 10.6 Question: I am trying to change the matplotlib font to helvetica, which I'd like to use in a PDF plot. I try the following: import matplotlib matplotlib.use('PDF') import matplotlib.pylab as plt from matplotlib import rc plt.rcParams['ps.useafm'] = True rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) plt.rcParams['pdf.fonttype'] = 42 This does not work -- when I run my code with --verbose-debug, I get the error: backend WXAgg version 2.8.10.1 /Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/site-packages/matplotlib/__init__.py:833: UserWarning: This call to matplotlib.use() has no effect because the the backend has already been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot, or matplotlib.backends is imported for the first time. findfont: Could not match :family=sans-serif:style=normal:variant=normal:weight=normal:stretch=normal:size=medium. Returning /Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/site-packages/matplotlib/mpl-data/fonts/ttf/Vera.ttf Assigning font /F1 = /Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/site-packages/matplotlib/mpl-data/fonts/ttf/Vera.ttf Embedding font /Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/site-packages/matplotlib/mpl-data/fonts/ttf/Vera.ttf Writing TrueType font So apparently it cannot find Helvetica. I am not sure why. I have Helvetica in the afm directory of mpl-data, and when matplotlib initiates it reads it and outputs: createFontDict: /Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/site-packages/matplotlib/mpl-data/fonts/afm/Helvetica.afm Do I need a special .ttf Helvetica font in addition? If so, how can I get it? I know I have Helvetica on my system since I see it in Illustrator and many other programs. I am using Enthought Python distribution as follows: $ python Enthought Python Distribution -- http://www.enthought.com Version: 6.2-2 (32-bit) Python 2.6.5 |EPD 6.2-2 (32-bit)| (r265:79063, May 28 2010, 15:13:03) [GCC 4.0.1 (Apple Inc. build 5488)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import matplotlib >>> matplotlib.__version__ '0.99.3' Any ideas how this can be fixed? thanks. Answer: The solution is to use fondu to convert the .dfont Helvetica font from Mac OS X into .ttf, and then place that in the mpl-data/fonts directory that Matplotlib looks in. That solved the issue.
Python: Load module by its name Question: I'm working on a django project that serves multiple sites; depending on the site I want to import different functionality from a different module; how do I import a module in Python if I have the name of its package and the module name itself as a string? Answer: in Python generally, you can use `__import__` builtin function or `imp` module features: >>> sys1 = __import__("sys") >>> import imp >>> sys2 = imp.load_module("sys2", *imp.find_module("sys")) >>> import sys >>> sys is sys1 is sys2 True
reading file data mixing strings and numbers in python Question: I would like to read different files in one directory with the following structure: # Mj = 1.60 ff = 7580.6 gg = 0.8325 I would like to read the numbers from each file and associate every one to a vector. If we assume I have 3 files, I will have 3 components for vector Mj, ... How can I do it in Python? Thanks for your help. Answer: I'd use a regular expression to take the line apart: import re lineRE = re.compile(r''' \#\s* Mj\s*=\s*(?P<Mj>[-+0-9eE.]+)\s* ff\s*=\s*(?P<ff>[-+0-9eE.]+)\s* gg\s*=\s*(?P<gg>[-+0-9eE.]+) ''', re.VERBOSE) for filename in filenames: for line in file(filename, 'r'): m = lineRE.match(line) if not m: continue Mj = m.group('Mj') ff = m.group('ff') gg = m.group('gg') # Put them in whatever lists you want here.
Python geocode filtering by distance Question: I need to filter geocodes for near-ness to a location. For example, I want to filter a list of restaurant geocodes to identify those restaurants within 10 miles of my current location. Can someone point me to a function that will convert a distance into latitude & longitude deltas? For example: class GeoCode(object): """Simple class to store geocode as lat, lng attributes.""" def __init__(self, lat=0, lng=0, tag=None): self.lat = lat self.lng = lng self.tag = None def distance_to_deltas(geocode, max_distance): """Given a geocode and a distance, provides dlat, dlng such that |geocode.lat - dlat| <= max_distance |geocode.lng - dlng| <= max_distance """ # implementation # uses inverse Haversine, or other function? return dlat, dlng Note: I am using the supremum norm for distance. Answer: There seems not to have been a good Python implementation. Fortunately the SO "Related articles" sidebar is our friend. [This SO article](http://stackoverflow.com/questions/1689096/calculating-bounding-box- a-certain-distance-away-from-a-lat-long-coordinate-in-ja) points to an [excellent article](http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates) that gives the maths and a Java implementation. The actual function that you require is rather short and is embedded in my Python code below. Tested to extent shown. Read warnings in comments. from math import sin, cos, asin, sqrt, degrees, radians Earth_radius_km = 6371.0 RADIUS = Earth_radius_km def haversine(angle_radians): return sin(angle_radians / 2.0) ** 2 def inverse_haversine(h): return 2 * asin(sqrt(h)) # radians def distance_between_points(lat1, lon1, lat2, lon2): # all args are in degrees # WARNING: loss of absolute precision when points are near-antipodal lat1 = radians(lat1) lat2 = radians(lat2) dlat = lat2 - lat1 dlon = radians(lon2 - lon1) h = haversine(dlat) + cos(lat1) * cos(lat2) * haversine(dlon) return RADIUS * inverse_haversine(h) def bounding_box(lat, lon, distance): # Input and output lats/longs are in degrees. # Distance arg must be in same units as RADIUS. # Returns (dlat, dlon) such that # no points outside lat +/- dlat or outside lon +/- dlon # are <= "distance" from the (lat, lon) point. # Derived from: http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates # WARNING: problems if North/South Pole is in circle of interest # WARNING: problems if longitude meridian +/-180 degrees intersects circle of interest # See quoted article for how to detect and overcome the above problems. # Note: the result is independent of the longitude of the central point, so the # "lon" arg is not used. dlat = distance / RADIUS dlon = asin(sin(dlat) / cos(radians(lat))) return degrees(dlat), degrees(dlon) if __name__ == "__main__": # Examples from Jan Matuschek's article def test(lat, lon, dist): print "test bounding box", lat, lon, dist dlat, dlon = bounding_box(lat, lon, dist) print "dlat, dlon degrees", dlat, dlon print "lat min/max rads", map(radians, (lat - dlat, lat + dlat)) print "lon min/max rads", map(radians, (lon - dlon, lon + dlon)) print "liberty to eiffel" print distance_between_points(40.6892, -74.0444, 48.8583, 2.2945) # about 5837 km print print "calc min/max lat/lon" degs = map(degrees, (1.3963, -0.6981)) test(*degs, dist=1000) print degs = map(degrees, (1.3963, -0.6981, 1.4618, -1.6021)) print degs, "distance", distance_between_points(*degs) # 872 km
Failure loading py2exe'd program when including pysvn Question: I am attempting to run a py2exe'd program (package.py) that includes pysvn. It is failing to run with the following error: Traceback (most recent call last): File "package.py", line 27, in <module> File "zipextimporter.pyc", line 82, in load_module File "pysvn\__init__.pyc", line 99, in <module> File "zipextimporter.pyc", line 98, in load_module ImportError: MemoryLoadLibrary failed loading pysvn\_pysvn_2_6.pyd The script runs fine for others in the office, the difference being I'm on Windows 7 x64 with them on WinXP x86. I do have _pysvn_2_6.pyd in my pysvn directory. Py2exe's "Problems to be Fixed" page has a similar error message with WxPython where it cannot find a needed system module, but I am not using WxPython and I have the dll they refer to anyway. The py2exe page for "Working with Various Packages and Modules" doesn't refer to pysvn, and I can't find anyone else with similar problems. I've checked the output of py2exe as outlined by [this answer](http://stackoverflow.com/questions/1048651/problem-deploying-python- program-packaged-with-py2exe/1124797#1124797), but my computer seems to have all the binary files required in the correct locations. EDIT: I just tried to run other py2exe created programs on this same machine and they failed as well. It seems that the problem is with my machine (ie x64) rather than the specific program I was converting; I get a similar error with another program: Traceback (most recent call last): File "rundemo.py", line 13, in <module> import win32api as w32 File "zipextimporter.pyc", line 98, in load_module ImportError: MemoryLoadLibrary failed loading win32api.pyd EDIT2: I tried the py2exe programs generated from my 64 bit compy on a 32 bit machine, and they failed with the same error. I think I'm generating 32 bit exe's (py2exe docs say 64-bit support is experimental, and I haven't explicitly turned it on), but I'm not sure how to check to be sure. Answer: Install [PyWin32](http://starship.python.net/~skippy/).
catch specific HTTP error in python Question: I want to catch a specific http error and not any one of the entire family.. what I was trying to do is -- import urllib2 try: urllib2.urlopen("some url") except urllib2.HTTPError: <whatever> but what I end up is catching any kind of http error, but I want to catch only if the specified webpage doesn't exist!! probably that's HTTP error 404..but I don't know how to specify that catch only error 404 and let the system run the default handler for other events..ny suggestions?? Answer: Just catch `urllib2.HTTPError`, handle it, and if it's not Error 404, simply use `raise` to re-raise the exception. See the [Python tutorial](http://docs.python.org/tutorial/errors.html#handling-exceptions). So you could do: import urllib2 try: urllib2.urlopen("some url") except urllib2.HTTPError as err: if err.code == 404: <whatever> else: raise
Can you pass multiple paths to the Django runserver --pythonpath directive? Question: For each of my projects I create an apps directory that holds all the apps I need. Satchmo also has an apps directory. Can I do something like _python manage.py runserver --pythonpath=/path/to/my/apps /path/to/satchmo/apps_? Is there some separator that it can take? Answer: There's no `--pythonpath` option to runserver. You either want to add it to your `.bashrc` file or in your `settings.py` file add something like the following at the top: import os,sys PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__)) sys.path.append(PROJECT_ROOT, 'to', 'my', 'apps') sys.path.append(os.path.join('path', 'to', 'satchmo', 'apps'))
Python socket server craps out after receiving data Question: I'm currently dabbling in sockets. I've got a jquery script that uses a very small flash swf file to establish a true socket connection. As a server I'd like to use python. Everything works, but I can only send information to the server just once. I've tried 2 pieces of python code for the server. I guess since they both have the same problem the problem's not here. # TCP server example import socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(("", 2000)) server_socket.listen(5) print "TCPServer Waiting for client on port 2000" while 1: client_socket, address = server_socket.accept() print "I got a connection from ", address while 1: data = client_socket.recv(512) print "RECIEVED:" , data Or this one: import socket mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) mySocket.bind ( ( '', 2000 ) ) mySocket.listen ( 1 ) while True: channel, details = mySocket.accept() print 'We have opened a connection with', details print channel.recv ( 100 ) channel.close() On the client side I use <http://devpro.it/xmlsocket/> Sending a piece of data is as simple as executing xmls.send('some text'); Which arrives, but after that it stops working. Does anyone know a solution? Or possibly a better javascript/swf combination I could use? Answer: I think you need to 'listen' again after you close the connection. Also, Sockets deliver data as per the tcp specifications. You're not guaranteed to get all of any data sent in one socket read. I see nothing to perform multiple reads and assemble a complete 'message'
How to use nose with IronPython? Question: I installed nose using the 'setup.py install' on the command line , I am able to run 'nosetests' and any python file matching testMatch regular expression is picked up and tests are automated in the %python home%\Scripts directory. Now I want nose to work with my iron Python files , how do I install nose on the %Iron Python home% directory ? i noticed my Iron Python Home directory does not even have a Scripts folder. If i try running 'nosetests' with iron python code , it throws all sorts of exception for eg. no module named clr. Is anybody using nose with iron python ? if yes , please guide me. I have been struggling with this since an entire day, currently my only workaround has been adding the following in my IronPython code: import nose nose.main(argv=['<arguments>']) is this is the only way to go about using nose in iron python files ? if there is no other way , then I wanted to know how to use the several plugins that nose has ? especially the coverage plugin ? i installed it for python2.6 , but how to make it work for ironpython ? The reason I am asking is because with python , it gets easy to use the plugins just by calling the command line , but with IronPython I don't know how to make it work. Answer: Your solution is actually all [`nosetests`](http://python- nose.googlecode.com/hg/bin/nosetests) does: #!/usr/bin/env python from nose import main if __name__ == '__main__': main() You'll want to make sure you add your system's Python lib to the path for it to find the nose extensions: >>>import sys >>>sys.path.append(r'C:\Python26\lib') And you'll need to make sure you're executing your script with `ipy.exe` and not your system's Python executable.
How to read String in java that was written using python’s struct.pack method Question: out.write( struct.pack(">f", 1.1) ); out.write( struct.pack(">i", 12) ); out.write( struct.pack(">3s", "abc") ); how to import struct package in java it says .. > no package found when i am trying to execute it so kindly tell me any suggestions if any Thanking you i took that code from <http://stackoverflow.com/questions/1255918/how-to-read- string-in-java-that-was-written-using-pythons-struct-pack-method> Answer: Read the answer to the question you referenced. The sample code in the question was incorrect. Also, you don't import the struct package in Java. It's a Python package. Also as described in the other question, you use java.io.DataInputStream to read the file created from Python.
How to synchronize the output of Python subprocess Question: I think I'm having issues to synchronize the output of two Popen running concurrently. It seems that the output from these two different command lines are interleaved with one another. I also tried using RLock to prevent this from happening but it didn't work. A sample output would be: cmd1 cmd1 cmd2 cmd2 cmd2 cmd2 cmd1 cmd2 The code is as attached: import subprocess import threading class PopenWorkerThread(threading.Thread): def __init__(self, cmdLine): self.lock = threading.RLock() self.WebSphereCmdLine = cmdLine threading.Thread.__init__(self) def run(self): logger.error('Runninf: ' + self.WebSphereCmdLine) proc = subprocess.Popen(self.WebSphereCmdLine, shell=False, stdout=subprocess.PIPE) while True: self.lock.acquire() print proc.stdout.readline() self.lock.release() def launch(): commandLine = ['ls -l', 'netstat'] for cmdLine in commandLine: workerThread = PopenWorkerThread(cmdLine) workerThread.start() launch() Is there a way to synchronize the outputs so that they look like such? cmd1 cmd1 cmd1 cmd1 cmd1 cmd2 cmd2 cmd2 cmd2 cmd2 Answer: You're locking with a granularity of a line, so of course lines from one thread can and do alternate with lines from the other. As long as you're willing to wait until a process ends before showing any of its output, you can lock with the larger "process" granularity. Of course you have to use the SAME lock for both threads -- having each thread use a completely separate lock, as you're doing now, cannot achieve anything at all, obviously. So, for example: import subprocess import threading class PopenWorkerThread(threading.Thread): lock = threading.RLock() # per-class, NOT per-instance! def __init__(self, cmdLine): self.WebSphereCmdLine = cmdLine threading.Thread.__init__(self) def run(self): logger.error('Runninf: ' + self.WebSphereCmdLine) proc = subprocess.Popen(self.WebSphereCmdLine, shell=False, stdout=subprocess.PIPE) result, _ = proc.communicate() with self.lock: print result, def launch(): commandLine = ['ls -l', 'netstat'] for cmdLine in commandLine: workerThread = PopenWorkerThread(cmdLine) workerThread.start() launch()
Class design — circular references between related classes Question: I need help trying to figure out the proper design of my classes. I have a user class: class AppUser: _email - String _fullname - String _organizations - List of ???? _active - Boolean ------------------ getOrgs - Method Also, I have an Organizations class: class Organization: _name - String _domain - String _members - List of ???? ------------------ getMembers So, my issue is the Lists. The Org class has a list of _members. This list should probably be a list of AppUser objects. And, the AppUser class has a list of _organizations. This list should probably be a list of Organization objects. But this would create a circular reference. So, how should I implement this? Edit: Need to implement this using Python. Answer: You did not specify which language you were using. That is important because in some languages circular references do cause problems (VB6) while in others they do not (Java, C#, etc.). In most cases you will be okay with circular references in your class hierarchies especially if you are using a modern language that uses garbage collection for memory management.
How to generate an HMAC in Java equivalent to a Python example? Question: I'm looking at implementing an app getting [Twitter authorization via Oauth](http://apiwiki.twitter.com/Authentication) in Java. The first step is [getting a request token](http://apiwiki.twitter.com/Twitter-REST-API- Method%3A-oauth-request_token). Here is a [Python example](http://github.com/tav/tweetapp/blob/master/standalone/twitter_oauth_handler.py) for app engine. To test my code, I am running Python and checking output with Java. Here is an example of Python generating a Hash-Based Message Authentication Code (HMAC): #!/usr/bin/python from hashlib import sha1 from hmac import new as hmac key = "qnscAdgRlkIhAUPY44oiexBKtQbGY0orf7OV1I50" message = "foo" print "%s" % hmac(key, message, sha1).digest().encode('base64')[:-1] Output: $ ./foo.py +3h2gpjf4xcynjCGU5lbdMBwGOc= How does one replicate this example in Java? I've seen an [example of HMAC](http://exampledepot.8waytrips.com/egs/javax.crypto/GenMac.html) in Java: try { // Generate a key for the HMAC-MD5 keyed-hashing algorithm; see RFC 2104 // In practice, you would save this key. KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5"); SecretKey key = keyGen.generateKey(); // Create a MAC object using HMAC-MD5 and initialize with key Mac mac = Mac.getInstance(key.getAlgorithm()); mac.init(key); String str = "This message will be digested"; // Encode the string into bytes using utf-8 and digest it byte[] utf8 = str.getBytes("UTF8"); byte[] digest = mac.doFinal(utf8); // If desired, convert the digest into a string String digestB64 = new sun.misc.BASE64Encoder().encode(digest); } catch (InvalidKeyException e) { } catch (NoSuchAlgorithmException e) { } catch (UnsupportedEncodingException e) { } It uses [javax.crypto.Mac](http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/javax/crypto/Mac.html), all good. However, the [SecretKey](http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/javax/crypto/SecretKey.html) constructors take bytes and an algorithm. What's the algorithm in the Python example? How can one create a Java secret key without an algorithm? Answer: HmacSHA1 seems to be the algorithm name you need: SecretKeySpec keySpec = new SecretKeySpec( "qnscAdgRlkIhAUPY44oiexBKtQbGY0orf7OV1I50".getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(keySpec); byte[] result = mac.doFinal("foo".getBytes()); BASE64Encoder encoder = new BASE64Encoder(); System.out.println(encoder.encode(result)); produces: +3h2gpjf4xcynjCGU5lbdMBwGOc= Note that I've used `sun.misc.BASE64Encoder` for a quick implementation here, but you should probably use something that doesn't depend on the Sun JRE. [The base64-encoder in Commons Codec](http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html) would be a better choice, for example.
No module named django.core Question: I'm following the step by step guide [here](http://jeffbaier.com/articles/installing-django-on-an-ubuntu-linux- server/) and I hit an error at the "Create Django Project" step when I try the command; > django-admin.py startproject myproject The error: > Traceback (most recent call last): > File "/usr/local/bin/django-admin.py", line 2, in from django.core import > management ImportError: No module named django.core Running on Ubuntu Server with Python 2.6. I'm sure it's a really simple error, and something do with Python paths, but I'm a Linux newbie. Thanks! Answer: Thanks to Daniel Roseman's comment, I investigated and found my symlink was broken. Just had to recreate that and it worked nicely.
append a particular column from a csv file to another using python Question: I'll explain my whole problem: I have 2 csv files: * project-table.csv (has about 50 columns) * interaction-matrix.csv (has about 45 columns) I want to append the string in `col[43]` from project-table.csv with string in `col[1]` of interaction-matrix.csv with a dot(`.`) in between both the strings next, * interaction-matrix.csv has a set of headers.. * its 1st col will now have the appended string after doing what I've mentioned above * all other remaining columns have only 0's and 1's * I'm supposed to extract only those columns with 1's from this interaction-matrix.csv and copy it to a new csv file... (with the first column intact) this is the code i ve come up with... I'm getting an error with the `keepcols` line... import csv reader=csv.reader(open("project-table.csv","r")) writer=csv.writer(open("output.csv","w"),delimiter=" ") for data in reader: name1=data[1].strip()+'.'+data[43].strip() writer.writerow((name1, None)) reader=csv.DictReader(open("interaction-matrix.csv","r"),[]) allrows = list(reader) keepcols = [c for c in allrows[0] if all(r[c] != '0' for r in allrows)] print keepcols writer=csv.DictWriter(open("output1.csv","w"),fieldnames='keepcols',extrasaction='ignore') writer.writerows(allrows) this is the error i get: Traceback (most recent call last): File "prg1.py", line 23, in ? keepcols = [c for c in allrows[0] if all([r[c] != '0' for r in allrows])] NameError: name 'all' is not defined project table and interaction-matrix both have the same data in their respective 1st columns .. so i just appended col[43] of prj-table to col[1] of the same table itself... Answer: Edit your question to show what error message are you getting. Update: NameError probably means you are using an (older) version of Python (which one?) without `all()` or (you have used `all` as a variable name AND are not showing the exact code that you ran) Note: open both files in binary mode ("rb" and "wb") respectively. You say "I want to append the string in col[43] from project-table.csv with string in col[1] of interaction-matrix.csv with a dot(.) in between both the strings" HOWEVER you are using col[2] (not col[1]) of project-table.csv (not interaction-matrix.csv, which you haven't opened at that stage).
Extract Meta Keywords From Webpage? Question: I need to extract the meta keywords from a web page using Python. I was thinking that this could be done using urllib or urllib2, but I'm not sure. Anyone have any ideas? I am using Python 2.6 on Windows XP Answer: [lxml](http://codespeak.net/lxml/index.html#documentation) is faster than BeautifulSoup (I think) and has much better functionality, while remaining relatively easy to use. Example: 52> from urllib import urlopen 53> from lxml import etree 54> f = urlopen( "http://www.google.com" ).read() 55> tree = etree.HTML( f ) 61> m = tree.xpath( "//meta" ) 62> for i in m: ..> print etree.tostring( i ) ..> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-2"/> Edit: another example. 75> f = urlopen( "http://www.w3schools.com/XPath/xpath_syntax.asp" ).read() 76> tree = etree.HTML( f ) 85> tree.xpath( "//meta[@name='Keywords']" )[0].get("content") 85> "xml,tutorial,html,dhtml,css,xsl,xhtml,javascript,asp,ado,vbscript,dom,sql,colors,soap,php,authoring,programming,training,learning,b eginner's guide,primer,lessons,school,howto,reference,examples,samples,source code,tags,demos,tips,links,FAQ,tag list,forms,frames,color table,w3c,cascading style sheets,active server pages,dynamic html,internet,database,development,Web building,Webmaster,html guide" BTW: [XPath](http://www.w3schools.com/XPath/xpath_syntax.asp) is worth knowing. Another edit: Alternatively, you can just use regexp: 87> f = urlopen( "http://www.w3schools.com/XPath/xpath_syntax.asp" ).read() 88> import re 101> re.search( "<meta name=\"Keywords\".*?content=\"([^\"]*)\"", f ).group( 1 ) 101>"xml,tutorial,html,dhtml,css,xsl,xhtml,javascript,asp,ado,vbscript,dom,sql, ...etc... ...but I find it less readable and more error prone (but involves only standard module and still fits on one line).
Import large chunk of data into Google App Engine Data Store at one go Question: I have a large CSV file, approx 10 MB in size, which contains all the data which need to be imported in the Google App Engine DataStore. I tried following approaches to perform import but all the times it failed in half way. * Import using mapping a command to url and then executing url, failed because of request time out... * Import using creating cron job, but got DeadlineExceededError... * Import using remort_api_shell, but got Operation timed out. Can you please suggest me and approch (using dummy data you can imagine) how to do it... Suggestion with code will be more helpful.. ** I am using Python and google's web app framework to develop the said app. Answer: you can post row by row. using built in bulk loader. <http://code.google.com/appengine/docs/python/tools/uploadingdata.html> this is good article. and here is my contactloader.py that i used 2 years ago for reference. it is more sophisticated since last i used but still..... import datetime from google.appengine.ext import db from google.appengine.tools import bulkloader class Contact(db.Model): date = db.DateTimeProperty(auto_now_add=True) owner = db.StringProperty() companyname = db.StringProperty() companyemail = db.EmailProperty() def myfunc(x): temp = x.split(":mailto:") if len(temp) > 0: temp = temp[-1].split(":") else: return "defaultvalue" if len(temp) > 0: temp = temp[0] else: return "defaultvalue" temp = temp.split("<1>")[0] if temp is None or len(temp) < 5: return "defaultvalue" return temp def mysecfunc(x): return x.split("<0>")[0] class ContactLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'Contact', [ ('companyname',mysecfunc), ('owner', lambda x:"somevalue"), ('companyemail',myfunc), ("date",lambda x:datetime.datetime.now()), ]) loaders = [ContactLoader]
Read all the contents in ini file into dictionary with Python Question: Normally, I code as follows for getting a particular item in a variable as follows try: config = ConfigParser.ConfigParser() config.read(self.iniPathName) except ConfigParser.MissingSectionHeaderError, e: raise WrongIniFormatError(`e`) try: self.makeDB = config.get("DB","makeDB") except ConfigParser.NoOptionError: self.makeDB = 0 Is there any way to read all the contents in a python dictionary? For example [A] x=1 y=2 z=3 [B] x=1 y=2 z=3 is written into val["A"]["x"] = 1 ... val["B"]["z"] = 3 Answer: I suggest subclassing `ConfigParser.ConfigParser` (or `SafeConfigParser`, &c) to safely access the "protected" attributes (names starting with single underscore -- "private" would be names starting with _two_ underscores, not to be accessed even in subclasses...): import ConfigParser class MyParser(ConfigParser.ConfigParser): def as_dict(self): d = dict(self._sections) for k in d: d[k] = dict(self._defaults, **d[k]) d[k].pop('__name__', None) return d This emulates the usual logic of config parsers, and is guaranteed to work in all versions of Python where there's a `ConfigParser.py` module (up to 2.7, which is the last of the `2.*` series -- knowing that there will be no future Python 2.any versions is how compatibility can be _guaranteed_ ;-). If you need to support future Python `3.*` versions (up to 3.1 and probably the soon forthcoming 3.2 it should be fine, just renaming the module to all- lowercase `configparser` instead of course) it may need some attention/tweaks a few years down the road, but I wouldn't expect anything major.
Get a subset of a generator Question: I have a generator function and want to get the first ten items from it; my first attempt was: my_generator()[:10] This doesn't work because generators aren't subscriptable, as the error tells me. Right now I have worked around that with: list(my_generator())[:10] This works since it converts the generator to a list; however, it's inefficient and defeats the point of having a generator. Is there some built- in, Pythonic equivalent of `[:10]` for generators? Answer: import itertools itertools.islice(mygenerator(), 10) `itertools` has a number of utilities for working with iterators. `islice` takes start, stop, and step arguments to slice an iterator just as you would slice a list.
Jinja2: Looking for a View-Helper Question: I'am new to the Jinja2 template engine. Is there something like the view- helpers from Zend Framework? Can i create simple functions and reuse them all over all my template-files? Something like this? #somewhere in my python code: def nice_demo_function(message): """"return a simple message""" return message So i can to use that: <!-- now in my template-file --> {% nice_demo_function('yes, this works great!') %} Answer: There are a number of ways you can expose helper functions to your templates. You could define them using [macros](http://jinja.pocoo.org/2/documentation/templates#macros), and then [import](http://jinja.pocoo.org/2/documentation/templates#import) them into templates that use them. You could add functions to the [globals attribute](http://jinja.pocoo.org/2/documentation/api#jinja2.Template.globals) of your Template objects, or pass them to the [render()](http://jinja.pocoo.org/2/documentation/api#jinja2.Template.render) method. You could subclass Template to do the same without having to repeat yourself each time. If you want to get really fancy, you could look into writing [extensions](http://jinja.pocoo.org/2/documentation/extensions#jinja- extensions) as well (but you probably don't need to go that deep).
set process name in mod_wsgi Question: I'm running a site by apache2.x with mod_wsgi 2.5, and python2.5. It is configured to run in multi-processes and each process only contains one thread. When I read this [post](http://pragdave.blogs.pragprog.com/pragdave/2008/11/trivial-request- logging-for-rails.html), I try to set the process name to PATH_INFO, but it doesn't work. My code is like: import ctypes libc = ctypes.CDLL('/lib/libc.so.6') def application (environ, start_response): libc.prctl(15, environ.get('PATH_INFO', 'WSGI'), 0, 0, 0); # other codes Answer: If you are using mod_wsgi daemon mode, is there anything wrong with the display-name option to WSGIDaemonProcess. That option is precisely for changing the name of the process to a fixed value using setproctitle() or argv[0] assignment as believed works for specific platforms. See: <http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIDaemonProcess> Note that it only makes sense to do this for daemon mode processes and not the Apache server processes themselves. Thus why is only available for WSGIDaemonProcess directive. It only makes sense to set it once on process start as well and not dynamically based on request.
Session management via pure CGI Question: I'm currently in the process of writing a little blog / generic posting system using CGI in C as a hobby project and am now in the need of a session management system to authentificate authorized users for posting, editing and similar operations over **multiple CGI programs** From working with PHP years ago I remember using the superglobal variable `$_SESSION` and some session intializing functions. _Obviously_ this is not going to work this way when dealing with pure CGI, so I'm in a tricky situation here. A bit of thinking showed that there's many different ways to do such a thing... 1. Saving the IP address and attributes inside a file where I can see if a particular IP is authorized 2. Same as #1 but using an SQLite database (my engine already runs on SQLite so there would be no additional overhead) 3. Something with cookies maybe? Instead of going all in and regret is later... what do **you** good people think? What's the most efficient (and most importantly) and the maintainable method? Please note that I do _not_ want to get a third party libary to do all the complicated things for me! I started this project to build something completely by myself (if you ignore SQLite here) and I don't want to hide the hard parts, even if it makes everything so much simpler. I could have just used Python if I didn't want to torture myself :) Answer: Cookie based session management is the way to go. You cannot merely use an IP address not even IP address + browser combination because that will fail when people are using proxy or are behind NAT. Just send the browser a hash in a cookie, then validate the hash against your record for the user, if it matches, you can then access the data for that user's session. Consider adding an expiry mechanism for the hash. There is a trade off between security and ease of use, because the longer the same hash is valid for the user, the longer the user is vulnerable to a cookie stealing attack. Expiry mechanisms will also enable you to delete stale session data from your database (or file, if you would so choose.)
Weird error when trying to write to an mmap under windows Question: This simple python code: import mmap with file("o:/temp/mmap.test", "w+b") as fp: m = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ|mmap.ACCESS_WRITE) m.write("Hello world!") Produces the following error (on the mmap.mmap(...) line): WindowsError: [Error 1006] The volume for a file has been externally altered so that the opened file is no longer valid Any idea why? Answer: Most likely because `w+` truncates the file, and Windows gives an error when trying to create an empty mapping from that file of length 0. Use `r+` instead. As well, you shouldn't use `access=mmap.ACCESS_READ|mmap.ACCESS_WRITE`: >>> mmap.ACCESS_READ 1 >>> mmap.ACCESS_WRITE 2 >>> mmap.ACCESS_COPY 3 >>> mmap.ACCESS_READ | mmap.ACCESS_WRITE 3 In other words, `access=mmap.ACCESS_READ|mmap.ACCESS_WRITE` is the same as `access=mmap.ACCESS_COPY`. What you want is most likely `access=mmap.ACCESS_WRITE`, and on Windows that's what you get anyway if you don't explicitly use that argument. Try this: import mmap with file("o:/temp/mmap.test", "r+b") as fp: m = mmap.mmap(fp.fileno(), 0) m.write("Hello world!") ( mmap docs: <http://docs.python.org/library/mmap.html> )
Python Rpy R data processing optimization Question: I am writing a data processing program in Python and R, bridged with Rpy2. Input data being binary, I use Python to read data out and pass them to R, then collect results to output. Data are organized into pieces, each being around 100 Bytes (1Byte per value * 100 values). They just work now, but the speed is very low. Here are some of my test on 1GB size (that is, 10^7 pieces) of data: If I disable Rpy2 calls to make a dry run, it takes about 90min for Python to loop all through on a Intel(R) Xeon(TM) CPU 3.06GHz using one single thread. If I enable full functionality and multithreading on that Xeon dual core, it (will by estimation) take ~200hrs for the program to finish. I killed the Python program several times the call stack is almost alwarys pointing to Rpy2 function interface. I also did profiling, which gives similar results. All these observations indicates the R part called by Rpy2 is the bottleneck. So I profiled a standalone version of my R program, but the profiling summary points to "Anonymous". I am still pushing my way to see which part of my R script is the most time consuming one. ***_updated, see my edit below_ **** There are two suspicious candidates through, one being a continuous wavelets transformation (CWT) and wavelets transformation modulus maxima (WTMM) using wmtsa from cran[1], the other being a non-linear fitting of ex-gaussion curve. What come to my mind are: 1. for fitting, I could substitute R routing with inline C code? there are many fitting library available in C and fortran... (idea from the net; I never did that; unsure) 2. for wavelet algorithms.... I would have to analyze the wmtsa package to rewrite hotspots in C? .... reimplementing the entire wmtsa package using C or fortran would be very non-trivial for me. I have not much programming experience. 3. the data piece in file is organized in 20 consecutive Bytes, which I could map directly to a C-like char* array? at present my Python program just read one Byte at a time and append it to a list, which is slow. This part of code takes 1.5 hrs vs. ~200 hrs for R, so not that urgent. This is the first time I meet program efficiency in solving real problems . I STFW and felt overwhelmed by the informations. Please give me some advice for what to do next and how. Cheers! footnotes: 1. <http://cran.r-project.org/web/packages/wmtsa/index.html> *** Update *** Thanks to proftools from cran, I managed to create a call stack graph. And I could see that ~56% of the time are spent on wmtsa, code snippet is like: W <- wavCWT(s,wavelet="gaussian1",variance=1/p) # 1/4 W.tree <-wavCWTTree(W) # 1/2 holderSpectrum(W.tree) # 1/4 ~28% of time is spent on nls: nls(y ~ Q * dexGAUS(x, m, abs(s), abs(n)) + B, start = list(Q = 1000, m = h$time[i], s = 3, n = 8, B = 0), algorithm="default", trace=FALSE) where evaluation of dexGAUS from gamlss.dist package takes the majority of time. remaining ~10% of R time are spent on data passing/split/aggregation/subset. Answer: For option 3.. getting your data in efficiently... read it all in as one long str type in python with a single read from the file. Let's assume it's called myStr. import array myNums = array.array('B', myStr) Now myNums is an array of each byte easily converted... see help(array.array)... in fact, looking at that it looks like you can get it directly from a file that way through the array. That should get rid of 1.4 hours of your data reading.