text
stringlengths
226
34.5k
Python error with debugging Question: I am very new with Python and I have just received this message while trying to use Visual Studio plugin for Python: try: import boinc # getting the exception here _BOINC_ENABLED = True except: _BOINC_ENABLED = False and this is the error message that I get: > exceptions.ImportError occurred Message: No module named boinc the other lines that import files are here : from util import * from util import raiseNotDefined import time, os import traceback (i haven't wrote them they were given in the pacman project) I am trying to use Python for the pacman project that was given to me as an assignment and I am having trouble running the project - debugging it (I didn't write any code yet). Thanks in advance for your kind help. Answer: problem was that my project was not on the root of my hard drive and the project was inside a folder named in hebrew. the path of the folder containning the project must be in english for it to work
python: from modules import abc.py does not work Question: I have recently switched from python 2.7 to python 3.2 considering following folder structure: ~/my_program ~/my_program/modules where *my_program* is the root of the application, containing main script called _main.py_ *my_program/modules* is used to store all additional classes and subscripts in python2.x I was able to import any file "module" the same way I do import standard modules from modules import abc.py however, while I try to launch the same program in python3.2 I get the error message saying: File "/my_program/modules/__init__.py" line 1 import abc, def ImportError: No module named abc Please advise Answer: It's a good example you are using, because "abc" is in fact a module in the standard library. So in fact, if you in Python 3 do `import abc` that will work just fine, but you will get the standard library module. In Python 2, if you had a local module called abc.py, that `import abc` would import the local module instead. That means you couldn't import the module from the standard library. In Python 3, this has been changed, and you now need to use the fully qualified name, in your case probably `from modules import abc`.
Setting properties from CSV file using eval (Python) Question: I have CSV files that contain numerous values that I want to reference. I wanted to parse them succinctly using `eval`. Here's what I tried: line = fileHandle.readline() while line != "": if line != "\n": parameter = line.split(',')[0] value = line.split(',')[2].replace("\n", "") eval("%s = \"%s\"" % (parameter, value)) print(parameter + " = " + eval(parameter)) # a quick test line = fileHandle.readline() What I get is: Traceback (innermost last): File "<string>", line 73, in ? File "<string>", line 70, in createJMSProviders File "<string>", line 49, in createJMSProviderFromFile File "<string>", line 1 externalProviderURL="tibjmsnaming://..." ^ SyntaxError: invalid syntax I reads to me like it is not possible to `eval("externalProviderURL=\"tibjmsnaming://...\"")`. What is wrong with this statement? Answer: As per S.Lott's suggestion, here is how I would solve this issue. I might be simplifying a little bit. If so, I apologize, but I haven't seen your data. import csv my_dict = {} with open('my/data.csv') as f: my_reader = csv.reader(f) for row in my_reader: my_dict[row[0]] = row[2] As you can see, there are a number of differences from your code here. First of all, I'm using Python's [`with` statement](http://effbot.org/zone/python- with-statement.htm), which is a good habit to get into when working with files. Second, I'm using python's [`csv`](http://docs.python.org/library/csv.html) module to create a reader object, which you can iterate over in a `for` loop. This is significantly more pythonic than using a `while` loop. Finally, and probably most relevantly, I'm adding these values to a dictionary, rather than trying to plop them into variables in the global scope. To access these parameters, you can simply do the following: my_dict['externalProviderURL'] However, you get a lot more than this. Storing your values in an actual data structure will allow you use all of it's [built in methods](http://docs.python.org/library/stdtypes.html#mapping-types-dict). For example, you can go back and iterate over it's keys and values for key, value in my_dict.iteritems(): print key print value Pythonic code often involves a significant use of dictionaries. They're finely tuned for performance, and are made particularly useful since most anything can be stored as a value in the dictionary (lists, other dictionaries, functions, classes etc.)
modifying familyName and givenName Question: I'm having an issue renaming a user account's familyName and givenName. I'm using the GData API for Python. After running the program no errors are shown. When I print the entryObject it does not show any difference from the original. What am I doing wrong? Thank you! import gdata.apps.service /* email, domain and password are specified here */ service = gdata.apps.service.AppsService(email=email, domain=domain, password=password) service.ProgrammaticLogin() entryObject = service.RetrieveUser('userAccount') entryObject.name.familyName = 'lastName' entryObject.name.givenName = 'firstName' Answer: It turns out I was doing things very wrong. I needed to get a different type of UserEntry object. Two relevant links are [UserEntry](http://gdata-python- client.googlecode.com/hg/pydocs/gdata.apps.multidomain.data.html#UserEntry) and [retrieve_user](http://gdata-python- client.googlecode.com/hg/pydocs/gdata.apps.multidomain.client.html#MultiDomainProvisioningClient- retrieve_user). These are all done in the gdata.apps.multidomain.client module. import gdata.apps.multidomain.client email='[email protected]' password='mypassword' domain='domain.com' multiDomainClient = gdata.apps.multidomain.client.MultiDomainProvisioningClient(domain=domain) multiDomainClient.ClientLogin(email=email, password=password, service='apps', source='mgmt') entryObject = multiDomainClient.retrieve_user('[email protected]') entryObject.SetFirstName('First_Name') entryObject.SetLastName('Last_Name') multiDomainClient.update_user('[email protected]', entryObject)
Sorting a Python list by third element, then by first element, etc? Question: Say I have a list in the form [[x,y,z], [x,y,z] etc...] etc where each grouping represents a random point. I want to order my points by the z coordinate, then within each grouping of z's, sort them by x coordinate. Is this possible? Answer: Sure, look at [this page](http://wiki.python.org/moin/HowTo/Sorting) under the section called "Operator Module Functions." Basically you just need to use sort's key feature with the itemgetter operator... from operator import itemgetter sorted(tuples, key=itemgetter(2,0))
Get recarray attributes/columns python Question: I'm trying to retrieve the column titles of a recarray, and running into considerable trouble. If I read in a .csv file using pylab's csv2rec function, I am able to access column titles in the following manner: from pylab import csv2rec x = csv2rec(file.csv) x.column1 x.column2 Where 'column1' is the title of the first column, and it would return the rest of the values in the column. But, I am reading in a .csv file where I don't know what all of the values of the column titles are, and I want to be able to access them (either loop through, or set a list). This seems like it should be simple. Any ideas? Answer: You can use `x.dtype.names`: >>> import numpy as np >>> a = np.array([0.1,0.2]) >>> b = np.array([0.3,0.4]) >>> dtype = {'names' : ['a','b'], 'formats' : ['f8', 'f8']} >>> c = np.rec.fromarrays([a,b], dtype = dtype) >>> c rec.array([(0.1, 0.3), (0.2, 0.4)], dtype=[('a', '<f8'), ('b', '<f8')]) >>> print c.dtype.names ('a', 'b') Or, using your example: [physics@aurora ~/calc ]$ cat csv.dat a,b 0.1,0.3 0.2,0.4 In [1]: from pylab import csv2rec In [2]: x = csv2rec('csv.dat') In [3]: for name in x.dtype.names: ...: print name a b
What are the downsides to defining a C macro that works like the Python "with" statement? Question: After playing around a bit with C preprocessors, I thought of a way to have something similar to a Pythonian with control structure, defined like this: #define with(var) for(int i##__LINE__=0;i##__LINE__<1;)for(var;i##__LINE__<1;++i##__LINE__) Sample usage: #include <cstdio> #include "FileClass.hpp" #include "with.hpp" int main(){ with(FileClass file("test.txt")){ printf("%s\n",file.readlines().c_str());} return 0;} The idea is that a doubly-nested for loop has an outer obfuscated iteration variable which is incremented once in the inner loop to break it. This causes the following code to be executed once with var in its scope. Are there any downsides to this? If I obfuscate the iteration variable enough, there would be almost no chance of having a name clash, it uses only standard preprocessor features in a way that doesn't seem to have any possibility of backfiring, and it's very easy to understand. It almost seems too good to be true - is there any reason this isn't used everywhere? Answer: > is there any reason this isn't used everywhere? Yes, C++ is not Python, and if I understood your code correctly, this does exactly the same: { FileClass file("test.txt"); printf("%s\n", file.readlines().c_str()); } So, what are the downsides? Unnatural syntax, usage of the preprocessor for code obfuscation, achieving the same thing as above with much more boilerplate code, and unidiomatic use of C++. Enough? C++ has the _very_ important concept of _value types_ and scope-based deterministic destruction of stack variables. This leads to _very_ important idioms like SBRM (scope-bound resource management, also called RAII).
Searching and writing Question: I need to write a program which looks for words with the same three middle characters(each word is 5 characters long) in a list, then writes them into a file like this : wasdy casde tasdf gsadk csade hsadi Between the similar words i need to leave an empty line. I am kinda stuck. Is there a way to do this? I use Python 3.2 . Thanks for your help. Answer: I would use the [`itertools.groupby`](http://docs.python.org/library/itertools.html#itertools.groupby) function for this. Assuming `wordlist` is a list of the words you want to group, this code does the trick. import itertools for k, v in itertools.groupby(wordlist, lambda word: word[1:4]): # here, k is the key the words are grouped by, i.e. word[1:4] # and v is a list/iterable of the words in the group for word in v: print word print `itertools.groupby(wordlist, lambda word: word[1:4])` basically takes all the words, and groups them by `word[1:4]`, i.e. the three middle characters. Here's the output of the above code with your sample data: wasdy casde tasdf gsadk csade hsadi  
OpenGL ES source files Question: I am trying to build the OpenGL SO lib from android sources (libGLESv2.so) and i would like a little bit more understanding of the internal mechanism of Android OpenGL ES and the flow. Please correct me where i am wrong: I know that in windows a developer includes gl.h and static link to OpenGL32(64).lib (which in turn dynamically link to OpenGL32.dll (probably there is a way to dynamic linke to OpenGL32.dll by the developer but that's not important). The developer is exposed to the declaration of OpenGL API's but the implementation which i assume to be HW dependent. The same scenario, Android: assuming developer import .opengl.GLES20 and calls the following method: GLES20.glTexEnvf(.... I would like to know what's going on behind the scenes in android (maybe Linux is better for an Android beginner). the implementation which reside in opengl/java/android/opengl/GLES20.java source calls the native C function glTexEnvf which unlike windows we have it's implementation which reside in opengl/libagl. Is it true? In any case what is the GLES2_dbg library in /libs/GLES20_dbg? i can see there some kind of debug implementation with python scripts... are they to compile OpenGL debug version? What are the .in files and gl2.cpp file in /libs/GLES20? Where are the HW calls? does each GPU vendor sends his libGLESv2 implementation for HW calls as i saw the libGLESv2_adreno200.so in my xperia arc? Please help me understand the flow. If you have a link which explain this structure even in Linux it will be great. Answer: In Windows opengl32.dll contains both a software rasterizer fallback and so called trampolines into the OpenGL-ICD shipping with the GPU driver. The opengl32.lib ist not really a library but a cross reference for the linker to add entries into the executable that make the OS dynamically link the program against the DLL at runtime. On Linux in the current implementation the libGL.so ships with the graphics driver and contains the vendor specific implementations. The linkers used in *nix systems don't rely on an extra crossreferencing .lib but can take the information directly from the .so On Android the libGLES you see is only a kind of placeholder to make linking possible. But ultimately the GPU vendor provides the proper library, which drops into the place where the phony libGLES resided. The .in files are nothing special in particular. They are input files used by configure and build systems to build source files from a template (the .in file) with fields filled in by configuration values.
Why does "pip install" raise a SyntaxError? Question: I'm trying to use pip to install a package. I try to run `pip install` from the Python shell, but I get a `SyntaxError`. Why do I get this error? How do I use pip to install the package? >>> pip install selenium ^ SyntaxError: invalid syntax Answer: pip is run from the command line, not the Python interpreter. It is a program that **installs** modules, so you can use them from Python. Once you have installed the module, then you can open the Python shell and do `import selenium`. The Python shell is not a command line, it is an interactive interpreter. You type Python code into it, not commands.
Compare List Similarity Python Question: S = ['hom'] L = ['home','honda','Hammer','Elephant'] I want to get output to show similarity hom = home and print home How I can do this? I want to use approximate matching to change "hom" to "home". Answer: For something built-in, you have [difflib](http://docs.python.org/library/difflib.html). It can (as said in the docs): Return a list of the best “good enough” matches. word is a sequence for which close matches are desired (typically a string), and possibilities is a list of sequences against which to match word (typically a list of strings). The example in the docs is: >>> from difflib import get_close_matches >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']) ['apple', 'ape']
payload of an email in string format, python Question: I got payload as a string instance using `get_payload()` method. But I want my payload in a way where I could access it word by word I tried several things like `as_string() method, flatten() method, get_charset() method` , but every time there is some problem. I got my payload using the following code import email from email import * f=open('mail.txt','r') obj=email.parser.Parser() fp=obj.parse(f) payload=fp.get_payload() Answer: Just tested your snippet with a couple of my own raw emails. Works fine... get_payload() returns either a list or string, so you need to check that first if isinstance(payload, list): for m in payload: print str(m).split() else: print str(m).split() **Edit** Per our discussion, your issue was that you were not checking is_multipart() on the fp object, which actually is a message instance. If fp.is_multipart() == True, then get_payload() will return a list of message instances. In your case, based on your example mail message, it was NOT multipart, and fp was actually the object you were interesting in.
Python callback working with functions but not methods Question: I have a third-party Python library that allows me to register a callback function that it called later. While the code works okay with functions, when I tried to pass a method it fails, the callback is never called. I have no control over the third party library (source code not available).   def old_callbackFunction(param, data): print data class MyClass(): def callbackFunction(self, param, data): print data myObj = MyClass() # old_setCallback(myObj.callbackFunction, param = "x") # this would work setCallback(myObj.callbackFunction, param = "x") # this is never called Answer: Sorin actually figured this out himself, with help from my comment, but he indicated that he wanted me to post the original comment as an answer. I was reluctant to post this originally because I'm unsure of the precise behavior of the setCallback and callbackFunction code; use at your own risk and modify as reason dictates. The best way to wrap a function is to use `functools.partial`: from functools import partial setCallback(partial(myObj.callbackFunction), param="x") You may also use a `lambda` (but you'll lose style points with the pythonistas): setCallback(lambda param, data: myObj.callbackFunction(param, data), param="x")
Python - Append to CSV Question: I am trying to append to a CSV file with the following code import csv cat_options = [row for row in csv.reader(open('catOptions.csv', 'r'), delimiter =',')] print cat_options new_cat = raw_input("\nEnter the new category: ") cat_options = csv.writer(open('catOptions.csv', 'a')) cat_options = cat_options.writerows(new_cat) Following is the output: "Housing" "Transportation" S a v i n g s The file "catOptions.csv" has Housing and Transportation. I tried to append Savings and did not get the desired result. Each word appears on a separate line. However the following code gives me the desired result but i am curious to know if there is an efficient way to do this. import csv cat_options = [row for row in csv.reader(open('catOptions.csv', 'r'), delimiter =',')] print cat_options new_cat = [] new_cat.append(raw_input("\nEnter the new category: ")) cat_options = csv.writer(open('catOptions.csv', 'a')) cat_options = cat_options.writerows([new_cat]) Thanks in advance! Answer: Use [`csvwriter.writerow()`](http://docs.python.org/library/csv.html#csv.csvwriter.writerow) if you only want to write a single row.
Converting IBM DB2 IXF file to CSV or XML Question: How do I convert an exported IXF file (using `db2 export`) to a human-readable format, like CSV or XML? I am comfortable with doing it in Python or .NET C#. Answer: The PC/IXF format is fairly complex, and is practically unknown to programs outside of DB2. Writing your own PC/IXF parser just to convert an IXF file directly to some other format might take a while. A faster alternative is to issue an IMPORT command on the DB2 server and specify CREATE INTO instead of INSERT INTO , which will generate a brand new table that can accommodate the contents of the file being imported. This will allow you to run an EXPORT command on the new table to dump the rows to a delimited format.
Python : Display a Dict of Dicts using a UI Tree for the keys and any other widget for the values Question: I have three dicts, one providing a list of all the available options, and two providing a subset of choices (one set for defaults and one for user choices). I get the three dicts using python's built in JSON parser. I want display, in a UI, a tree on the left that is based on the keys in the dicts, on the right I would like to display either a combobox, a button, a listbox or some other appropriate widget to manipulate the data for that key. I need the tree since I'm really working with a dict of dicts and I want to allow folding. So far I have looked into tkinter, tkinter's ttk and tix libraries and they allow trees but don't allow configurable lists on the right it seems. I've also seen some examples where the tree is borrowed from python's IDLE. 1. Is there a GUI toolkit that provides such functionality or is there no such thing and I have to design my own ? 2. If I have to design my own is there any GUI toolkit that you would recommend over tk ? 3. Is there a basic tutorial on GUI design for the recommended toolkit if it doens't provide this kind of thing ? I'd prefer it if the GUI toolkit was cross platform compatible (*nix and win) and free to distribute if possible. Out of interest is there a tutorial on creating custom widgets with tk, I have tried looking but I keep getting directed to tk's widget use instead of widget design :s As a minimal example I've dropped the extra dicts for now and have the following : import json import tkinter as tk from tkinter import ttk from pprint import pprint as pprint def JSONTree(Tree, Parent, Dictionery, TagList = []): for key in Dictionery : if isinstance(Dictionery[key],dict): Tree.insert(Parent, 'end', key, text = key) TagList.append(key) JSONTree(Tree, key, Dictionery[key], TagList) pprint(TagList) elif isinstance(Dictionery[key],list): Tree.insert(Parent, 'end', key, text = key) # Still working on this else : Tree.insert(Parent, 'end', key, text = key, value = Dictionery[key]) if __name__ == "__main__" : # Setup the root UI root = tk.Tk() root.title("JSON editor") root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) # Setup Data Data = {"firstName": "John", "lastName": "Smith", "gender": "man", "age": 32, "address": {"streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021"}, "phoneNumbers": [{ "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" }]} # Setup the Frames TreeFrame = ttk.Frame(root, padding = "3") TreeFrame.grid(row = 0, column = 0, sticky = tk.NSEW) # Setup the Tree tree = ttk.Treeview(TreeFrame, columns = ('Values')) tree.column('Values', width = 100, anchor = 'center') tree.heading('Values', text = 'Values') JSONTree(tree, '', Data) tree.pack(fill=tk.BOTH, expand = 1) # Limit windows minimum dimensions root.update_idletasks() root.minsize(root.winfo_reqwidth(),root.winfo_reqheight()) root.mainloop() Answer: OK, so it's not really pretty, nor would I feel very good about putting code like this into production, but it does work. To make it more sane and production quality, I'd probably make JSONTree a class with all this code wrapped up into methods. This would allow some simplification and cleanup of the code and a little less passing around of objects to event handlers. import json import tkinter as tk from tkinter import ttk from pprint import pprint as pprint # opt_name: (from_, to, increment) IntOptions = { 'age': (1.0, 200.0, 1.0), } def close_ed(parent, edwin): parent.focus_set() edwin.destroy() def set_cell(edwin, w, tvar): value = tvar.get() w.item(w.focus(), values=(value,)) close_ed(w, edwin) def edit_cell(e): w = e.widget if w and len(w.item(w.focus(), 'values')) > 0: edwin = tk.Toplevel(e.widget) edwin.protocol("WM_DELETE_WINDOW", lambda: close_ed(w, edwin)) edwin.grab_set() edwin.overrideredirect(1) opt_name = w.focus() (x, y, width, height) = w.bbox(opt_name, 'Values') edwin.geometry('%dx%d+%d+%d' % (width, height, w.winfo_rootx() + x, w.winfo_rooty() + y)) value = w.item(opt_name, 'values')[0] tvar = tk.StringVar() tvar.set(str(value)) ed = None if opt_name in IntOptions: constraints = IntOptions[opt_name] ed = tk.Spinbox(edwin, from_=constraints[0], to=constraints[1], increment=constraints[2], textvariable=tvar) else: ed = tk.Entry(edwin, textvariable=tvar) if ed: ed.config(background='LightYellow') #ed.grid(column=0, row=0, sticky=(tk.N, tk.S, tk.W, tk.E)) ed.pack() ed.focus_set() edwin.bind('<Return>', lambda e: set_cell(edwin, w, tvar)) edwin.bind('<Escape>', lambda e: close_ed(w, edwin)) def JSONTree(Tree, Parent, Dictionery, TagList=[]): for key in Dictionery : if isinstance(Dictionery[key], dict): Tree.insert(Parent, 'end', key, text=key) TagList.append(key) JSONTree(Tree, key, Dictionery[key], TagList) pprint(TagList) elif isinstance(Dictionery[key], list): Tree.insert(Parent, 'end', key, text=key) # Still working on this else: Tree.insert(Parent, 'end', key, text=key, value=Dictionery[key]) if __name__ == "__main__" : # Setup the root UI root = tk.Tk() root.title("JSON editor") root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) # Setup Data Data = { "firstName": "John", "lastName": "Smith", "gender": "man", "age": 32, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021"}, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" }, ]} # Setup the Frames TreeFrame = ttk.Frame(root, padding="3") TreeFrame.grid(row=0, column=0, sticky=tk.NSEW) # Setup the Tree tree = ttk.Treeview(TreeFrame, columns=('Values')) tree.column('Values', width=100, anchor='center') tree.heading('Values', text='Values') tree.bind('<Double-1>', edit_cell) tree.bind('<Return>', edit_cell) JSONTree(tree, '', Data) tree.pack(fill=tk.BOTH, expand=1) # Limit windows minimum dimensions root.update_idletasks() root.minsize(root.winfo_reqwidth(), root.winfo_reqheight()) root.mainloop()
how to run python script from shell Question: I have a noob question. I got a python script path1/path2/file.py The script has a function: def run (datetime = None): In the shell I call import path1.path2.file import datetime path1.path2.file.run(datetime = datetime(2011,12,1)) but I am getting TypeError: 'module' object is not callable whats the correct way to call the method in the shell? Answer: The problem is actually in the datetime module. You are trying to call the module itself. The function you want to call is itself called datetime. so what you want to call is: datetime.datetime() OR you can import the function with: from datetime import datetime and then call it with: datetime()
Python subprocess call with arguments having multiple quotations Question: I use the following command in bash to execute a Python script. python myfile.py -c "'USA'" -g "'CA'" -0 "'2011-10-13'" -1 "'2011-10-27'" I'm writing a Python script to wrap around this one. I'm currently having to use os.system (I know, it's crappy) since I can't figure out how to get the quotes to work with subprocess.Popen. The inner single quotes must be maintained in the string variables that are passed in. Can someone please help me determine how to format the first variable passed to subprocess.Popen. Answer: You don't need to escape the values. To the process everything is passed as a string. You can use the shlex module to figure out what is the best way to pass variables: import shlex shlex.split('python myfile.py -c "USA" -g "CA" -0 "2011-10-13" -1 "2011-10-27"') ['python', 'myfile.py', '-c', 'USA', '-g', 'CA', '-0', '2011-10-13', '-1', '2011-10-27']
Sending JSON using the django test client Question: I'm working on a django a project that will serve as the endpoint for a webhook. The webhook will POST some JSON data to my endpoint, which will then parse that data. I'm trying to write unit tests for it, but I'm not sure if I'm sending the JSON properly. I keep getting "TypeError: string indices must be integers" in pipeline_endpoint Here's the code: # tests.py from django.test import TestCase from django.test.client import Client import simplejson class TestPipeline(TestCase): def setUp(self): """initialize the Django test client""" self.c = Client() def test_200(self): json_string = u'{"1": {"guid": "8a40135230f21bdb0130f21c255c0007", "portalId": 999, "email": "fake@email"}}' json_data = simplejson.loads(json_string) self.response = self.c.post('/pipeline-endpoint', json_data, content_type="application/json") self.assertEqual(self.response.status_code, "200") and # views.py from pipeline.prospect import Prospect import simplejson def pipeline_endpoint(request): #get the data from the json object that came in prospects_json = simplejson.loads(request.raw_post_data) for p in prospects_json: prospect = { 'email' : p['email'], 'hs_id' : p['guid'], 'portal' : p['portalId'], } Edit: whole traceback. ====================================================================== ERROR: test_200 (pipeline.tests.TestPipeline) ---------------------------------------------------------------------- Traceback (most recent call last): File "F:\......\pipeline\tests.py", line 31, in test_200 self.response = self.c.post('/pipeline-endpoint', json_string, content_type="application/json") File "C:\Python27\lib\site-packages\django\test\client.py", line 455, in post response = super(Client, self).post(path, data=data, content_type=content_type, **extra) File "C:\Python27\lib\site-packages\django\test\client.py", line 256, in post return self.request(**r) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 111, in get_response response = callback(request, *callback_args, **callback_kwargs) File "F:\......\pipeline\views.py", line 18, in pipeline_endpoint 'email' : p['email'], TypeError: string indices must be integers ---------------------------------------------------------------------- Ran 1 test in 0.095s FAILED (errors=1) Destroying test database for alias 'default'... Answer: @mrmagooey is right def test_your_test(self): python_dict = { "1": { "guid": "8a40135230f21bdb0130f21c255c0007", "portalId": 999, "email": "fake@email" } } response = self.client.post('/pipeline-endpoint/', json.dumps(python_dict), content_type="application/json") use `json.dumps` instead of `json.loads`
How to receive/get C struct from Python Question: I have a standalone Python module used to perform analysis on some raw data. The module is working great. Now I need the output generated by the Python module in C source that will do further processing on output. Here is the rough idea of flow: 1. C source will call the Python module. 2. Python module will fill the results generated into a C structure and then somehow pass it to C source. So what is the best way to get the results from Python module in C source code? Should I use something like the following to fill the results? from ctypes import * class result(Structure): _fields_ = [("status", c_int), ...] Answer: I don't think you'll want to use the ctypes module — that module is for accessing DLLs and shared objects _from_ Python code, not the other way around. You don't specify how the C program is going to invoke the Python module. Will it * invoke the Python script using something like `popen` from C? If so, then you can write data to `stdout` in Python and interpret the data appropriately in C. You'll have to design your own little protocol for this. This can be an ad-hoc protocol, or you can use existing formats like JSON, for which you'll find libraries for both C and Python. * [embed the Python VM in your C program?](http://docs.python.org/extending/embedding.html) Then you'll need to convert the C values into appropriate `Py*` values and put them into a `PyTuple` that you can pass as an argument to the Python function, from C. The output of the Python function will be a [`PyObject`](http://docs.python.org/c-api/structures.html#PyObject), which you'll have to unpack (in C) to get the data. In both cases, you'll need to do the packing and unpacking yourself.
Writing complex custom metadata on images through python Question: I'm looking to write custom metadata on to images(mostly jpegs, but could be others too). So far I haven't been able to do that through PIL preferably (I'm on centos 5 & I couldn't get pyexiv installed) I understand that I can update some pre-defined tags, but I need to create custom fields/tags! Can that be done? This data would be created by users, so I wouldn't know what those tags are before hand or what they contain. I need to allow them to create tags/subtags & then write data for them. For example, someone may want to create this metadata on a particular image : Category : Human Physical : skin_type : smooth complexion : fair eye_color: blue beard: yes beard_color: brown age: mid Location : city: london terrain: grass buildings: old I also found that upon saving a jpeg through the PIL JpegImagePlugin, all previous metadata is overwritten with new data that you don't get to edit? Is that a bug? Cheers, S Answer: The python [pyexiv2 module](http://tilloy.net/dev/pyexiv2/api.html) can read/write metadata. I think there is a limited set of valid EXIF tags. I don't know how, or if it is possible to create your own custom tags. However, you could use the Exif.Photo.UserComment tag, and fill it with JSON: import pyexiv2 import json metadata = pyexiv2.ImageMetadata(filename) metadata.read() userdata={'Category':'Human', 'Physical': { 'skin_type':'smooth', 'complexion':'fair' }, 'Location': { 'city': 'london' } } metadata['Exif.Photo.UserComment']=json.dumps(userdata) metadata.write() And to read it back: import pprint filename='/tmp/image.jpg' metadata = pyexiv2.ImageMetadata(filename) metadata.read() userdata=json.loads(metadata['Exif.Photo.UserComment'].value) pprint.pprint(userdata) yields {u'Category': u'Human', u'Location': {u'city': u'london'}, u'Physical': {u'complexion': u'fair', u'skin_type': u'smooth'}}
How to do POS tagging using the NLTK POS tagger in Python? Question: I just started using a part-of-speech tagger, and I am facing many problems. I started POS tagging with the following: import nltk text=nltk.word_tokenize("We are going out.Just you and me.") When I want to print `'text'`, the following happens: print nltk.pos_tag(text) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "F:\Python26\lib\site-packages\nltk\tag\__init__.py", line 63, in pos_tag tagger = nltk.data.load(_POS_TAGGER) File "F:\Python26\lib\site-packages\nltk\data.py", line 594, in load resource_val = pickle.load(_open(resource_url)) File "F:\Python26\lib\site-packages\nltk\data.py", line 673, in _open return find(path).open() File "F:\Python26\lib\site-packages\nltk\data.py", line 455, in find raise LookupError(resource_not_found)` LookupError: Resource 'taggers/maxent_treebank_pos_tagger/english.pickle' not found. Please use the NLTK Downloader to obtain the resource: >>> nltk.download(). Searched in: - 'C:\\Documents and Settings\\Administrator/nltk_data' - 'C:\\nltk_data' - 'D:\\nltk_data' - 'E:\\nltk_data' - 'F:\\Python26\\nltk_data' - 'F:\\Python26\\lib\\nltk_data' - 'C:\\Documents and Settings\\Administrator\\Application Data\\nltk_data' I used `nltk.download()` but it did not work. Answer: When you type `nltk.download()` in Python, an NLTK Downloader interface gets displayed automatically. Click on Models and choose maxent_treebank_pos_. It gets installed automatically. import nltk text=nltk.word_tokenize("We are going out.Just you and me.") print nltk.pos_tag(text) [('We', 'PRP'), ('are', 'VBP'), ('going', 'VBG'), ('out.Just', 'JJ'), ('you', 'PRP'), ('and', 'CC'), ('me', 'PRP'), ('.', '.')]
How to fill a textArea in an online form automatically using Python? Question: I am wondering how I can fill an online form automatically. I have researched it and it tuned out that, one can uses Python ( I am more interested to know how to do it with Python because it is a scripting language I know) but documentation about it is not very good. This is what I found: [Fill form values in a web page via a Python script (not testing)](http://stackoverflow.com/questions/1555234/fill-form-values-in-a- web-page-via-a-python-script-not-testing) Even the "mechanize" package itself does not have enough documentation: <http://wwwsearch.sourceforge.net/mechanize/> More specifically, I want to fill the TextArea in this page (Addresses): <http://stevemorse.org/jcal/latlonbatch.html?direction=forward> so I don't know what I should look for? Should I look for "id" of the the textArea? ?It doesn't look like that it has "id" (or I am very naive!). How I can "select_form"? Python, web gurus, please help. Thanks Answer: See if my answer to the other question you linked helps: <http://stackoverflow.com/a/5685569/711017> **EDIT:** Here is the explicit code for your example. Now, I don't have mechanize installed right now, so I haven't been able to check the code. No online IDE's I checked have it either. But even if it doesn't work, toy around with it, and you should eventually get there: import re from mechanize import Browser br = Browser() br.open("http://stevemorse.org/jcal/latlonbatch.html?direction=forward") br.select_form(name="display") br["locations"] = ["Hollywood and Vine, Hollywood CA"] response = br.submit() print response.read() Explanation: `br` emulates a browser that opens your url and selects the desired form. It's called _display_ in the website. The textarea to enter the address is called _locations_ , into which I fill in the address, then submit the form. Whatever the server returns is the string `response.read()`, in which you should find your Lat-Longs somewhere. Install mechanize and check it out.
How to use python NLP POS tagger in C# code? Question: I came across and successfully used a python NLP POS tagger.The problem is that my code was in c# and I used a python pos tagger because I could not find a good c# pos tagger.Now,I don't know how to use this python NLP POS tagger in my c# code.Could anyone guide me?Also please do suggest any C# POS tagger.Thankx EDIT: I thought of using IronPython for using the python NLP POS tagger.But when I use `import nltk`,I get an `ImportError:No module named nltk` The same command when used in python2.6 had worked perfectly fine. Answer: You can use the [SharpNLP](http://sharpnlp.codeplex.com/) project.
How to put device context (wx.DC) into a sizer? -wxpython Question: Hello I would like to put device context into a sizer, however when I try to do this, python returns an error. import wx class Example(wx.Frame): def __init__(self, parent, title): super(Example, self).__init__(parent, title=title, size=(250, 150)) self.sizer = wx.BoxSizer() self.Bind(wx.EVT_PAINT, self.OnPaint) button1 = wx.Button(self, id=wx.ID_ANY, label='Button',pos=(8, 38), size=(175, 28)) self.sizer.Add(button1, 1, wx.EXPAND|wx.ALL, 10) self.Centre() self.Show() def OnPaint(self, e): dc = wx.PaintDC(self) self.sizer.Add(dc, 1, wx.EXPAND|wx.ALL, 10) dc.DrawLine(50, 60, 190, 60) if __name__ == '__main__': app = wx.App() Example(None, 'Line') app.MainLoop() Thank you! Answer: The only thing you can put into a sizer is a window. A device context is not a window, so you cannot put it into a sizer. Create a window, put it into your sizer, then, when you need to draw on the window, create a device context from the window. I think that the best thing for you to do is to remove the line self.sizer.Add(dc, 1, wx.EXPAND|wx.ALL, 10) The line dc.DrawLine(50, 60, 190, 60) Will draw your line in the window that the dc belongs to ( self )
load pyd files from a zip from embedded python Question: I can load Python modules (.py, .pyc, .pyd) from a zip file by calling "import some_module" from a Python interpreter only after sys.path has been extended to include the zip file and only after I have run import zipextimporter zipextimporter.install() The latter is required for .pyd modules. I can also load Python .py and .pyc modules from Python embedded in C++. However, in order to also load .pyd modules from embedded Python I added PyRun_SimpleString("import zipextimporter"); The C++ exe runs beyond this line without error. But the next command PyRun_SimpleString("zipextimporter.install()"); gives me this error: ![enter image description here](http://i.stack.imgur.com/3iYeR.png) Why does zipextimporter.install() crash when Python is embedded? How can I solve this? Does it perhaps have to do with the way the C++ code is compiled? I use g++: `g++ embed-simple.cpp -IE:\Python27\include -LE:\Python27\libs -lpython27 -o embed-simple` I saw a link [How to link against msvcr90.dll with mingw gcc?](http://stackoverflow.com/questions/3402252/how-to-link-against- msvcr90-dll-with-mingw-gcc) Could that provide a solution? If yes, how should I adjust it, gcc-->g++, since I am running C++ code, not C. I am running Python 2.7.2 on WinXP. I don't get the runtime error after a clean install of Python 2.7.2, just this: > Import Error: No module named.... Would it matter the way the embedding C++ script is compiled? I used g++. I also compiled with the Intel compiler, but that gave the same runtime error. Perhaps I should try MS Visual C++. Or use ctypes to import the pyd? Answer: memimporter and zipextimporter are indeed able to load .pyd files from memory/zip-archives without unpacking them to files. The runtimerror R6034 is caused by the fact that the VC9 runtime library must be loaded via a manifest. Running your code in Python 2.5, whic uses a different C runtime, would most probably succeed. I guess you must embed a manifest referencing the VC9 runtime library in your exe; maybe the py2exe wiki can provide some guidance.
Get point IDs after clustering, using python Question: > **Possible Duplicate:** > [Python k-means > algorithm](http://stackoverflow.com/questions/1545606/python-k-means- > algorithm) I want to **cluster** 10000 indexed points based on their feature vectors and **get their ids** after clustering i.e. cluster1:[p1, p3, p100, ...], cluster2:[...] ... Is there any way to do this in Python? Thx~ P.s. The indexed points are stored in a 10000*10 matrix, where each row represents a feature vector. Answer: Use some clustering algorithm - I've included an implementation of the K-means algorithm that @Cameron linked to in his second comment, but you might want to refer to [the link in his first comment](http://hackmap.blogspot.com/2007/09/k-means-clustering-in- scipy.html). I'm not sure what you mean by get their ID's, could you elaborate? from math import sqrt def k_means(data_pts, k=None): """ Return k (x,y) pairs where: k = number of clusters and each (x,y) pair = centroid of cluster data_pts should be a list of (x,y) tuples, e.g., data_pts=[ (0,0), (0,5), (1,3) ] """ """ Helper functions """ def lists_are_same(la, lb): # see if two lists have the same elements out = False for item in la: if item not in lb: out = False break else: out = True return out def distance(a, b): # distance between (x,y) points a and b return sqrt(abs(a[0]-b[0])**2 + abs(a[1]-b[1])**2) def average(a): # return the average of a one-dimensional list (e.g., [1, 2, 3]) return sum(a)/float(len(a)) """ Set up some initial values """ if k is None: # if the user didn't supply a number of means to look for, try to estimate how many there are n = len(data_pts)# number of points in the dataset k = int(sqrt(n/2)) # number of clusters - see # http://en.wikipedia.org/wiki/Determining_the_number_of_clusters_in_a_data_set#Rule_of_thumb if k < 1: # make sure there's at least one cluster k = 1 """ Randomly generate k clusters and determine the cluster centers, or directly generate k random points as cluster centers. """ init_clusters = data_pts[:] # put all of the data points into clusters shuffle(init_clusters) # put the data points in random order init_clusters = init_clusters[0:k] # only keep the first k random clusters old_clusters, new_clusters = {}, {} for item in init_clusters: old_clusters[item] = [] # every cluster has a list of points associated with it. Initially, it's 0 while 1: # just keep going forever, until our break condition is met tmp = {} for k in old_clusters: # create an editable version of the old_clusters dictionary tmp[k] = [] """ Associate each point with the closest cluster center. """ for point in data_pts: # for each (x,y) data point min_clust = None min_dist = 1000000000 # absurdly large, should be larger than the maximum distance for most data sets for pc in tmp: # for every possible closest cluster pc_dist = distance(point, pc) if pc_dist < min_dist: # if this cluster is the closest, have it be the closest (duh) min_dist = pc_dist min_clust = pc tmp[min_clust].append(point) # add each point to its closest cluster's list of associated points """ Recompute the new cluster centers. """ for k in tmp: associated = tmp[k] xs = [pt[0] for pt in associated] # build up a list of x's ys = [pt[1] for pt in associated] # build up a list of y's x = average(xs) # x coordinate of new cluster y = average(ys) # y coordinate of new cluster new_clusters[(x,y)] = associated # these are the points the center was built off of, they're *probably* still associated if lists_are_same(old_clusters.keys(), new_clusters.keys()): # if we've reached equilibrium, return the points return old_clusters.keys() else: # otherwise, we'll go another round. let old_clusters = new_clusters, and clear new_clusters. old_clusters = new_clusters new_clusters = {}
How to tell what python version libboost_python.so is using? Question: I'd like to know what version of python boost_python.so is expecting. This is on a computer with multiple python versions and I did not build/install boost myself (nor do i have root access). How can i tell what version of python boost_python.so is compiled for? I didn't find anything useful in the output from ldd but include it here incase someone else sees something. -bash-3.2$ ldd -v libboost_python.so.1.46.1 libutil.so.1 => /lib64/libutil.so.1 (0x00002ad65582d000) libpthread.so.0 => /lib64/libpthread.so.0 (0x00002ad655a30000) libdl.so.2 => /lib64/libdl.so.2 (0x00002ad655c4b000) librt.so.1 => /lib64/librt.so.1 (0x00002ad655e50000) libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x00002ad656059000) libm.so.6 => /lib64/libm.so.6 (0x00002ad656359000) libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00002ad6565dd000) libc.so.6 => /lib64/libc.so.6 (0x00002ad6567eb000) /lib64/ld-linux-x86-64.so.2 (0x000000374c600000) Version information: ./libboost_python.so.1.46.1: libgcc_s.so.1 (GCC_3.0) => /lib64/libgcc_s.so.1 libpthread.so.0 (GLIBC_2.2.5) => /lib64/libpthread.so.0 libc.so.6 (GLIBC_2.4) => /lib64/libc.so.6 libc.so.6 (GLIBC_2.2.5) => /lib64/libc.so.6 libstdc++.so.6 (CXXABI_1.3) => /usr/lib64/libstdc++.so.6 libstdc++.so.6 (GLIBCXX_3.4) => /usr/lib64/libstdc++.so.6 /lib64/libutil.so.1: libc.so.6 (GLIBC_2.2.5) => /lib64/libc.so.6 /lib64/libpthread.so.0: ld-linux-x86-64.so.2 (GLIBC_2.3) => /lib64/ld-linux-x86-64.so.2 ld-linux-x86-64.so.2 (GLIBC_2.2.5) => /lib64/ld-linux-x86-64.so.2 ld-linux-x86-64.so.2 (GLIBC_PRIVATE) => /lib64/ld-linux-x86-64.so.2 libc.so.6 (GLIBC_2.3.2) => /lib64/libc.so.6 libc.so.6 (GLIBC_PRIVATE) => /lib64/libc.so.6 libc.so.6 (GLIBC_2.2.5) => /lib64/libc.so.6 /lib64/libdl.so.2: ld-linux-x86-64.so.2 (GLIBC_PRIVATE) => /lib64/ld-linux-x86-64.so.2 libc.so.6 (GLIBC_PRIVATE) => /lib64/libc.so.6 libc.so.6 (GLIBC_2.2.5) => /lib64/libc.so.6 /lib64/librt.so.1: ld-linux-x86-64.so.2 (GLIBC_PRIVATE) => /lib64/ld-linux-x86-64.so.2 libpthread.so.0 (GLIBC_2.2.5) => /lib64/libpthread.so.0 libpthread.so.0 (GLIBC_PRIVATE) => /lib64/libpthread.so.0 libc.so.6 (GLIBC_2.3.2) => /lib64/libc.so.6 libc.so.6 (GLIBC_2.2.5) => /lib64/libc.so.6 libc.so.6 (GLIBC_PRIVATE) => /lib64/libc.so.6 /usr/lib64/libstdc++.so.6: ld-linux-x86-64.so.2 (GLIBC_2.3) => /lib64/ld-linux-x86-64.so.2 libgcc_s.so.1 (GCC_4.2.0) => /lib64/libgcc_s.so.1 libgcc_s.so.1 (GCC_3.3) => /lib64/libgcc_s.so.1 libgcc_s.so.1 (GCC_3.0) => /lib64/libgcc_s.so.1 libc.so.6 (GLIBC_2.3.2) => /lib64/libc.so.6 libc.so.6 (GLIBC_2.4) => /lib64/libc.so.6 libc.so.6 (GLIBC_2.3) => /lib64/libc.so.6 libc.so.6 (GLIBC_2.2.5) => /lib64/libc.so.6 /lib64/libm.so.6: libc.so.6 (GLIBC_2.2.5) => /lib64/libc.so.6 /lib64/libgcc_s.so.1: libc.so.6 (GLIBC_2.4) => /lib64/libc.so.6 libc.so.6 (GLIBC_2.2.5) => /lib64/libc.so.6 /lib64/libc.so.6: ld-linux-x86-64.so.2 (GLIBC_2.3) => /lib64/ld-linux-x86-64.so.2 ld-linux-x86-64.so.2 (GLIBC_PRIVATE) => /lib64/ld-linux-x86-64.so.2 Answer: From: <https://github.com/mapnik/mapnik/wiki/InstallationTroubleshooting> "And sometimes even that does not work. HINT: pass the -d2 flag to see all the compile commands sent to gcc by bjam and you will likely see something like -I/usr/include/python24 in the compile arguments when it should be -I/usr/include/python26 (or some older version of python headers). If this happens then you can craft a full config file (with all possible python info) and pass a reference to that on the bjam command line. Docs on this are here: <http://www.boost.org/doc/libs/1_42_0/libs/python/doc/building.html#configuring- boost-build>, and an example follows: Create a file called 'user-config.jam' (but change the python versions to be appropriate): import option ; import feature ; if ! gcc in [ feature.values <toolset> ] { using gcc ; } project : default-build <toolset>gcc ; using python : 2.5 # version : /usr/bin/python2.5 # cmd-or-prefix : /usr/include/python2.5/ # includes : /usr/lib/python2.5/config/ # a lib actually symlink : <toolset>gcc # condition ; libraries = --with-python ; " Look for a .jam config file. If it exists check for the 'using python' command. If it doesn't exist, run the -d2 flag against bjam to determine the default location of python that it uses. This obviously isn't a direct method and would simply leave you with a likely answer given the inputs (but maybe that's good enough).
Using matplotlib: ImportError: No module named animation? Question: I've tried using the EPD installation on Mac OS X, the apt-get install process on Ubuntu, and the EPD installation on Ubuntu. In the python interactive interpretor: >>> import matplotlib.animation as animation Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named animation That import is used in this matplotlib example code: <http://matplotlib.sourceforge.net/examples/animation/double_pendulum_animated.html> Answer: FWIW, you should be able to update to matplotlib 1.1.0 or 1.2.0 using `enpkg matplotlib [version]`. <https://support.enthought.com/entries/22415022-Using-enpkg-to-update-EPD- packages>
How to pass value to a function Question: I am new to python and doing this homework. I need to create a small program with menu. I was very good 'til now. I am a little bit lost. How can I pass a value to the function? Can you please check if there are any other faults in my code. import turtle as t def how_many(): while True: print " How many of then do you want to draw?" print " (Range is from 1 to 5)" shape_no = raw_input(' Enter your choice: ') try: shape_no = int(shape_no) if (1 <= shape_no <= 5): print "Your number is ok" break else: print print "from 1 to 5 only" except: print "Only numbers allowed - Please try again" return True #=========#=========#=========#=========#=========#=========#=========# def draw_square(): t.penup() t.setpos(-200,0) t.pendown() Number_of = 5 for a in range(Number_of): for a in range(4): t.forward(60) t.left(90) t.penup() t.forward(80) t.pendown() #=========#=========#=========#=========#=========#=========#=========# def main(): while True: print print " Draw a Shape" print " ============" print print " 1 - Draw a square" print print " X - Exit" print choice = raw_input(' Enter your choice: ') if (choice == 'x') or (choice == 'X'): break elif choice == '1': how_many() draw_square() else: print 'Try again' #=========#=========#=========#=========#=========#=========#=========# if __name__ == "__main__": main() #=========#=========#=========#=========#=========#=========#=========# Answer: For how to define and call functions, see the [Python tutorial](http://docs.python.org/tutorial/controlflow.html#defining- functions). For code review, try <http://codereview.stackexchange.com/>
Using Voice instead of 'raw_input' in python for Mac OS X Question: I'm in the process of making a Python-based personal assistant/question answerer, which, in my wildest dreams, will rival the inevitable "Siri For Mac". However, as of now, it requires you type text into an infinite loop of raw_inputs, and processes the text each time. But if this is ever to be useful to, well, people, it can't be a .py in a terminal window. As of now, I'm thinking about making it a simple .app with Platypus. But, since there is no text input on the Window app style for Platypus, I would include no GUI, and just have it all be speech-based, for input and output. Output is simple, I can just replace all 'print' lines with 'speakString' from "macspeech". But input would be the tricky part. I can only find libraries to input speech on Windows (pyspeech is EXACTLY what I need, but it's windows-based). Anyone heard of something like pyspeech for mac/universal? Answer: I would look at [Sphinx4.0 from CMU](http://cmusphinx.sourceforge.net/sphinx4/). Sadly, it is written in Java. I think the recognition is better than what is built into my mac. I am just learning java/python so am struggling with getting the two to talk to each other. You can interface with the mac speech engine using `Appkit.NSSpeechRecognizer`: from Foundation import * The final method is to use the google voice search. But that requires shipping a voice snippet to the "cloud". That approach is the most accurate but takes up to 10 seconds for a reply!
Initializing a static variable in Python Question: ## Context Say, we want to use the Box-Muller algorithm. Starting from a couple of random numbers U1 and U2, we can generate G1 and G2. Now, for any call, we just want to output either G1 or G2. In other languages, we could use static variables to be able to know if we need to generate a new couple. How can it be done in Python? ## First thoughts I know, much had been said about static variables in Python, I also must say I'm a bit confused as the answers are quite scattered. I found this [thread](http://stackoverflow.com/questions/592931/why-doesnt-python-have- static-variables) and references therein. By that thread, the solution here would be to use a generator. ## The devil's in the details Now, the problem is, how do we initialize the generator and how do we retain, say G2, for the next `yield`? Answer: Writing generators is a very good practice! import random import math def BoxMullerFormula(a,b): c = math.sqrt(-2 * math.log(a)) * math.cos(2 * math.pi * b) d = math.sqrt(-2 * math.log(a)) * math.sin(2 * math.pi * b) return (c,d) def BoxM(): while 1: Rand01 = random.random() Rand02 = random.random() (a,b) = BoxMullerFormula(Rand01,Rand02) yield a yield b BoxM01 = BoxM() for i in xrange(10): print BoxM01.next() You should consider also having a class BoxMuller with a get() method, a re_initialize() one, and so on.
Python logging with multiple modules Question: I have got various modules in which I use Python logging heavily. When I import them into the main module like in the Python documentation and try to run it, I don't get any output from the logging. Has anyone got any idea what is happening? Logging is called in the module imported by the `public` module imported below (the piece of code is too large to be put up here). The piece of code below is where the whole program is run and the logging is initialized: import logging from bottle import run, debug import public logging.basicConfig(level=logging.DEBUG) if __name__ == '__main__': logging.info('Started') debug(mode=True) run(host='localhost', port = 8080, reloader=True) logging.info('Finished') Answer: Your problem is probably being caused by the `import public` statement making a call to `logging.debug(...)` or similar. What then happens is this: 1. You `import public`. As a side-effect, this calls e.g. `logging.debug` or similar, which automatically calls `basicConfig`, which adds a `StreamHandler` to the root logger, but doesn't change the level. 2. You then call `basicConfig`, but as the root logger already has a handler, it does nothing (as documented). 3. Since the default logging level is `WARNING`, your `info` and `debug` calls produce no output. You really should avoid side-effects on import: for example, your call to `basicConfig` should be in the `if __name__ == '__main__'` clause. With this `public.py`: import logging def main(): logging.debug('Hello from public') and this `main.py`: import logging from bottle import run, debug import public def main(): logging.basicConfig(level=logging.DEBUG) logging.info('Started') debug(mode=True) public.main() run(host='localhost', port = 8080, reloader=True) logging.info('Finished') if __name__ == '__main__': main() You get the following output: $ python main.py INFO:root:Started DEBUG:root:Hello from public INFO:root:Started DEBUG:root:Hello from public Bottle server starting up (using WSGIRefServer())... Listening on http://localhost:8080/ Hit Ctrl-C to quit. ^CINFO:root:Finished $ Shutdown... INFO:root:Finished You'll see from this that Bottle actually re-runs the script in a separate process, which accounts for the doubling up of messages. You can illustrate this by using a format string which shows the process ID: if you use logging.basicConfig(level=logging.DEBUG, format='%(process)s %(levelname)s %(message)s') then you get output like $ python main.py 13839 INFO Started 13839 DEBUG Hello from public 13840 INFO Started 13840 DEBUG Hello from public Bottle server starting up (using WSGIRefServer())... Listening on http://localhost:8080/ Hit Ctrl-C to quit. ^C13839 INFO Finished $ Shutdown... 13840 INFO Finished Note that if you add a side-effect producing statement to `public.py` like this: logging.debug('Side-effect from public') at the module level, then you get no logging output at all: $ python main.py Bottle server starting up (using WSGIRefServer())... Listening on http://localhost:8080/ Hit Ctrl-C to quit. ^C$ Shutdown... which appears to confirm the above analysis.
Removing cocos2d-python from Mac Question: I installed cocos2d today on OS X Lion, but whenever I try to import **cocos** in the Python interpreter, I get a bunch of import errors. > File "", line 1, in File > "/Library/Frameworks/Python.framework/Versions/2.7/lib/ python2.7/site- > packages/cocos2d-0.5.0-py2.7.egg/cocos/**init**.py", line 105, in > import_all() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/ > python2.7/site-packages/cocos2d-0.5.0-py2.7.egg/cocos/**init**.py", line 89, > in import_all import actions File > "/Library/Frameworks/Python.framework/Versions/2.7/lib/ python2.7/site- > packages/cocos2d-0.5.0-py2.7.egg/cocos/actions/ **init**.py", line 37, in > from basegrid_actions import * File > "/Library/Frameworks/Python.framework/Versions/2.7/lib/ python2.7/site- > packages/cocos2d-0.5.0-py2.7.egg/cocos/actions/ basegrid_actions.py", line > 62, in from pyglet.gl import * File > "build/bdist.macosx-10.6-intel/egg/pyglet/gl/**init**.py", line 510, in File > "build/bdist.macosx-10.6-intel/egg/pyglet/window/**init**.py", line 1669, in > File "build/bdist.macosx-10.6-intel/egg/pyglet/window/carbon/ **init**.py", > line 69, in File "build/bdist.macosx-10.6-intel/egg/pyglet/lib.py", line 90, > in load_library File "build/bdist.macosx-10.6-intel/egg/pyglet/lib.py", line > 226, in load_framework File > "/Library/Frameworks/Python.framework/Versions/2.7/lib/ > python2.7/ctypes/**init**.py", line 431, in LoadLibrary return > self._dlltype(name) File > "/Library/Frameworks/Python.framework/Versions/2.7/lib/ > python2.7/ctypes/**init**.py", line 353, in **init** self._handle = > _dlopen(self._name, mode) OSError: > dlopen(/System/Library/Frameworks/QuickTime.framework/ QuickTime, 6): no > suitable image found. Did find: > /System/Library/Frameworks/QuickTime.framework/QuickTime: mach-o, but wrong > architecture /System/Library/Frameworks/QuickTime.framework/QuickTime: > mach-o, but wrong architecture Since I can't fix it, I'd like to remove cocos2d entirely. The problem is that I can't seem to find a guide anywhere that details how to remove it from the Python installation. Any help regarding either of these problems is greatly appreciated. Answer: You could fix it. The problem comes from the fact that cocos2D is built on top of Pyglet, and the stable release of pyglet does not yet support Mac OS X 64 bits architecture. You have to use the 1.2 release of pyglet or later, which by now is not released yet. A workaround is to remove any existing Pyglet install: pip uninstall piglet Then install the latest Pyglet from the mercurial repository pip install hg+https://pyglet.googlecode.com/hg/
I clear try clearing the surface in python, then it still draws the button? Question: I clear try filling the screen with white then importing an image, but when I use display.flip() the buttons are still there and it still detects collision? How do I fix this?? def stagesel(): screen.fill(WHITE) StageselPic = image.load("Locationmenu.png") # done once screen.blit(StageselPic, Rect(0,0,800,600)) display.flip() def getmouse(): mx, my = mouse.get_pos() mb = mouse.get_pressed()[0] return (mx, my, mb) def Menu(): global GREEN global WHITE if mx >= rectx and mx <= rectx + rectw and my >= recty and my <= recty + recth: x = GREEN menutext(x) elif mx >= instx and mx <= instx + instw and my >= insty and my <= insty + insth: y = GREEN menuhelp(y) else: x = WHITE y = WHITE menutext(x) menuhelp(y) if mx >= rectx and mx <= rectx + rectw and my >= recty and my <= recty + recth and mb == True: stagesel() running = True while running: for evnt in event.get(): if evnt.type == QUIT: running = False mx,my,mb = getmouse() Menu() TITLE() quit() Answer: Your source is incomplete and bogus. This way you can't expect any help. It seems you lack understanding of the pygame surface-mechanics, but the way you represent your misundertandings it's impossible to help. My best guess would be, that you fail to copy your screen-surface to the display-surface. The part about collision detection is way above me, because you provided not even the most basic hint to your collision detection. (In the hope your Mouse-Coordinates checks don't qualify as collision detection.) Please strip your source to the relevant parts and provide pointers to problems therein.
Python, os.system fails when script not in same folder Question: I have a bat.bat file containing the following command: **'setup.py build'** I have a script that executes this bat command using: `os.system('E:/bla/FPtest/retryURL/Temp_installed/bat.bat'` If i run the script from the same folder as the bat.bat ... it works perfectly perfectly. If i run it in ANY other folder, the following error is returned. **'setup.py'** is not recognized as an internal or external command, operable program or batch file. I have also tried `subprocess.Popen` which returns the same result **BUT** it includes this at the top: `C:\Eclipse\Workspace\example>setup.py build` ... mmmmmm ... **UPDATE:** I have decided to run the os.system command in the same directory where the bat.bat file is kept (this is ALSO the directory where the setup.py is stored) the call should be so simply now. import os os.system('bat.bat') note: (run from pydev) **result:** E:\App\FPtest\retryURL\Temp_installed>setup.py build Traceback (most recent call last): File "C:\Python31\lib\site.py", line 56, in <module> import os File "C:\Python31\lib\os.py", line 380, in <module> from _abcoll import MutableMapping # Can't use collections (bootstrap) File "C:\Python31\lib\_abcoll.py", line 49 class Hashable(metaclass=ABCMeta): ^ SyntaxError: invalid syntax Additional note: If i run any 'simple' .bat file everything works fine. and if i run the .bat file outside of the interpreter it too works fine ... which leads me to believe it is the content of the .bat file that is causing the problem the content is: `setup.py build`. In this case the content of the .bat file executes an cx_freeze command to freeze and exe but the above error is what is returned when I try this **UPDATE:** It appears running the 'os.system('bat.bat')or the subprocess equivalent successfully executes the .bat file if run from the standard python interpreter. So it is only unsuccessful if run from Pydev Answer: In Windows 2000 and beyond the `.py` extension is associated with an open command that runs the interpreter. This is actually done during installation. But inorder to run the python script via the interpreter, either the script should be in the current directory or should be in one of the directories concatenated in the path environment variable. In your case if setyp.py is present in present in some and the path is absolute you can do the following path=%path%;<directory containing setup.py> On the other hand, if setup.py is at a relative directory from your batch file which is not an absolute path. You need to specify the full relative path from your current batch file location. Something like ..\<sub directory>\setyp.py #If the script is below the current path or .\<sup directory>\setyp.py #If the script is above the current path Note*** You can also run the script without an extension (Not Recommend) if `.py` is present in the PATHEXT environment variable.
Unexpected: flufl.enum prints integer value Question: Using Python 3, I unpackaged the flufl.enum code into my application source tree just to try it. Sample code: from taurine.flufl.enum import Enum class Colors(Enum): red = 1 green = 2 blue = 3 print(Colors.red) red = Colors.red print("red == Colors.red "+str(red == Colors.red)) print("red == Colors.blue "+str(red == Colors.blue)) print("red is Colors.red "+str(red is Colors.red)) Everything works as expected except the print(Color.red). According to <http://packages.python.org/flufl.enum/docs/using.html> I'd expect it to print "Colors.red" but it's printing 1. Anyone familiar with this package know if there's a way to get it to print "Colors.red"? I've posted a question on the library's site but thought someone here might have experience as well. EDIT: It does work as expected if I define Colors with: Colors = make_enum('Colors','red green blue') But I prefer the syntax of: class Colors(Enum): red = 1 green = 2 blue = 3 Answer: I realized init wasn't even being called on EnumMetaclass. I think the following code in _enum.py is meant to make inheriting from Enum all you'd need to do, but something about it doesn't work and it's beyond me: class Enum: __metaclass__ = EnumMetaclass This works: class Colors(metaclass=EnumMetaclass): red = 1 green = 2 blue = 3 I'm happy now. EDIT: Found out why. See the first answer to the following question: [Shouldn't __metaclass__ force the use of a metaclass in Python?](http://stackoverflow.com/questions/818483/shouldnt-metaclass-force- the-use-of-a-metaclass-in-python)
Click the javascript popup through webdriver Question: I am scraping a webpage using Selenium webdriver in Python The webpage I am working on, has a form. I am able to fill the form and then I click on the Submit button. It generates an popup window( Javascript Alert). I am not sure, how to click the popup through webdriver. Any idea how to do it ? Thanks Answer: Python Webdriver Script: from selenium import webdriver browser = webdriver.Firefox() browser.get("http://sandbox.dev/alert.html") alert = browser.switch_to_alert() alert.accept() browser.close() Webpage (alert.html): <html><body> <script>alert("hey");</script> </body></html> Running the webdriver script will open the HTML page that shows an alert. Webdriver immediately switches to the alert and accepts it. Webdriver then closes the browser and ends. If you are not sure there will be an alert then you need to catch the error with something like this. from selenium import webdriver browser = webdriver.Firefox() browser.get("http://sandbox.dev/no-alert.html") try: alert = browser.switch_to_alert() alert.accept() except: print "no alert to accept" browser.close() If you need to check the text of the alert, you can get the text of the alert by accessing the text attribute of the alert object: from selenium import webdriver browser = webdriver.Firefox() browser.get("http://sandbox.dev/alert.html") try: alert = browser.switch_to_alert() print alert.text alert.accept() except: print "no alert to accept" browser.close()
Why do I keep getting this title match error with my Python program? Question: When I run the following code, I keep getting this error: Traceback (most recent call last): File "C:\Users\Robert\Documents\j-a-c-o-b\newlc.py", line 94, in <module> main() File "C:\Users\Robert\Documents\j-a-c-o-b\newlc.py", line 71, in main for final_url in pool.imap(handle_listing, listings): File "C:\Python27\lib\site-packages\eventlet-0.9.16-py2.7.egg\eventlet\greenpool.py", line 232, in next val = self.waiters.get().wait() File "C:\Python27\lib\site-packages\eventlet-0.9.16-py2.7.egg\eventlet\greenthread.py", line 166, in wait return self._exit_event.wait() File "C:\Python27\lib\site-packages\eventlet-0.9.16-py2.7.egg\eventlet\event.py", line 120, in wait current.throw(*self._exc) File "C:\Python27\lib\site-packages\eventlet-0.9.16-py2.7.egg\eventlet\greenthread.py", line 192, in main result = function(*args, **kwargs) File "C:\Users\Robert\Documents\j-a-c-o-b\newlc.py", line 35, in handle_listing title, = TITLE_MATCH.match(listing_title).groups() AttributeError: 'NoneType' object has no attribute 'groups' What is wrong? It has something to do with the Title match but I don't know how to fix it! If you could help me I would really appreciate it! Thanks! from gzip import GzipFile from cStringIO import StringIO import re import webbrowser import time from difflib import SequenceMatcher import os import sys from BeautifulSoup import BeautifulSoup import eventlet from eventlet.green import urllib2 import urllib2 import urllib def download(url): print "Downloading:", url s = urllib2.urlopen(url).read() if s[:2] == '\x1f\x8b': ifh = GzipFile(mode='rb', fileobj=StringIO(s)) s = ifh.read() print "Downloaded: ", url return s def replace_chars(text, replacements): return ''.join(replacements.get(x,x) for x in text) def handle_listing(listing_url): listing_document = BeautifulSoup(download(listing_url)) # ignore pages that link to yellowpages if not listing_document.find("a", href=re.compile(re.escape("http://www.yellowpages.com/") + ".*")): listing_title = listing_document.title.text reps = {' ':'-', ',':'', '\'':'', '[':'', ']':''} title, = TITLE_MATCH.match(listing_title).groups() address, = ADDRESS_MATCH.match(listing_title).groups() yellow_page_url = "http://www.yellowpages.com/%s/%s?order=distance" % ( replace_chars(address, reps), replace_chars(title, reps), ) yellow_page = BeautifulSoup(download(yellow_page_url)) page_url = yellow_page.find("h3", {"class" : "business-name fn org"}) if page_url: page_url = page_url.a["href"] business_name = title[:title.index(",")] page = BeautifulSoup(download(page_url)) yellow_page_address = page.find("span", {"class" : "street-address"}) if yellow_page_address: if SequenceMatcher(None, address, yellow_page_address.text).ratio() >= 0.5: pid, = re.search(r'p(\d{5,20})\.jsp', listing_url).groups(0) page_escaped = replace_chars(page_url, {':':'%3A', '/':'%2F', '?':'%3F', '=':'%3D'}) final_url = "http://www.locationary.com/access/proxy.jsp?ACTION_TOKEN=proxy_jsp$JspView$SaveAction&inPlaceID=%s&xxx_c_1_f_987=%s" % ( pid, page_escaped) return final_url def main(): pool = eventlet.GreenPool() listings_document = BeautifulSoup(download(START_URL)) listings = listings_document.findAll("a", href = LOCATION_LISTING) listings = [listing['href'] for listing in listings] for final_url in pool.imap(handle_listing, listings): print final_url if str(final_url) is not None: url = str(final_url) req = urllib2.Request(url) response = urllib2.urlopen(req) page = response.read() time.sleep(2) for a in range(2,3): START_URL = 'http://www.locationary.com/place/en/US/New_Jersey/Randolph-page' + str(a) + '/?ACTION_TOKEN=NumericAction' TITLE_MATCH = re.compile(r'(.*) \(\d{1,10}.{1,100}\)$') ADDRESS_MATCH = re.compile(r'.{1,100}\((.*), .{4,14}, United States\)$') LOCATION_LISTING = re.compile(r'http://www\.locationary\.com/place/en/US/.{1,50}/.{1,50}/.{1,100}\.jsp') if __name__ == '__main__': main() Answer: Quoting from your error: > title, = TITLE_MATCH.match(listing_title).groups() > AttributeError: 'NoneType' object has no attribute 'groups' `TITLE_MATCH.match(listing_title)` returns `None`, so you can't call `.groups()`.
More pythonic way to iterate in Numpy Question: I am an engineering student and I'm accustomed to write code in Fortran, but now I'm trying to get more into Python for my numerical recipes using Numpy. If I needed to perform a calculation repeatedly using elements from several arrays, the immediate translation from what I'd write in Fortran would be k = np.zeros(N, dtype=np.float) u = ... M = ... r = ... for i in xrange(N): k[i] = ... # Something with u[i], M[i], r[i] and r[i - 1], for example But I was wondering if this way is more pythonic, or preferrable in any way: for i, (k_i, u_i, M_i, r_i) in enumerate(zip(k, u, M, r)): k_i = ... # Something with u_i, M_i, r_i and r[i - 1] Thanks to enumerate I have the index, otherwise if I don't need it I could use just zip or itertools.izip. Any ideas? How is the code affected in terms of performance? Is there any other way to accomplish this? Answer: Almost all numpy operations are performed element-wise. So instead of writing an explicit loop, try defining `k` using an array-based formula: r_shifted = np.roll(x, shift = 1) k = ... # some formula in terms of u, M, r, r_shifted For example, instead of import numpy as np N=5 k = np.zeros(N, dtype=np.float) u = np.ones(N, dtype=np.float) M = np.ones(N, dtype=np.float) r = np.ones(N, dtype=np.float) for i in xrange(N): k[i] = u[i] + M[i] + r[i] + r[i-1] print(k) # [ 4. 4. 4. 4. 4.] use: r_shifted = np.roll(r, shift = 1) k = u + M + r + r_shifted print(k) # [ 4. 4. 4. 4. 4.] * * * [np.roll(r, shift = 1)](http://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html) returns a new array of the same size as `r`, with `r_shifted[i] = r[i-1]` for `i = 0, ..., N-1`. In [31]: x = np.arange(5) In [32]: x Out[32]: array([0, 1, 2, 3, 4]) In [33]: np.roll(x, shift = 1) Out[33]: array([4, 0, 1, 2, 3]) Making a copy like this requires more memory (of the same size as `r`) but allows you to do fast numpy operations instead of using a slow Python loop. * * * Sometimes the formula for `k` can instead be defined in terms of `r[:-1]` and `r[1:]`. Note `r[:-1]` and `r[1:]` are slices of `r` and of the same shape. In this case, you don't need any extra memory since basic slices of `r` are so- called _views_ of `r`, not copies. I didn't define `k` this way in the example above because then `k` would have had length `N-1` instead of `N`, so it would have been slightly different than what your original code would have produced.
Python tkinter grid manager? Question: I just learned how to use tkinter in Python (3.2.2), and I'm having some problem using the grid manager. When I put button.grid(sticky=SE), for example, the button is not being put in the bottom-right and is just being put in the upper-left, ignoring the sticky value. What am I doing wrong here? I tried to search it but I couldn't really find out what I am doing wrong. Answer: You probably need to set a minimum size for the widget containing the button. If you don't, the container widget may shrink to occupy only the space required to display the button. If so, the sticky option will be meaningless since the container widget gives no space to show any difference. For example, using a `tk.Frame` as the container widget: import Tkinter as tk class SimpleApp(object): def __init__(self, master, **kwargs): title = kwargs.pop('title') frame = tk.Frame(master, borderwidth=5, bg = 'cyan', **kwargs) frame.grid() button = tk.Button(frame, text = title) button.grid(sticky = tk.SE) frame.rowconfigure('all', minsize = 200) frame.columnconfigure('all', minsize = 200) def basic(): root = tk.Tk() app = SimpleApp(root, title = 'Hello, world') root.mainloop() basic() yields ![enter image description here](http://i.stack.imgur.com/oCXjZ.png) * * * PS. I don't have tkinter installed in Python3.2 so I can't test this, but I think the only change you need to make this work with Python3.2 is import tkinter as tk instead of import Tkinter as tk
What is wrong with my regex Pattern to find recurring cycles in Python? Question: I want to match any string that has a recurring cycle. Like in this data: 3333333333333333333333333333333333333333 / 1 digit cycle(3) 1666666666666666666666666666666666666666 / 1 digit cycle(6) 1428571428571428571428571428571428571428 / 6 digit cycle(142857) 1111111111111111111111111111111111111111 / 1 digit cycle(1) 0909090909090909090909090909090909090909 / 2 digit cycle(09) 0834522467546323545411673445234655345222 / no cycle 0769230769230769230769230769230769230769 / 6 digit cycle(769230) 0714285714285714285714285714285714285714 / 6 digit cycle(714285) 0666666666666666666666666666666666666666 / 1 digit cycle(6) The pattern I have tried is `"([0-9]+?)\1+"` which works well in other languages (like VB or text editors). I have stored these strings inside a list named `values`. So here is my code: import re #stuff to get values pattern = re.compile("([0-9]+?)\1+") for value in values: matchObj = pattern.search(value) print(matchObj) #-> None matchObj = pattern.findall(value) print(matchObj) #-> [] What am I doing wrong? Any hint is appreciated. Answer: Add an r prefix: r"([0-9]+?)\1+" That will make the backslash a literal backslash instead of escaping the 1.
Why does the code : os.popen('move *.bin tmp) only move one file? Question: all, Currently, I write a python code in WIN, i'd like to run the command line code move *.bin tmp but only one file was removed. How can I make popen to finish this task? Best wish! Answer: I suggest using Pythons own modules instead of Windows tools (as also Patrick suggest). I think something like this will work: import glob import shutil dest = 'c:/tmp/' # Get all the files as a list with glob files = glob.glob('c:/files/*.bin') # move each file seperatly for filename in files: shutil.move(filename, dest) Or to make it short: import glob, shutil for f in glob.glob('c:/files/*.bin'): shutil.move(f, 'c:/tmp/')
Extract Text from a Binary File (using Python 2.7 on Windows 7) Question: I have a binary file of size about 5MB.. which has lots of interspersed text.. and control characters.. This is actually an equivalent of an outlook .pst file for SITATEX Application (from SITA). The file contains all the TEXT MESSAGES sent and received to and from outside world...(but the text has to be extracted through the binary control characters).. all the text messages are clearly available... with line ending ^M characters... etc. for example: assume ^@ ^X are control characters... \xaa with HEX aa, etc. loads of them around my required text extraction. ^@^@^@^@^@^@^@^@^@^@^@BLLBBCC^X^X^X^X^X^X^X^X^X ^X^X^X MVT^M EA1123 TEXT TEXT TEXT^M END^M \xaa^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@ ^@^@^@^@^@^@^@^@^@^@^@TTBBTT^X^X^X^X^X^X^X^X^X ^X^X^X blah blah blah... of control characters.. and then the message comes.. MVT MESSAGE 2 ED1123 etc. and so on.. for several messages. Using Perl.. it is easy to do: while (<>) { use regular expression to split messages m/ / } How would one do this in python easily.. 1. How to read the file? binary and text interspersed 2. Eliminate unnecessary control characters 3. parse the messages in between two \xaa USEFUL TEXT INFORMATION \xaa (HEX 'aa') 4. print out the required stuff 5. Loop through all the lines.. and more files. In the text file sample... I am interested in seeing.. BLLBBCC... and MVT and EA1123 and so on. Please assist... If it is going to be very difficult in python.. I will have to think through the logic in perl itself.. as it (perl) doesn't throw lots of errors at me at least for the looping part of binary and text stuff.. and the regex. Thanks. **Update 02Jan after reading your answers/comments** After going through S.Lott's comments and others... This is where I am at.. and it is working 80% ok. import fileinput import sys import re strfile = r'C:\Users\' \ r'\Learn\python\mvt\sitatex_test.msgs' f = open(strfile, 'rb') contents = f.read() # read whole file in contents #extract the string between two \xaaU.. multiline pattern match #with look ahead assertion #and this is stored in a list with all msgs msgs = re.findall(r'\xaaU.*?(?=\xaaU)', contents, re.I|re.DOTALL|re.M) for msg in msgs: #loop through msgs.. to find the first msg then next and so on. print "## NEW MESSAGE STARTS HERE ##" #for each msg split the lines.. to read line by line # stored as list in msglines msglines = msg.splitlines() line = 0 #then process each msgline with a message for msgline in msglines: line += 1 #msgline = re.sub(r'[\x00]+', r' ', msgline) mystr = msgline print mystr textstrings = re.findall(r'[\x00\x20-\x7E]+', msgline) So far so good.. still I am not completely done.. because I need to parse the text line by line and word by word.. to pickup (as an example) the origin address and headers, subject line, message body... by parsing the message through the control characters. Now I am stuck with... how to print line by line with the control characters converted to `\x00\x02..` etc (using the `\xHH` format).. but leave the normal readable text alone. For example.. say I have this: assume `^@` and `^X` are some control characters `line1 = '^@UG^@^@^@^@^@^@^@^@^@^@BLLBBCC^X^X^X^X^X^X^X^X^X'` (on the first line). When I print the line as it is on IDLE.. `print line1`.. it prints only say the first 2 or 3 characters.. and ignores the rest due to the control characters get choked. However, when I print with this: `print re.findall(r'.*', line1)` ['\xaaUG\x02\x05\x00\x04\x00\x00\x00\x05\x00\x00\x00.... x00\x00\x00..BLLBBCC\x00\x00N\x00N\\x00 002 010 180000 DEC 11', ''] It prints nicely with all the control characters converted to \xHH format.. and ascii text intact.. (just as I want it)..with one catch.. the list has two items.. with '' in the end. 1. What is the explanation for the empty string in the end? 2. How to avoid it... I just want the line converted nicely to a string (not a list). i.e. one line of binary/text to be converted to a string with \xHH codes.. leave the ASCII TEXT alone. Is using `re.findall(r'.*', line1)` is the only easy solution.. to do this conversion.. or are there any other straightforward method.. to convert a `'\x00string'` to \xHH and TEXT (where it is a printable character or whitespace). Also.. any other useful comments to get the lines out nicely. Thanks. **Update 2Jan2011 - Part 2** I have found out that `re.findall(r'.+', line1)` strips to ['\xaaUG\x02\x05\x00\x04\x00\x00\x00\x05\x00\x00\x00.... x00\x00\x00..BLLBBCC\x00\x00N\x00N\\x00 002 010 180000 DEC 11'] without the extra blank '' item in the list. This finding after numerous trial and errors. Still I will need assistance to eliminate the list altogether but return just a string. like this: '\xaaUG\x02\x05\x00\x04..BLLBBCC..002 010 180000 DEC 11' **Added Info on 05Jan:** @John Machin 1) \xaaU is the delimiter between messages.. In the example.. I may have just left out in the samples. Please see below for one actual message that ends with \xaaU (but left out). Following text is obtained from repr(msg between `r'\xaaU.*?(?=\xaaU)'`) I am trying to understand the binary format.. this is a typical message which is sent out the first 'JJJOWXH' is the sender address.. anything that follows that has 7 alphanumeric is the receiver addresses.. Based on the sender address.. I can know whether this is a 'SND' or 'RCV'.. as the source is 'JJJOWXH'... This msg is a 'SND' as we are 'JJJOWXH'. The message is addressed to: JJJKLXH.... JJJKRXH.... and so on. As soon as all the.. \x00000000 finishes.. the sita header and subject starts In this particular case... `"\x00QN\x00HX\x00180001 \x00"` this is the header.. and I am only interested all the stuff between \x00. and the body comes next.. after the final \x00 or any other control character... In this case... it is: > COR\r\nMVT \r\nHX9136/17.BLNZ.JJJ\r\nAD2309/2314 EA0128 > BBB\r\nDLRA/CI/0032/0022\r\nSI EET 02:14 HRS\r\n RA / 0032 DUE TO LATE ARVL > ACFT\r\n CI / 0022 OFFLOAD OVERHANG PALLET DUE INADEQUATE PACKING LEADING TO > \r\n SPACE PROBLEM once the readable text ends... the first control character that appears until the end \xaaU is to be ignored... In above cases.. "SPACE PROBLEM".. is the last one.. then control characters starts... so to be ignored... sometimes the control characters are not there till the next \xaaU. This is one complete message. > > "\xaaU\x1c\x04\x02\x00\x05\x06\x1f\x00\x19\x00\x00\x00\xc4\x9d\xedN\x1a\x00?\x02\x02\x00B\x02\x02\x00E\x02\x07\x00\xff\xff\x00\x00\xff\xff\x00\x00\xff\xff\x00\x00M\x02\xec\x00\xff\xff\x00\x00\x00\x00?\x02M\x02\xec\x00\xff\xff\x00\x00\xff\xff\x00\x00\xff\xff\x00\x00\xff\xff\x00\x00\xff\xff\x00\x00:\x03\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x7f\x00JJJOWXH\x00\x05w\x01x\x01\x00\x01JJJKLXH\x00\x00\x7f\x01\x80\x01\x00\x01JJJKRXH\x00F\x87\x01\x88\x01\x00\x01JJJFFXH\x00\xff\x8f\x01\x90\x01\x00\x01JJJFCXH\x00\xff\x97\x01\x98\x01\x00\x01JJJFAXH\x00\x00\x9f\x01\xa0\x01\x00\x01JJJKPXH\x00\x00\xa7\x01\xa8\x01\x00\x01HAKUOHU\x00\x00\xaf\x01\xb0\x01\x00\x01BBBHRXH\x00\x00\xb7\x01\xb8\x01\x00\x01BBBFFHX\x00\x00\xbf\x01\xc0\x01\x00\x01BBBOMHX\x00\x00\xc7\x01\xc8\x01\x00\x01BBBFMXH\x00\x00\xcf\x01\xd0\x01\x00\x01JJJHBER\x00\x00\xd7\x01\xd8\x01\x00\x01BBBFRUO\x00\x00\xdf\x01\xe0\x01\x00\x01BBBKKHX\x00\x00\xe7\x01\xe8\x01\x00\x01JJJLOTG\x00\x01\xef\x01\xf0\x01\x00\x01JJJLCTG\x00\x00\xf7\x01\xf8\x01\x00\x01HDQOMTG\x005\xff\x01\x00\x02\x00\x01CHACSHX\x00K\x07\x02\x08\x02\x00\x01JJJKZXH\x00F\x0f\x02\x10\x02\x00\x01BBBOMUO\x00 > \x17\x02\x18\x02\x00\x01BBBORXH\x00 \x1f\x02 > \x02\x00\x01BBBOPXH\x00W'\x02(\x02\x00\x01CHACSHX\x00 > /\x020\x02\x00\x01JJJDBXH\x0007\x028\x02\x00010000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00\x00000000\x00QN\x00HX\x00180001 > \x00COR\r\nMVT \r\nHX9136/17.BLNZ.JJJ\r\nAD2309/2314 EA0128 > BBB\r\nDLRA/CI/0032/0022\r\nSI EET 02:14 HRS\r\n RA / 0032 DUE TO LATE ARVL > ACFT\r\n CI / 0022 OFFLOAD OVERHANG PALLET DUE INADEQUATE PACKING LEADING TO > \r\n SPACE PROBLEM\x00D-\xedN\x00\x04\x1a\x00t<\x93\x01x\x00M_\x00" 2) I am not using .+ anymore after the 'repr' is known. 3) each Message is multiline.. and i need to preserve all the control characters to make some sense of this proprietary format.. that is why i needed repr to see it up close. Hope this explains... This is just 1 message out of 1000s with in the file... and some are 'SND' and some are 'RCV'... and for 'RCV' there will not be '000000'.. and occasionally there are minor exceptions to the rule... but usually that is okay. Any further suggestions anyone.. I am still working with the file.. to retrieve the text out intact... with sender and receiver addresses. Thank you. Answer: **Q: How to read the file? binary and text interspersed** _A: Don't bother, just read it as normal text and you'll be able to keep your binary/text dichotomy (otherwise you won't be able to regex it as easily)_ fh = open('/path/to/my/file.ext', 'r') fh.read() Just in case you want to read binary later for some reason, you just add a b to the second input of the open: fh = open('/path/to/my/file.ext', 'rb') **Q: Eliminate unnecessary control characters** _A: Use the python[re](http://docs.python.org/library/re.html) module. Your next question sorta ask how_ **Q: parse the messages in between two \xaa USEFUL TEXT INFORMATION \xaa (HEX 'aa')** _A: re module has a findall function that works as you (mostly) expect._ import re mytext = '\xaaUseful text that I want to keep\xaa^X^X^X\xaaOther text i like\xaa' usefultext = re.findall('\xaa([a-zA-Z^!-~0-9 ]+)\xaa', mytext) **Q: print out the required stuff** *A: There's a print function... print usefultext **Q: Loop through all the lines.. and more files.** fh = open('/some/file.ext','r') for lines in fh.readlines(): #do stuff I'll let you figure out the [os](http://docs.python.org/library/os.html) module to figure out what files exist/how to iterate through them.
Why are my Amazon S3 key permissions not sticking? Question: I'm using the Python library `boto` to connect to Amazon S3 and create buckets and keys for a static website. My keys and values are dynamically generated, hence why I am doing this programmatically and not through the web interface (it works using the web interface). My code currently looks like this: import boto from boto.s3.connection import S3Connection from boto.s3.key import Key conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(BUCKET_NAME) bucket.configure_website('index.html', 'error.html') bucket.set_acl('public-read') for template in ['index.html', 'contact-us.html', 'cart.html', 'checkout.html']: k = Key(bucket) k.key = key k.set_acl('public-read') k.set_metadata('Content-Type', 'text/html') k.set_contents_from_string(get_page_contents(template)) I'm getting various errors and problems with this code. When the keys already existed and I used this code to update them, I would set the ACL of each key to `public-read`, but I'd still get 403 forbidden errors when viewing the file in a browser. I tried removing all the keys to recreate them from scratch, and now I get a `NoSuchKey` exception. Obviously the key isn't there because I'm trying to create it. Am I going about this the wrong way? Is there a different way of doing this to create the keys as opposed to updating them? And am I experiencing some kind of race condition when the permissions don't stick? Answer: I'm still not completely sure why the code above didn't work, but I found a different (or newer?) syntax for creating keys. The order of operations also appears to have some effect. This is what I came up with that worked: conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(store.domain_name) bucket.set_acl('public-read') bucket.configure_website('index.html', 'error.html') for template in ['index.html', 'contact-us.html', 'cart.html', 'checkout.html']: k = bucket.new_key(template) k.set_metadata('Content-Type', 'text/html') k.set_contents_from_string(get_page_contents(template)) k.set_acl('public-read') #doing this last seems to be important for some reason
multiprocessing Listeners and Clients between python and pypy Question: Is it possible to have a [Listener server process and a Client process](http://docs.python.org/library/multiprocessing.html#module- multiprocessing.connection) where one of them uses a python interpreter and the other a [pypy](http://pypy.org/) interpreter? Would `conn.send()` and `conn.recv()` interoperate well? Answer: I tried it out to see: import sys from multiprocessing.connection import Listener, Client address = ('localhost', 6000) def client(): conn = Client(address, authkey='secret password') print conn.recv_bytes() conn.close() def server(): listener = Listener(address, authkey='secret password') conn = listener.accept() print 'connection accepted from', listener.last_accepted conn.send_bytes('hello') conn.close() listener.close() if __name__ == '__main__': if sys.argv[1] == 'client': client() else: server() Here are the results I got: * CPython 2.7 + CPython 2.7: **working** * PyPy 1.7 + PyPy 1.7: **working** * CPython 2.7 + PyPy 1.7: **not working** * CPython 2.7 + PyPy Nightly (pypy-c-jit-50911-94e9969b5f00-linux64): **working** When using PyPy 1.7 (doesn't matter which is the server and which is the client), an error is reported with `IOError: bad message length`. This also mirrors [the report on the pypy-dev mailing list](http://www.mail- archive.com/[email protected]/msg01607.html). However, this was recently fixed (it works in nightly build), so the next version (presumably 1.8) should have it fixed as well. In general, this works because the multiprocessing module uses Python's [pickle](http://docs.python.org/library/pickle.html) module, which is stable and supported across multiple Python implementations, even PyPy.
TaggedCorpusReader and UnigramTagger in nltk (python) Question: I'm trying to use nltk to auto-categorize news articles in a very lo-fi way. I've created a custom corpus of word/tag pairs correlating to my categories (ie. teacher/EDU, computer/TECH, etc.) I've been reading around and [this question](http://stackoverflow.com/questions/5919355/custom-tagging-with-nltk) got me pretty close, but I'm still stuck. Based on my code so far, how do I use my tagger to tag my sentence? import nltk # Loads my custom word/tag corpus from nltk.corpus.reader import TaggedCorpusReader reader = TaggedCorpusReader('taggers','.*') #Sets up the UnigramTagger default_tagger = nltk.data.load(nltk.tag._POS_TAGGER) tagger = nltk.tag.UnigramTagger(model=reader.tagged_words(), backoff=default_tagger) #Sample content sent = 'The students went to school to ask their teacher what the homework for the day was but she told them to check their email.' tokens = nltk.tokenize.word_tokenize(sent) # Sad Panda tagged = tagger.tag(tokens) # ^ produces AttributeError: 'ConcatenatedCorpusView' object has no attribute 'get' It's also very possible that this is a poor way to go about doing what I'm trying to do, but it seems good enough for a first run. Thanks in advance. Answer: Taggers are for part-of-speech tagging, not text classification. Take a look at the reuters corpus - it categorizes news articles into multiple categories using a category file. Then look at the nltk.classify module and read up on how to train text classifiers.
gai error at /home [Errno -2] Name or service not known Question: per the example in the httplib docs: >>> import httplib, urllib >>> params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'}) >>> headers = {"Content-type": "application/x-www-form-urlencoded", ... "Accept": "text/plain"} >>> conn = httplib.HTTPConnection("bugs.python.org") >>> conn.request("POST", "", params, headers) >>> response = conn.getresponse() >>> print response.status, response.reason 302 Found >>> data = response.read() >>> data 'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>' >>> conn.close() my code is: import httplib import urllib token = request.POST.get('token') if token: params = urllib.urlencode({'apiKey':'[some string]', 'token':token}) connection = httplib.HTTPSConnection('rpxnow.com/api/v2/auth_info') connection.request('POST', "", params) response = connection.getresponse() print response.read() inspection of my local vars yeilds: connection: "httplib.HTTPSConnection instance at 0x8baa4ac" params: 'token=[some string]&apiKey=[some string]' (My instructions to make this call are: Use the token to make the auth_info API call: URL: <https://rpxnow.com/api/v2/auth_info> Parameters: apiKey [some string] token The token value you extracted above) but I'm getting the error mentioned in the subject line. Why? Answer: You've misunderstood the documentation to httplib. The parameter to instantiate the `HTTPSConnection` is just the hostname. You then pass the actual path as the second param to `request`. So: connection = httplib.HTTPSConnection('rpxnow.com') connection.request('POST', '/api/v2/auth_info', params)
Pprint module works slowly with Django in 32bits system Question: I use Django on a 32 bits Ubuntu machine with Python 2.7. My development server has been slow all the time, taking about 15 seconds to render any page. I ran a cProfile test to see what works so slowly. Seems that it's the pprint module. Here's my statistics: ncalls tottime percall cumtime percall filename:lineno(function) 272605/48718 24.238 0 49.213 0.001 pprint.py:247(_safe_repr) and this is my colleague's who runs 64 bits OS X: 14531/5334 1.016 0.000 2.199 0.000 pprint.py:247(_safe_repr) Meanwhile I have to turn off the debug mode to use the dev server normally. Here's the profiling script: from cProfile import Profile from django.test.client import Client import Cookie cl = Client() cl.cookies = Cookie.SimpleCookie({'sessionid':'7344ebeba093b65c1d59a9d7583f60bc'}) p = Profile() p.runctx("c.get('/welcome/')", globals={'c': cl}, locals={}) p.print_stats() (the sessionid cookie is used to show a page where you need to log in.) **I'm not sure the 32bits system is the main reason.** The main quesion is: **Why is pprint._safe_repr so slow in Python 2.7 32 bits and fast in 64 bits?** and if I can set something to make it fast. Answer: > Why is pprint._safe_repr so slow in Python 2.7 32 bits and fast in 64 bits? It is not fast on 64 bits. Your colleague got much less `ncalls`. You should investigate why a single GET leads to such a large number of calls to `_safe_repr()`.
Conversion of unix epoch time to windows epoch time in python Question: Quick question: Is there a pythonic (whether in the standard libraries or not) way to convert unix 32-bit epoch time to windows 64-bit epoch time and back again? Answer: You can convert a POSIX timestamp to a `datetime` with >>> tstamp = 1325178061 # right about now >>> from datetime import datetime >>> datetime.fromtimestamp(tstamp) datetime.datetime(2011, 12, 29, 18, 1, 1) The [`fromtimestamp`](http://docs.python.org/library/datetime.html#datetime.datetime.fromtimestamp) named constructor accepts POSIX timestamps on all platforms (!). Conversion to a Windows timestamp would be a matter of subtracting the Windows epoch, which [Wikipedia says](http://en.wikipedia.org/wiki/Epoch_%28reference_date%29) is January 1, 1601, and converting the resulting `timedelta` to a number of seconds: >>> W_EPOCH = datetime(1601, 1, 1) >>> (datetime.fromtimestamp(tstamp) - W_EPOCH).total_seconds() 12969655261.0 Now you've got a `float` that you convert to `int` and store as a 64-bit quantity in whichever way you like.
pythonic way to iterate over part of a list Question: I want to iterate over everything in a list except the first few elements, e.g.: for line in lines[2:]: foo(line) This is concise, but copies the whole list, which is unnecessary. I could do: del lines[0:2] for line in lines: foo(line) But this modifies the list, which isn't always good. I can do this: for i in xrange(2, len(lines)): line = lines[i] foo(line) But, that's just gross. Better might be this: for i,line in enumerate(lines): if i < 2: continue foo(line) But it isn't quite as obvious as the very first example. So: What's a way to do it that is as obvious as the first example, but doesn't copy the list unnecessarily? Answer: You can try [`itertools.islice(iterable[, start], stop[, step])`](http://docs.python.org/library/itertools.html#itertools.islice): import itertools for line in itertools.islice(list , start, stop): foo(line)
Error: Could not import settings 'mysite.settings' after setting up virtualenv for Django Question: I am doing this on Fedora **Problem:** (sandbox)[root@localhost mysite]# django-admin.py runserver Error: Could not import settings 'mysite.settings' (Is it on sys.path?): No module named mysite.settings **Setup virtualenv** mkdir pythonenv # that's the /home/yeukhon/pythonenv/*.* cd pythonenv virtualenv --no-site-packages --distribute sandbox **Install Django** pip install -E sandbox django # changing mode of /home/yeukhon/pythonenv/sandbox/bin/django-admin.py to 755 # Successfully installed django **Under /home/yeukhon/pythonenv/sandbox** bin include lib mysite **Under lib** You have /lib/python2.7/site-packages/django/*.* **Create Project is fine** (sandbox)[root@localhost sandbox]# django-admin.py startproject mysite # the path is now /home/yeukhon/pythonenv/sandbox/mysite/*.* **Can't run server** django-admin.py runserver Error: Could not import settings 'mysite.settings' (Is it on sys.path?): No module named mysite.settings **Python Shell under sandbox** (following this guide: [How to troubleshoot - ImportError: Could not import settings 'mysite.settings' when deploying django?](http://stackoverflow.com/a/8054992/230884)) (sandbox)[root@localhost mysite]# python Python 2.7.2 (default, Oct 27 2011, 01:36:46) [GCC 4.6.1 20111003 (Red Hat 4.6.1-10)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> import os >>> os.environ['DJANGO_SETTINGS_MODULE'] 'mysite.settings' >>> os.path.exists('/home') True >>> os.path.exists('/home/yeukhon/pythonenv/sandbox/mysite') True >>> os.path.exists('/home/yeukhon/pythonenv/sandbox/mysite/settings.py') True >>> from django.core.management import setup_environ >>> import mysite.settings Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named mysite.settings >>> setup_environ(mysite.settings) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'mysite' is not defined >>> print sys.path ['', /home/yeukhon/pythonenv/sandbox/lib/python2.7/site-packages/distribute-0.6.14-py2.7.egg', '/home/yeukhon/pythonenv/sandbox/lib/python2.7/site-packages/pip-0.8.1-py2.7.egg', '/home/yeukhon/pythonenv/sandbox/lib/python27.zip', '/home/yeukhon/pythonenv/sandbox/lib/python2.7', '/home/yeukhon/pythonenv/sandbox/lib/python2.7/plat-linux2', '/home/yeukhon/pythonenv/sandbox/lib/python2.7/lib-tk', '/home/yeukhon/pythonenv/sandbox/lib/python2.7/lib-old', '/home/yeukhon/pythonenv/sandbox/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/home/yeukhon/pythonenv/sandbox/lib/python2.7/site-packages' What do I need to do to correct this problem? Thank you for your time. * * * **EDIT** Thanks for the response. I tried the following: (sandbox)[root@localhost mysite]# export PYTHONPATH="/home/yeukhon/pythonenv/sandbox/" (sandbox)[root@localhost mysite]# export PYTHONPATH="/home/yeukhon/pythonenv/" (sandbox)[root@localhost mysite]# deactivate [root@localhost mysite]# source ../bin/activate (sandbox)[root@localhost mysite]# django-admin.py runserver Error: Could not import settings 'mysite.settings' (Is it on sys.path?): No module named mysite.settings >>> sys.path ['',.... '/home/yeukhon/pythonenv'.....] It is now on the python path. But I still can't run the server. **Centralized Django Project** Yes. That's a good suggestion. So I suppose that all I need to do is "create a directory called mydjango, then create projects within mydjango". But what commands need to be changed / added? I am willing to learn good practice. Thank you very much. * * * **Solution (Add to environment variable)** PYTHONPATH=$PYTHONPATH:path-to-your-directory # PYTHONPATH=$PYTHONPATH:/home/yeukhon/pythonenv/sandbox/ Answer: The last line tells you all you need to know. In order to import `mysite.settings`, the parent directory of `mysite` must be on your PYTHONPATH. It currently isn't. FWIW, it's not typical to actually store your project _in_ the virtualenv directory. Usually, you put all your projects in on directory that you put on your PYTHONPATH. Then, just load up whatever virtualenv you need, and all's good. In fact, the best part of virtualenv is that they're interchangeable; i.e., you could easily run the same project in multiple different virtualenv environments (such as for testing a new release of Django without altering your normal virtualenv), but there again, you want your projects in one centralized place instead of inside a particular virtualenv directory.
imp.load_source() in Python Question: When is it useful to use `imp.load_source()` [method](http://docs.python.org/library/imp.html) for importing Python module? Has it some advantage in some scenario in opposite to normal importing with `import` keyword? Answer: `import` always looks in the following [order](http://docs.python.org/reference/simple_stmts.html#the-import- statement): 1. already imported modules 2. import hooks 3. files in the locations in `sys.path` 4. builtin modules If you want to import a module which would not be found by any of these mechanisms, but you know the filename, then you could use `imp.load_source()`. Or if you want to import a module that would be shadowed by an earlier import mechanism, for example if you want to import `foo` from a directory in `sys.path` but there is a custom import hook that would find its own version of `foo` first, then you could use `imp.load_source()` for that too. Basically it lets you control the source of the module's code in a way that `import` does not.
including additional static xml with python Question: I need my current script to include additional xml. This is the script in its current form: import csv import sys from xml.etree import ElementTree from xml.dom import minidom video_data = ((256, 336000), (512, 592000), (768, 848000), (1128, 1208000)) with open(sys.argv[1], 'rU') as f: reader = csv.DictReader(f) for row in reader: switch_tag = ElementTree.Element('switch') for suffix, bitrate in video_data: attrs = {'src': ("mp4:soundcheck/{year}/{id}/{file_root_name}_{suffix}.mp4" .format(suffix=str(suffix), **row)), 'system-bitrate': str(bitrate), } ElementTree.SubElement(switch_tag, 'video', attrs) print minidom.parseString(ElementTree.tostring(switch_tag)).toprettyxml() It currently outputs this xml: <?xml version="1.0" ?> <switch> <video src="mp4:soundcheck/2006/clay_aiken/02_sc_ca_sorry_256.mp4" system-bitrate="336000"/> <video src="mp4:soundcheck/2006/clay_aiken/02_sc_ca_sorry_512.mp4" system-bitrate="592000"/> <video src="mp4:soundcheck/2006/clay_aiken/02_sc_ca_sorry_768.mp4" system-bitrate="848000"/> <video src="mp4:soundcheck/2006/clay_aiken/02_sc_ca_sorry_1128.mp4" system-bitrate="1208000"/> </switch> I need to include additional information in the header and footer of the xml file. See example below: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE smil PUBLIC "-//W3C//DTD SMIL 2.0//EN" "http://www.w3.org/2001/SMIL20/SMIL20.dtd"> <smil xmlns="http://www.w3.org/2001/SMIL20/Language"> <head> <meta base="rtmp://cp23636.edgefcs.net/ondemand" /> </head> <body> <switch> <video src="mp4:soundcheck/2006/clay_aiken/02_sc_ca_sorry_256.mp4" system-bitrate="336000"/> <video src="mp4:soundcheck/2006/clay_aiken/02_sc_ca_sorry_512.mp4" system-bitrate="592000"/> <video src="mp4:soundcheck/2006/clay_aiken/02_sc_ca_sorry_768.mp4" system-bitrate="848000"/> <video src="mp4:soundcheck/2006/clay_aiken/02_sc_ca_sorry_1128.mp4" system-bitrate="1208000"/> </switch> </body> </smil> How can I update my current script to include this static information as well as the variable's that are being pulled from the csv in the scripts current form? Answer: Why don't you replace print minidom.parseString(ElementTree.tostring(switch_tag)).toprettyxml() with print header + ElementTree.tostring(switch_tag) + footer Where `header` and `footer` are what is above and below the switch tag in your second example output, respectively. Alternatively, if you want to use the `prettyxml()`, remove the first line from its output. '\n'.join(minidom.parseString(ElementTree.tostring(switch_tag)).toprettyxml().splitlines()[1:])
Eclipse PyDev auto-import malfunctioning Question: I've been trying to get used to pydev for a couple of days now, and I really like it, but if I keep the auto-import option on, it keeps importing for example `from test.test_iterlen import len` (and many others) whenever I want a `len(something)` even though it's not necessary. On the other hand if I completely turn the auto-import feature off, when I do a len(something), it just keeps inserting empty/blank lines before the current line and it's really annoying. Any idea what might be causing it? Either the non necessary import or the empty line one. Eclipse: Indigo Service Release 1 Eclipse platform: 3.7.1 PyDev: 2.3.0.2011121518 Python: 3.2.2 Many thanks! Answer: A popup list should appear with the code completion. Scroll down to the `len(object)` choice. With Python 2.7 I'm not able to recreate the weirdness you describe. There may be some strange Py3 behavior.
do not understand this use of sys module Question: Here is code from a tutorial in A Byte of Python: import sys filename = 'poem.txt' def readfile(filename): #Print a file to standard output f = file(filename) while True: line = f.readline() if len(line) == 0: break print line, f.close() if len(sys.argv) < 2: print 'No action specified' sys.exit() //<--This is where the error is occurring if sys.argv[1].startswith('--'): option = sys.argv[1][2:] #fetches sys.argv[1] without first 2 char if option == 'version': print 'Version 1.2' elif option == 'help': print '''\ This program prints files to the standard output. Any number of files can be specified. Options include: --version: Prints the version number --help: Displays this help''' else: print 'Unknown option' sys.exit() else: for filename in sys.argv[1:]: readfile(filename) When I run this code, this is the error that appears: Traceback (most recent call last): File "C:/Python/sysmodulepr.py", line 17, in <module> sys.exit() SystemExit I don't understand why. Please help. Answer: It's telling you that sys.exit() has executed on line 17 of your program. [The entry for for sys.exit in the Python documentation](http://docs.python.org/library/sys.html#sys.exit) tells you that this exits your program. There's no way this line can execute without producing other output, so I think there's something missing in the question.
Why does Django make Python look ugly? Question: I took up the Python programming language because of its design philosophies, its great community and most importantly for me its beautiful syntax. However, recently I've been a left a little disheartend. In my attempts to customise Django I've come across code that I think syntactically could be cleaner. I'm by no means a seasoned Python programmer, in-fact I've only been using it properly for the past few months. I'd appreciate your insights and your views. Here are some examples of code I have come across: Why is there a need for the slash? from django.contrib.admin.util import get_model_from_relation, \ reverse_field_path, get_limit_choices_to_from_path Could this be written more elegantly? rel_name = other_model._meta.pk.name self.lookup_kwarg = '%s__%s__exact' % (self.field_path, rel_name) self.lookup_kwarg_isnull = '%s__isnull' % (self.field_path) self.lookup_val = request.GET.get(self.lookup_kwarg, None) self.lookup_val_isnull = request.GET.get( self.lookup_kwarg_isnull, None) self.lookup_choices = f.get_choices(include_blank=False) One thing I don't understand is why the code after the if statement for each and statement is on seperate lines? def has_output(self): if isinstance(self.field, models.related.RelatedObject) \ and self.field.field.null or hasattr(self.field, 'rel') \ and self.field.null: extra = 1 else: extra = 0 return len(self.lookup_choices) + extra > 1 This just looks messy! def choices(self, cl): from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE yield {'selected': self.lookup_val is None and not self.lookup_val_isnull, 'query_string': cl.get_query_string( {}, [self.lookup_kwarg, self.lookup_kwarg_isnull]), 'display': _('All')} for pk_val, val in self.lookup_choices: yield {'selected': self.lookup_val == smart_unicode(pk_val), 'query_string': cl.get_query_string( {self.lookup_kwarg: pk_val}, [self.lookup_kwarg_isnull]), 'display': val} if isinstance(self.field, models.related.RelatedObject) \ and self.field.field.null or hasattr(self.field, 'rel') \ and self.field.null: yield {'selected': bool(self.lookup_val_isnull), 'query_string': cl.get_query_string( {self.lookup_kwarg_isnull: 'True'}, [self.lookup_kwarg]), 'display': EMPTY_CHANGELIST_VALUE} Please don't get me wrong, I'm not doing a disservice to the many contributors of Django, on the contrary I really admire them and I'm grateful. I appreciate that maybe it's my lack of experience with Python itself or that bits of code that make the syntax look unclean are in-fact core features of the Python programming language. **Just to make it clear this question is genuine and sincere, I ask this question in the spirit of learning and discussion. If you don't have anything conducive to contribute please don't respond.** Thank You Answer: > I appreciate that maybe it's my lack of experience with Python itself or > that bits of code that make the syntax look unclean are in-fact core > features of the Python programming language. That's just it. As you continue to code you'll realize that what you were experiencing was a result of everything being new. That type of code will happen in just about any language because the language is only ever going to be describing the communication between objects and function that respond to messages. A good exercise is just to glance over the codebase and get a feel for it. After a while you will get accustomed to the code and relations being expressed. So to summarize, the 'ugliness' is not exclusive to Python, but you will soon being to perceive it as just code as you begin to familiarize yourself with the language and become unconsciously competent and fluent in using the language.
Unescaping filenames generated by ls -R Question: I have a text file containing the output of a recursive directory listing that generally looks like this: ./subfolder/something with spaces: something\ with\ spaces.txt* something\ with\ spaces.dat* ./subfolder/yet another thing: yet\ another\ thing.txt* yet\ another\ thing.dat* I need to get a list of the full paths to each .txt file: ./subfolder/something with spaces/something with spaces.txt ./subfolder/yet another thing/yet another thing.txt I've almost got a solution for this, but what's the best solution for unescaping the filenames in Python? I don't know exactly what characters `ls -R` escaped (space and = are two such characters, though). I don't have access to the drive containing these files, either, so using a better command to obtain the list is out of the question, unfortunately. Answer: I'm not sure if there's built-in for this, but a simple regex could be used. re.sub(r'(?<!\\)\\', '', filename) This would remove all backslashes (except for those following another backslash). This seems to be the behavior when you try and `echo` these values on the terminal (I've only tested this in bash). bash-3.2$ echo foo\\bar foo\bar bash-3.2$ echo foo\ bar foo bar bash-3.2$ echo foo\=bar foo=bar Here's a complete python example: import re def unescape(filename): return re.sub(r'(?<!\\)\\', '', filename) print unescape(r'foo\ bar') print unescape(r'foo\=bar') print unescape(r'foo\\bar') Output: foo bar foo=bar foo\bar
Unusual Math with incorrect results? Question: My python interpreter is acting funky when I use the math.cos() and math.sin() function. For example, if I do this on my calculator: cos(35)*15+9 = 21.28728066 sin(35)*15+9 = 17.60364655 But when I do this on python (both 3.2 and 2.7) >>> import math >>> math.cos(35)*15+9 -4.5553830763726015 >>> import math >>> math.sin(35)*15+9 2.577259957557734 Why does this happen? EDIT: How do you change the Radian in Python to degrees, just in case? Answer: This is being caused by the fact that you are using _degrees_ and the trigonometric functions expect _radians_ as input: `sin(radians)` The description for `sin` is: sin(x) Return the sine of x (measured in radians). In Python, you can convert degrees to radians with the `math.radians` function. So if you do this with your input: >>> math.sin(math.radians(35)) * 15 + 9 17.60364654526569 it gives the same result as your calculator.
Roundrobin over changing set Question: I'd like to implement a simple round robin over a Python list or set that may be changed at runtime. The Problem is that I have a set of tasks that are to be executed in a round robin fashion, which should be simple enough to implement with a list and a modular increment of the index, but since I will modify the list it gets a bit more complex. Any good solution in Python, so I don't have to reinvent the wheel? Answer: I once used for testing purposes a "round-robin" test-object generator. I don't know if this will help you, but i included a simple example script to demsonstrate how it operates. from itertools import cycle n = 1 lst = [n] for i in cycle(lst): print i n += 1 if n < 100: lst.append(n)
Mac OS X 10.6, Mysql, Mysql-Python, Django Question: # UPDATE: I came across this post: [Python mysqldb on Mac OSX 10.6 not working](http://stackoverflow.com/questions/5072066/python-mysqldb-on-mac- osx-10-6-not-working) saw two options: 1. Add MySQL client libraries to the LD_LIBRARY_PATH mysql_config --libs -L/usr/local/mysql/lib -lmysqlclient -lpthread So I don't need to do anything here. 1. just going to upgrade to Python 2.7 and then re-install mysqldb. # ISSUE: Successfully installing django and and running virtualenvs environment and creating a project with sqlite3. I wanted to use mysql to manage the database instead. **settings.py** DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'blog', # Or path to database file if using sqlite3. 'USER': 'root', # Not used with sqlite3. 'PASSWORD': 'root', # Not used with sqlite3. 'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } This has stomped me: after performing: sudo python manage.py runserver **Error I get is:** Traceback (most recent call last): File "manage.py", line 14, in <module> execute_manager(settings) File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 438, in execute_manager utility.execute() File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 379, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 191, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 209, in execute translation.activate('en-us') File "/Library/Python/2.6/site-packages/django/utils/translation/__init__.py", line 100, in activate return _trans.activate(language) File "/Library/Python/2.6/site-packages/django/utils/translation/trans_real.py", line 202, in activate _active.value = translation(language) File "/Library/Python/2.6/site-packages/django/utils/translation/trans_real.py", line 185, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "/Library/Python/2.6/site-packages/django/utils/translation/trans_real.py", line 162, in _fetch app = import_module(appname) File "/Library/Python/2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Users/james/Projects/current/code/blog/jamesapps/../jamesapps/tagging/__init__.py", line 3, in <module> from tagging.managers import ModelTaggedItemManager, TagDescriptor File "/Users/james/Projects/current/code/blog/jamesapps/../jamesapps/apps/tagging/__init__.py", line 3, in <module> from tagging.managers import ModelTaggedItemManager, TagDescriptor File "/Users/james/Projects/current/code/blog/blog/django-tagging/tagging/managers.py", line 5, in <module> File "/Library/Python/2.6/site-packages/django/contrib/contenttypes/models.py", line 1, in <module> from django.db import models File "/Library/Python/2.6/site-packages/django/db/__init__.py", line 78, in <module> connection = connections[DEFAULT_DB_ALIAS] File "/Library/Python/2.6/site-packages/django/db/utils.py", line 93, in __getitem__ backend = load_backend(db['ENGINE']) File "/Library/Python/2.6/site-packages/django/db/utils.py", line 33, in load_backend return import_module('.base', backend_name) File "/Library/Python/2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Python/2.6/site-packages/django/db/backends/mysql/base.py", line 14, in <module> raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Python/2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib Referenced from: /Library/Python/2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg/_mysql.so Reason: image not found **My setup is:** Mac OS X 10.6.8 2x2Ghz Dual-Core Intel Xeon /usr/local/mysql/bin/mysql: Mach-O 64-bit executable x86_64 /usr/bin/python (for architecture x86_64): Mach-O 64-bit executable x86_64 /usr/bin/python (for architecture i386): Mach-O executable i386 /usr/bin/python (for architecture ppc7400): Mach-O executable ppc ~/.bash_profile contains export PATH=/usr/local/mysql/bin:$PATH export EDITOR="$HOME/bin/mate -w" export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/ **If I do** python shell import MySQLdb This displays nothing. **I have read the following posts and pages including many more:** <http://stackoverflow.com/questions/7335853/mysql-python-installation-problems-on-mac-os-x-lion> <http://stackoverflow.com/questions/1299013/problem-using-mysqldb-symbol-not-found-mysql-affected-rows> <http://friendlybit.com/tutorial/install-mysql-python-on-mac-os-x-leopard/> **I have uninstalled mysql using the following and then reinstalled from .dmg:** • Stop the database server • sudo rm /usr/local/mysql • sudo rm -rf /usr/local/mysql* • sudo rm -rf /Library/StartupItems/MySQLCOM • sudo rm -rf /Library/PreferencePanes/My* • edit /etc/hostconfig and remove the line MYSQLCOM=-YES- • rm -rf ~/Library/PreferencePanes/My* • sudo rm -rf /Library/Receipts/mysql* • sudo rm -rf /Library/Receipts/MySQL* • sudo rm -rf /private/var/db/receipts/*mysql* **Uninstalled mysql-python using pip and then recompiled from source:** sudo ARCHFLAGS='-arch x86_64' python setup.py build sudo ARCHFLAGS='-arch x86_64' python setup.py install Where am I going wrong, is it because the mysql clients are incorrectly configured for this version of Mysql-python? Answer: sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
Python SUDS SOAP request to https service 401 Question: I am trying use SUDS and am stuck trying to figure out why I can't get authentication to work (or https). The service I am trying to access is over https with basic digest authentication. Based on the debugs it seems to be using http instead of https. But not really sure what I am missing. Any clue is appreciated. from suds.client import Client from suds.transport.http import HttpAuthenticated import logging logging.basicConfig(level=logging.DEBUG) logging.getLogger('suds.client').setLevel(logging.DEBUG) logging.getLogger('suds.transport').setLevel(logging.DEBUG) logging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG) logging.getLogger('suds.wsdl').setLevel(logging.DEBUG) def main(): url = 'https://blah.com/soap/sp/Services?wsdl' credentials = dict(username='xxxx', password='xxxx') t = HttpAuthenticated(**credentials) client = Client(url, location='https://blah.com/soap/sp/Services', transport=t) print client.last_sent() if __name__=="__main__": main() Debug Output: > DEBUG:suds.wsdl:reading wsdl at: <https://blah.com/soap/sp/Services?wsdl> > ... DEBUG:suds.transport.http:opening > (https://blah.com/soap/sp/Services?wsdl) > snip ... > File "C:\Python27\Lib\site-packages\suds-0.4-py2.7\suds\reader.py", line > 95, in download > fp = self.options.transport.open(Request(url)) > > File "C:\Python27\Lib\site-packages\suds-0.4-py2.7\suds\transport\http.py", > line 173, in open > return HttpTransport.open(self, request) > > File "C:\Python27\Lib\site-packages\suds-0.4-py2.7\suds\transport\http.py", > line 64, in open > raise TransportError(str(e), e.code, e.fp) > > suds.transport.TransportError: HTTP Error 401: Authorization Required Answer: Suds provides two `HttpAuthenticated` classes, one in the `suds.transport.http` module and the second in the `suds.transport.https` module. It appears your instantiating from `suds.transport.http`, however since your URL is `https://`, you may want to try `suds.transport.https.HttpAuthenticated`.
How can I use Python to pipe stdin/stdout to Perl script Question: This Python code pipes data through Perl script fine. import subprocess kw = {} kw['executable'] = None kw['shell'] = True kw['stdin'] = None kw['stdout'] = subprocess.PIPE kw['stderr'] = subprocess.PIPE args = ' '.join(['/usr/bin/perl','-w','/path/script.perl','<','/path/mydata']) subproc = subprocess.Popen(args,**kw) for line in iter(subproc.stdout.readline, ''): print line.rstrip().decode('UTF-8') However, it requires that I first to save my buffers to a disk file (/path/mydata). It's cleaner to loop through the data in Python code and pass line-by-line to the subprocess like this: import subprocess kw = {} kw['executable'] = '/usr/bin/perl' kw['shell'] = False kw['stderr'] = subprocess.PIPE kw['stdin'] = subprocess.PIPE kw['stdout'] = subprocess.PIPE args = ['-w','/path/script.perl',] subproc = subprocess.Popen(args,**kw) f = codecs.open('/path/mydata','r','UTF-8') for line in f: subproc.stdin.write('%s\n'%(line.strip().encode('UTF-8'))) print line.strip() ### code hangs after printing this ### for line in iter(subproc.stdout.readline, ''): print line.rstrip().decode('UTF-8') subproc.terminate() f.close() The code hangs with the readline after sending the first line to the subprocess. I have other executables that use this exact same code perfectly. My data files can be quite large (1.5 GB) Is there way to accomplish piping the data without saving to file? I don't want to re-write the perl script for compatibility with other systems. Answer: Your code is blocking at the line: for line in iter(subproc.stdout.readline, ''): because the only way this iteration can terminate is when EOF (end-of-file) is reached, which will happen when the subprocess terminates. You don't want to wait till the process terminates, however, you only want to wait till its finished processing the line that was sent to it. Futhermore, you're encountering issues with buffering as Chris Morgan has already pointed out. Another [question on stackoverflow](http://stackoverflow.com/questions/375427/non-blocking-read-on- a-subprocess-pipe-in-python) discusses how you can do non-blocking reads with subprocess. I've hacked up a quick and dirty adaptation of the code from that question to your problem: def enqueue_output(out, queue): for line in iter(out.readline, ''): queue.put(line) out.close() kw = {} kw['executable'] = '/usr/bin/perl' kw['shell'] = False kw['stderr'] = subprocess.PIPE kw['stdin'] = subprocess.PIPE kw['stdout'] = subprocess.PIPE args = ['-w','/path/script.perl',] subproc = subprocess.Popen(args, **kw) f = codecs.open('/path/mydata','r','UTF-8') q = Queue.Queue() t = threading.Thread(target = enqueue_output, args = (subproc.stdout, q)) t.daemon = True t.start() for line in f: subproc.stdin.write('%s\n'%(line.strip().encode('UTF-8'))) print "Sent:", line.strip() ### code hangs after printing this ### try: line = q.get_nowait() except Queue.Empty: pass else: print "Received:", line.rstrip().decode('UTF-8') subproc.terminate() f.close() It's quite likely that you'll need to make modifications to this code, but at least it doesn't block.
Python: How to import, from two modules, Classes that have same names? Question: I'm writing a python programm to do granular syncs between different DB. I'm using SQLAlchemy and a module named sqlautocode for DB inspecting and Schema Classes production. Having two DB to sync, with same tables name, the Classes written by sqlautocode results with same names. I have to import theese Classes with arbitrary prefixes, I'm thinking about something like this: from module_name import * with prefixes Otherwise I should import every Classes name with an "as" modifier, like this: from module_name import x as master_x First of HardCode name extraction procedures with control lists and exec/eval complex code I'd like some suggestions about it. UPDATE: The solution is a sqlautocode option: --table-prefix=TABLE_PREFIX thank you all Answer: Just import the modules and don't try to pull the names from them. `from X import Y` should be used sporadically, anyway. import module_a import module_b module_a.x module_b.x
Python catch any exception, and print or log traceback with variable values Question: When I catch unexpected error with sys.excepthook import sys import traceback def handleException(excType, excValue, trace): print 'error' traceback.print_exception(excType, excValue, trace) sys.excepthook = handleException h = 1 k = 0 print h/k This is output I get error Traceback (most recent call last): File "test.py", line 13, in <module> print h/k ZeroDivisionError: integer division or modulo by zero How can I include variable values (h, k, ...) in traceback simillar to <http://www.doughellmann.com/PyMOTW/cgitb/> ? When I include cgitb result is same. **EDIT:** Great answer I only modified it like this so it logs trace in a file def handleException(excType, excValue, trace): cgitb.Hook(logdir=os.path.dirname(__file__), display=False, format='text')(excType, excValue, trace) Answer: By looking at the source of `cgitb.py`, you should be able to use something like this: import sys import traceback import cgitb def handleException(excType, excValue, trace): print 'error' cgitb.Hook(format="text")(excType, excValue, trace) sys.excepthook = handleException h = 1 k = 0 print h/k
wxpython capture keyboard events in a wx.Frame Question: I'm trying to capture keyboard events that happen inside a wx.Frame, and I would expect the following code to capture those events. However, the handler OnKeyDown is never called when I run the code: import logging as log import wx class MainWindow(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(200,100)) self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) self.Bind(wx.EVT_KEY_UP, self.OnKeyDown) self.Bind(wx.EVT_CHAR, self.OnKeyDown) self.SetFocus() self.Show(True) def OnKeyDown(self, event=None): log.debug("OnKeyDown event %s" % (event)) if __name__ == "__main__": app = wx.App(False) gui = MainWindow(None, "test") app.MainLoop() If anyone knows how to do this, I would appreciate some help. Answer: I figured out that I can add a panel to the frame, and a panel is much more receptive of keyboard events. import wx class MainWindow(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(200,100)) self.panel = wx.Panel(self, wx.ID_ANY) self.panel.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) self.panel.Bind(wx.EVT_KEY_UP, self.OnKeyDown) self.panel.Bind(wx.EVT_CHAR, self.OnKeyDown) self.panel.SetFocus() self.Show(True) def OnKeyDown(self, event=None): print "Event!" if __name__ == "__main__": app = wx.App(False) gui = MainWindow(None, "test") app.MainLoop()
Application of the dynamic/functional features of Python Question: I'm learning Python and it seems to be too dynamic to me. Application of some of the dynamic/functional features I understand. For example, you can use dynamic typing to write functions that behave the same for complex and real numbers. But application of others seems obscure to me. So here is my question. Please give examples where the following Python features are actually useful: * Lack of private variables. * Ability do define methods and variables in runtime. * Ability to replace methods in runtime. (Maybe some other features will appear here - I'm still learning.) Answer: Lack of private variables: you don't have to waste time declaring every variable public or private. Most of the stuff is usually public. If you think that a directly variable accessed without getter/setters will break things, you can use the convention of naming it with underscore: e.g. self._metadata. Ability to define methods and variables in runtime: This is non-python- specific, general question regarding dynamic languages. One important use case is alternative to function pointers and polymorphism. Rather than compiling on-hand all kinds of functions you'd encounter, you can dynamically make/change things on the fly. Ability to replace methods in runtime: this is again mainly used for polymorphism and function pointers. You have a running HR system with a policy in place. You want to make some changes in the policy. Rather than recompiling the whole system and restarting the system, you can just inject the new policy and replace the policy related method(s). You might want be interested in this article: <http://www.paulgraham.com/diff.html>
Python IP Check Question: Given the range xxx.xxx.xxx.(195-223) Is that correct to write it in xxx.xxx.xxx.196/29 and check whether an IP is in the given network by doing from ipaddr import IP, CIDR #if IP('xxx.xxx.xxx.xxx') in IP('xxx.xxx.xxx.196/29') or #if IP('xxx.xxx.xxx.xxx') in CIDR('xxx.xxx.xxx.196/29') Answer: I didn't see IP in ipaddr, only IPAddress. May be like this? from ipaddr import IPAdddress, IPNetwork if IPAddress('10.0.0.195') in IPNetwork('10.0.0.196/29'): pass
Error while using urllib.request.urlopen in Python Question: What's wrong with this code? >>> from urllib.request import urlopen >>> for line in urlopen("http://google.com/"): print(line.decode("utf-8")) <!doctype html><html><head><meta http-equiv="content-type" content="text/html; charset=windows-1251"><title>Google</title><script>window.google={kEI:"XMECT7XyDcGn0AWFk7ywAQ",getEI:function(a){var b;while(a&&!(a.getAttribute&&(b=a.getAttribute("eid"))))a=a.parentNode;return b||google.kEI},https:function(){return window.location.protocol=="https:"},kEXPI:"33492,35300",kCSI:{e:"33492,35300",ei:"XMECT7XyDcGn0AWFk7ywAQ"},authuser:0, ml:function(){},kHL:"uk",time:function(){return(new Date).getTime()},log:function(a,b,c,e){var d=new Image,g=google,h=g.lc,f=g.li,j="";d.onerror=(d.onload=(d.onabort=function(){delete h[f]}));h[f]=d;if(!c&&b.search("&ei=")==-1)j="&ei="+google.getEI(e);var i=c||"/gen_204?atyp=i&ct="+a+"&cad="+b+j+"&zx="+google.time(),k=/^http:/i;if(k.test(i)&&google.https()){google.ml(new Error("GLMM"),false,{src:i}); delete h[f];return}d.src=i;g.li=f+1},lc:[],li:0,Toolbelt:{},y:{},x:function(a,b){google.y[a.id]= [a,b];return false}}; window.google.sn="webhp";window.google.timers={};window.google.startTick=function(a,b){window.google.timers[a]={t:{start:(new Date).getTime()},bfr:!(!b)}};window.google.tick=function(a,b,c){if(!window.google.timers[a])google.startTick(a);window.google.timers[a].t[b]=c||(new Date).getTime()};google.startTick("load",true);try{}catch(u){} var _gjwl=location;function _gjuc(){var e=_gjwl.href.indexOf("#");if(e>=0){var a=_gjwl.href.substring(e);if(a.indexOf("&q=")>0||a.indexOf("#q=")>=0){a=a.substring(1);if(a.indexOf("#")==-1){for(var c=0;c<a.length;){var d=c;if(a.charAt(d)=="&")++d;var b=a.indexOf("&",d);if(b==-1)b=a.length;var f=a.substring(d,b);if(f.indexOf("fp=")==0){a=a.substring(0,c)+a.substring(b,a.length);b=c}else if(f=="cad=h")return 0;c=b}_gjwl.href="/search?"+a+"&cad=h";return 1}}}return 0}function _gjp(){!(window._gjwl.hash&& window._gjuc())&&setTimeout(_gjp,500)}; Traceback (most recent call last): File "<pyshell#109>", line 2, in <module> print(line.decode("utf-8")) UnicodeDecodeError: 'utf8' codec can't decode byte 0xc2 in position 2364: invalid continuation byte Answer: Google sends you text in windows-1251 encoding, it says it in meta tag. This will work: >>> from urllib.request import urlopen >>> for line in urlopen("http://google.com/"): print(line.decode("cp1251"))
matlab subsref: {} with string argument fails, why? Question: There are a few implementations of a hash or dictionary class in the Mathworks File Exchange repository. All that I have looked at use parentheses overloading for key referencing, e.g. d = Dict; d('foo') = 'bar'; y = d('foo'); which seems a reasonable interface. It would be preferable, though, if you want to easily have dictionaries which contain other dictionaries, to use braces `{}` instead of parentheses, as this allows you to get around MATLAB's (arbitrary, it seems) syntax limitation that multiple parentheses are not allowed but multiple braces are allowed, i.e. t{1}{2}{3} % is legal MATLAB t(1)(2)(3) % is not legal MATLAB So if you want to easily be able to nest dictionaries within dictionaries, dict{'key1'}{'key2'}{'key3'} as is a common idiom in Perl and is possible and frequently useful in other languages including Python, then unless you want to use `n-1` intermediate variables to extract a dictionary entry `n` layers deep, this seems a good choice. And it would seem easy to rewrite the class's `subsref` and `subsasgn` operations to do the same thing for `{}` as they previously did for `()`, and everything should work. Except it doesn't when I try it. Here's my code. (I've reduced it to a minimal case. No actual dictionary is implemented here, each object has one key and one value, but this is enough to demonstrate the problem.) classdef TestBraces < handle properties % not a full hash table implementation, obviously key value end methods(Access = public) function val = subsref(obj, ref) % Re-implement dot referencing for methods. if strcmp(ref(1).type, '.') % User trying to access a method % Methods access if ismember(ref(1).subs, methods(obj)) if length(ref) > 1 % Call with args val = obj.(ref(1).subs)(ref(2).subs{:}); else % No args val = obj.(ref.subs); end return; end % User trying to access something else. error(['Reference to non-existant property or method ''' ref.subs '''']); end switch ref.type case '()' error('() indexing not supported.'); case '{}' theKey = ref.subs{1}; if isequal(obj.key, theKey) val = obj.value; else error('key %s not found', theKey); end otherwise error('Should never happen') end end function obj = subsasgn(obj, ref, value) %Dict/SUBSASGN Subscript assignment for Dict objects. % % See also: Dict % if ~strcmp(ref.type,'{}') error('() and dot indexing for assignment not supported.'); end % Vectorized calls not supported if length(ref.subs) > 1 error('Dict only supports storing key/value pairs one at a time.'); end theKey = ref.subs{1}; obj.key = theKey; obj.value = value; end % subsasgn end end Using this code, I can assign as expected: t = TestBraces; t{'foo'} = 'bar' (And it is clear that the assignment work from the default display output for `t`.) So `subsasgn` appears to work correctly. But I can't retrieve the value (`subsref` doesn't work): t{'foo'} ??? Error using ==> subsref Too many output arguments. The error message makes no sense to me, and a breakpoint at the first executable line of my `subsref` handler is never hit, so at least superficially this looks like a MATLAB issue, not a bug in my code. Clearly string arguments to `()` parenthesis subscripts _are_ allowed, since this works fine if you change the code to work with `()` instead of `{}`. (Except then you can't nest subscript operations, which is the object of the exercise.) Either insight into what I'm doing wrong in my code, any limitations that make what I'm doing unfeasible, or alternative implementations of nested dictionaries would be appreciated. Answer: Short answer, add this method to your class: function n = numel(obj, varargin) n = 1; end **EDIT** : The long answer. Despite the way that `subsref`'s function signature appears in the documentation, it's actually a varargout function - it can produce a variable number of output arguments. Both brace and dot indexing can produce multiple outputs, as shown here: >> c = {1,2,3,4,5}; >> [a,b,c] = c{[1 3 5]} a = 1 b = 3 c = 5 The number of outputs expected from `subsref` is determined based on the size of the indexing array. In this case, the indexing array is size 3, so there's three outputs. Now, look again at: t{'foo'} What's the size of the indexing array? Also 3. MATLAB doesn't care that you intend to interpret this as a string instead of an array. It just sees that the input is size 3 and your subsref can only output 1 thing at a time. So, the arguments mismatch. Fortunately, we can correct things by changing the way that MATLAB determines how many outputs are expected by overloading [`numel`](http://www.mathworks.com/help/techdoc/ref/numel.html). Quoted from the doc link: > It is important to note the significance of numel with regards to the > overloaded subsref and subsasgn functions. In the case of the overloaded > subsref function for brace and dot indexing (as described in the last > paragraph), numel is used to compute the number of expected outputs > (nargout) returned from subsref. For the overloaded subsasgn function, numel > is used to compute the number of expected inputs (nargin) to be assigned > using subsasgn. The nargin value for the overloaded subsasgn function is the > value returned by numel plus 2 (one for the variable being assigned to, and > one for the structure array of subscripts). > > As a class designer, you must ensure that the value of n returned by the > built-in numel function is consistent with the class design for that object. > If n is different from either the nargout for the overloaded subsref > function or the nargin for the overloaded subsasgn function, then you need > to overload numel to return a value of n that is consistent with the class' > subsref and subsasgn functions. Otherwise, MATLAB produces errors when > calling these functions. And there you have it.
Python variables naming convention Question: So I am trying to switch to PEP8 notation (from a rather personal CamelCase notation) and I was wondering how you guys are tackling the cases where existing functions/variables would be overwritten? e.g. having something like: open, high, low, close, sum = row would already overwrite the "open" and "sum" functions. First, if I wouldn't use a good IDE, I wouldn't even notice that I've just overwritten important basic functions. Second, how would you name the variables instead? In this example I would have used apps hungarian and wouldn't have encountered any potential problem at all. Thanks! Answer: I would use `open_` and `sum_`.
python: how to tell if file executed as import vs. main script? Question: I'm writing a python file `mylib.py` I'd like mylib.py to do something based on `sys.argv` if it's being executed as a script. But if it's imported from some other script, I don't want it to do that. How can I tell if my python file is being imported or it's a main script? (I've seen how to do this before, but I forgot.) Answer: if __name__ == '__main__': # this was run as a main script Here is the [documentation on `__main__`](http://docs.python.org/library/__main__.html#module-__main__). Usually this code is placed at the bottom of a module, and one common way to keep your code clean is to create a `main()` function that does all of the work, and only call that function inside of the conditional.
Python UTF-8 XML parsing (SUDS): Removing 'invalid token' Question: Here's a common error when dealing with UTF-8 - 'invalid tokens' In my example, It comes from dealing with a SOAP service provider that had no respect for unicode characters, simply truncating values to 100 bytes and neglecting that the 100'th byte may be in the middle of a multi-byte character: for example: <name xsi:type="xsd:string">浙江家庭教会五十人遭驱散及抓打 圣诞节聚会被断电及抢走物品(图、视频\xef\xbc</name> The last two bytes are what remains of a 3 byte unicode character, after the truncation knife assumed that the world uses 1-byte characters. Next stop, sax parser and: xml.sax._exceptions.SAXParseException: <unknown>:1:2392: not well-formed (invalid token) I don't care about this character anymore. It should be removed from the document and allow the sax parser to function. The XML reply is valid in every other respect except for these values. **Question: How do you remove this character without parsing the entire document and re-inventing UTF-8 encoding to check every byte?** Using: Python+SUDS Answer: Turns out, SUDS sees xml as type 'string' (not unicode) so these are encoded values. 1) The FILTER: badXML = "your bad utf-8 xml here" #(type <str>) #Turn it into a python unicode string - ignore errors, kick out bad unicode decoded = badXML.decode('utf-8', errors='ignore') #(type <unicode>) #turn it back into a string, using utf-8 encoding. goodXML = decoded.encode('utf-8') #(type <str>) 2) SUDS: see <https://fedorahosted.org/suds/wiki/Documentation#MessagePlugin> from suds.plugin import MessagePlugin class UnicodeFilter(MessagePlugin): def received(self, context): decoded = context.reply.decode('utf-8', errors='ignore') reencoded = decoded.encode('utf-8') context.reply = reencoded and from suds.client import Client client = Client(WSDL_url, plugins=[UnicodeFilter()]) Hope this helps someone. * * * Note: Thanks to [John Machin](http://stackoverflow.com/users/84270/john-machin "John Machin")! See: [Why is python decode replacing more than the invalid bytes from an encoded string?](http://stackoverflow.com/questions/2547262/why-is-python- decode-replacing-more-than-the-invalid-bytes-from-an-encoded-strin) Python [issue8271](http://bugs.python.org/issue8271) regarding `errors='ignore'` can get in your way here. Without this bug fixed in python, 'ignore' will consume the next few bytes to satisfy the length > during the decoding of an invalid UTF-8 byte sequence, only the > start byte and the continuation byte(s) are now considered invalid, instead > of the number of bytes specified by the start byte Issue was fixed in: Python 2.6.6 rc1 Python 2.7.1 rc1 (and all future releases of 2.7) Python 3.1.3 rc1 (and all future release of 3.x) Python 2.5 and below will contain this issue. In the example above, `"\xef\xbc</name".decode('utf-8', errors='ignore')` should return `"</name"`, but in 'bugged' versions of python it returns `"/name"`. The first four bits (`0xe`) describes a 3-byte UTF character, so the bytes`0xef`, `0xbc`, and then (erroneously) `0x3c` (`'<'`) are consumed. `0x3c` is not a valid continuation byte which creates the invalid 3-byte UTF character in the first place. Fixed versions of python only remove the first byte and _only valid continuation_ bytes, leaving `0x3c` unconsumed
How to append to PYTHONPATH in Tornado so Handlers can use other libraries? Question: I am attempting to start a Tornado web server, but I need the Handlers to be able to import libraries from a custom path. I cannot simply add sys.path.append('..') when launching Tornado, so how do I do it? Answer: import sys sys.path.append('/home/user/py/lib')
Passing in arguments to a called script Question: I'm running `nosetests` on my project with `--with-snort` for Growl notifications. The problem is that I have some lib files that I put on the path, so I have a custom python script at `bin/python`. I have no issues running nose via my `bin/python` by doing `which nosetests` and using that executable - `bin/python /usr/local/bin/nosetests`. But now how do I pass in flags to `nosetests`? Any flags will go to `bin/python` instead. Answer: What makes you think that flags will go to `bin/python`? Have you tested this? If I write a simple program to test this out: import sys print sys.argv[1:] I get the following ouput from these example calls (assuming I have saved this in a file called test.py) `python test.py` prints `[]` `python test.py 5` prints `['5']` `python -i test.py 5` prints `['5']` (and then passes control to the interpreter because of the `-i` flag). So flags **before** the script name are passed to Python, flags **after** the script name are passed to the script. So in your example, just use bin/python /usr/local/bin/nosetests --with-snort Some of this is convered in [Invoking the Interpreter](http://docs.python.org/tutorial/interpreter.html) in Python's documentation.
PYTHON 2.6 XML.ETREE to output single quote for attributes instead of double quote Question: i got the following code : #!/usr/bin/python2.6 from lxml import etree n = etree.Element('test') n.set('id','1234') print etree.tostring(n) the output generate is `<test id="1234"/>` but i want `<test id='1234'/>` can someone help ? Answer: I checked the documentation and found no reference for single/double-quote option. I think your only recourse is `print etree.tostring(n).replace('"', "'")`
AES Encryption in Google App Engine (Python) and Decryption on iOS (Objective-C) Question: I'm trying to encrypt some data from python (Google App Engine) and then decrypt it on iOS. There are several issues surrounding this based on the fact that there are so many options with AES Encryption and the different formats available in Python and Objective-C. Because of the limited availability of the PyCrypto libraries on Google App Engine and the AES code on the iOS/Objective-C side requiring PKCS7Padding, I decided to use slowAES on the python side. I'm also using a 16-bit key, CBC Mode, and PKCS7Padding. Given that, this is my encrypt function and helper variables/function: def str2nums(s): return map(ord, s) key = "hjt4mndfy234n5fs" moo = aes.AESModeOfOperation() iv = [12, 34, 96, 15] * 4 CBC_mode = moo.modeOfOperation['CBC'] nkey = str2nums(key) def encrypt(plaintext): funcName = inspect.stack()[0][3] logging.debug("Enter " + funcName) logging.debug("Input string: " + plaintext) m, s, encData = moo.encrypt(plaintext, CBC_mode, nkey, len(nkey), iv) fmt = len(encData)*'B' dataAsStr = "" for j in encData: dataAsStr = dataAsStr + str(j) + "," logging.debug("Output encrypted data:[" + dataAsStr + "]") encoded = base64.b64encode(struct.pack(fmt, *encData)) logging.debug("Output encrypted string: " + encoded) decoded = struct.unpack(fmt, base64.b64decode(encoded)) decrypted = moo.decrypt(decoded, s, CBC_mode, nkey, len(nkey), iv) logging.debug("Output decrypted back: " + decrypted) return encoded Note that on the Python side, I am encrypting, packing, and then base64 encoding the data. Before returning this encrypted data, I'm also doing a test run at decrypting it just to show that in the logs and it does indeed work. On the iOS side, I'm using the following AES NSData addition: - (NSData *)AES128DecryptWithKey:(NSString *)key { // 'key' should be 16 bytes for AES128, will be null-padded otherwise char keyPtr[kCCKeySizeAES128+1]; // room for terminator (unused) bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding) // fetch key data [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSASCIIStringEncoding]; NSUInteger dataLength = [self length]; //See the doc: For block ciphers, the output size will always be less than or //equal to the input size plus the size of one block. //That's why we need to add the size of one block here size_t bufferSize = dataLength + kCCBlockSizeAES128; void *buffer = malloc(bufferSize); size_t numBytesDecrypted = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, keyPtr, kCCKeySizeAES128, NULL /* initialization vector (optional) */, [self bytes], dataLength, /* input */ buffer, bufferSize, /* output */ &numBytesDecrypted); if (cryptStatus == kCCSuccess) { //the returned NSData takes ownership of the buffer and will free it on deallocation return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted]; } free(buffer); //free the buffer; return nil; } And I'm making use of this when I pull down the base64/packed/encrypted data like so: NSMutableString * result = [[NSMutableString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]; if (LOG) { NSLog(@"Base64 encoded / Encrypted string: %@", result); } NSData* encryptedData = [NSData decodeBase64ForString:result]; // base64 decode if (LOG) { NSLog(@"Encrypted string: %@", encryptedData); } NSData* decryptedData = [encryptedData AES128DecryptWithKey:@"hjt4mndfy234n5fs"]; // AES Decrypt The problem is, I can't seem to get the data to decrypt correctly on the client (iOS) side even though it decrypts just fine on the server (in python). During the decryption, the cryptStatus always ends up : **kCCAlignmentError.** Which I don't quite understand. I've also messed with AES 256 but I need a 32bit key I think and that doesn't seem to be an option for slowAES in CBC mode (at least according to the examples?). Logging of the Server (Notice the actual unencrypted data is merely an empty set [] . That's a JSON representation of such to return to the client. 2012-01-04 08:48:13.962 Enter encrypt D 2012-01-04 08:48:13.962 Input string: [] D 2012-01-04 08:48:13.967 Output encrypted data:[4,254,226,26,101,240,22,113,44,54,209,203,233,64,208,255,] D 2012-01-04 08:48:13.967 Output encrypted string: BP7iGmXwFnEsNtHL6UDQ/w== D 2012-01-04 08:48:13.971 Output decrypted back: [] Logging of the client (iOS): 2012-01-04 12:45:13.891 Base64 encoded / Encrypted string: BP7iGmXwFnEsNtHL6UDQ/w== 2012-01-04 12:45:13.892 Encrypted string: <04fee21a 65f01671 2c36d1cb e940d0ff> 2012-01-04 12:45:29.126 Decrypted string: So my questions are: 1. What does it mean by an "Alignment Error"? Or what am I doing wrong that it doesn't want to decrypt on the client? 2. Do I need to worry about unpacking the data at all considering it looks like it matches up just fine? And if so, how would I go about an unpack() function in C or Objective-C? 3. Is there just plain a better way to do AES encryption between Google App Engine and iOS? EDIT: I should also note that besides the answer of using the same Initialization Vector, I found a discrepancy between the python and iOS code for the padding. The encrypt/decrypt worked fine for small amounts of data but then I ran into failure to decrypt with larger ones. I fixed this by changing the iOS side to NOT use PKCS7Padding and put 0 there instead. Answer: The IV needs to match on both ends. The IV (initialization vector) is a string of bytes that's sent through the encryptor/decryptor to place its "memory" in a pseudo-random state before the "real" data is sent through. Since the encryption results depend on what's gone through before, this initialization makes it impossible (without knowing the IV) for a malicious 3rd party o know whether a given cleartext and key could have produced a given cypertext. Ideally the IV is itself somehow variable, based, perhaps, on a serial number or some other text that's sent along with the cyphertext, or based on a counter that's synchronized between ends. The presence of the IV (even if semi-predictable) significantly increases the difficulty of using a "known cleartext" attack. This is especially important for relatively short, frequent messages.
Best way to implement 2-D array of series elements in Python Question: I have a dynamic set consisting of a data series on the order of hundreds of objects, where each series must be identified (by integer) and consists of elements, also identified by an integer. Each element is a custom class. I used a defaultdict to created a nested (2-D) dictionary. This enables me to quickly access a series and individual elements by key/ID. I needed to be able to add and delete elements and entire series, so the dict served me well. Also note that the IDs do not have to be sequential, due to add/delete. The IDs are important since they are unique and referenced elsewhere through my application. For example, consider the following data set with keys/IDs, [1][1,2,3,4,5] [2][1,4,10] [4][1] However, now I realize I want to be able to insert elements in a series, but the dictionary doesn't quite support it. For example, I'd like to be able to insert a new element between 3 and 4 for series 1, causing the IDs above it (from 4,5) to increment (to 5,6): [1][1,2,3,4,5] becomes [1][1,2,3,4(new),5,6] The order matters since the elements are part of a sequential series. I realize that this would be easier with a nested list since it supports insert(), but then I would be forced to iterate over the entire 2-D array to get element indices right? What would be the most optimal way to implement this data structure in Python? Answer: I think what you want is a dict with array values: dict = {1:[...],3:[...], ....} You can then operate on the arrays as you please. If the array values are sequential ints just use: dict[key].append(vals) dict[key].sort() Don't worry about the speed unless you find out it's a problem. Premature optimization is the root of all evil. In fact, don't even sort your dict vals until you have to, if you want to be really efficient.
Google App Engine static pages Python 2.5 directories etc Question: I am new at this and am planning to move my stuff from a paid web service to GAE (nothing dynamic just static pages). Believe me I have spent countless hours trying to make this work but am at an impasse whereby I achieve one result at the exclusion of another and visa versa. I am sure it is a simple answer and that I am violating some basic principles. What I want is that the app engine page (mygaeid.appspot.com) delivers a static landing page such that other pages are available with the addition of a suffix e.g. mygaeid.appspot.com/oranges.html mygaeid.appspot.com/grapes.html etc. I am unable to achieve this such that I either am able to get the other pages when I add the suffix e.g. mygaeid.appspot.com/apples.html; mygaeid.appspot.com/oranges.html but not the landing page OR with a slightly different yaml the landing page (mygaeid.appspot.com) works but there is no access to the other pages (mygaeid.appspot.com/oranges.html etc) that have a suffix. The py file (abcdefg.py) is below and is common to the two different yamls that follow: import os from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.ext.webapp import template class MainHandler(webapp.RequestHandler): def get (self, q): if q is None: q = 'htmdir/apples.html' path = os.path.join (os.path.dirname (__file__), q) self.response.headers ['Content-Type'] = 'text/html' self.response.out.write (template.render (path, {})) def main (): application = webapp.WSGIApplication ([('/(.*html)?', MainHandler)], debug=True) util.run_wsgi_app (application) if __name__ == '__main__': main () * * * Using the following yaml the landing page (mygaeid.appspot.com) works perfectly (delivering the content of apples.html), but I cannot access the page if I add a suffix e.g. mygaeid.appspot.com/apples.html or mygaeid.appspot.com/static/htmdir/apples.html etc, as soon as I add the suffix it does not work. In the directory (htmdir) I have placed apples.html along with other html pages e.g. oranges.html etc and I cannot access any of them with this yaml. application: mygaeid version: 1 runtime: python api_version: 1 handlers: - url: /(.*\.(html)) static_files: static/htmdir/\1 upload: static/htmdir/(.*\.(html)) - url: /css static_dir: css - url: /js static_dir: js - url: /images static_dir: images - url: .* script: abcdefg.py If I modify the yaml as follows then the landing page (mygaeid.appspot.com) does not work but when I add the suffixes then it works perfectly e.g. mygaeid.appspot.com/apples.html; mygaeid.appspot.com/oranges.html etc deliver the appropriate pages: - url: /(.*\.(html)) static_files: htmdir/\1 upload: htmdir/(.*\.(html)) Finally if I dispense with the directories altogether and using the same abcdefg.py (without the directory) the following very simple yaml actually delivers the results I want but is very unruly as all the files are stuffed in the root directory. application: mygaeid version: 1 runtime: python api_version: 1 handlers: - url: /(.*\.(png|js|css)) static_files: \1 upload: (.*\.(png|js|css)) - url: .* script: abcedfg.py any help would be much appreciated on figuring this out. thanks * * * thanks wooble and thanks dave I went back yet again and carefully read the logs Wooble's solution works but I needed to put the htmdir (that contains the html) inside a directory called static. GAE is a great (and free) solution for static websites your help and feedback is very much appreciated SiteDirectory -mygaeid -static -htmdir -js -css -images app.yaml index.yaml (py file was removed) Answer: If you declare files as static in app.yaml, they are not available to your application's handlers. However, if they're really static, using the django template engine to "render" them is kind of silly; just add mappings in app.yaml to display the static files, including one to display apples.html for /: application: mygaeid version: 1 runtime: python api_version: 1 handlers: - url: /(.*\.html) static_files: static/htmdir/\1 upload: static/htmdir/.*\.html - url: /css static_dir: css - url: /js static_dir: js - url: /images static_dir: images - url: / static_files: static/htmdir/apples.html upload: static/htmdir/apples\.html (no python files needed)
how to extract certain text from file? Question: i want to extract certain section of the text file. my input file: -- num cell port function safe [ccell disval rslt] "17 (BC_1, CLK, input, X)," & "16 (BC_1, OC_NEG, input, X), " &-- Merged input/ " 8 (BC_1, D(8), input, X)," & -- cell 16 @ 1 -> Hi-Z " 7 (BC_1, Q(1), output3, X, 16, 1, Z)," & " 0 (BC_1, Q(8), output3, X, 16, 1, Z)"; and i need the output to be as such: num cell port function safe ccell 17 BC_1 CLK input X 16 BC_1 OC_NEG input X 16 BC_1 * control 1 8 BC_1 D8 input X 7 BC_1 Q1 output3 X 16 1 0 BC_1 Q8 output3 X 16 1 so far i tried below code but it gave index error. pls advise. import re lines=open("input.txt",'r').readlines() for line in lines: a=re.findall(r'\w+',line) print re.findall(r'\w+',line) print a[0],a[1],a[2],a[3],a[4],a[5],a[6] i'm using python 2.6.6 and error as below: ['num', 'cell', 'port', 'function', 'safe', 'ccell', 'disval', 'rslt'] num cell port function safe ccell disval ['17', 'BC_1', 'CLK', 'input', 'X'] 17 BC_1 CLK input X Traceback (most recent call last): File "C:\Users\ctee1\Desktop\pyparsing\outputparser.py", line 39, in <module> print a[0],a[1],a[2],a[3],a[4],a[5],a[6] IndexError: list index out of range Answer: sed -r 's/(disval|rslt)//; s/(.)--.*/\1/; s/[^[:alnum:]_]//; s/ +$//'
Python's pretty printing of matrix Question: I have to print several rows of data and do it good. I can do it with C++ changing parameters of std::cout, but I can't understand how I can do it with Python. For example, I have this: row1 = [1, 'arc1.tgz', 'First', '15.02.1992'] row2 = [16, 'arc2modified.tgz', 'Second', 'today'] row3 = ['112', 'arc89.tgz', 'Corrupted', 'unknown'] I want to print text like this: 1 arc1.tgz First 15.02.1992 16 arc2modified.tgz Second today 112 arc89.tgz Corrupted unknown It seems that it would be a clever idea to put it in one list and then count symbols in each string and then add spaces, but I'd like to know if there is more clever way to do it. The main problem is that I can use only default Python's modules. Is there any possibility to do it? Thanks a lot! Answer: my_matrix = [row1, row2, row3] print "\n".join(["\t".join(map(str, r)) for r in my_matrix]) ETA: My original answer missed that you wanted each column to be of a fixed width, using padded spaces (rather than tabs). It also looks like you want exactly two spaces between the longest datum and the next column. In that case, it can be done as follows (note that **string** is a built-in, default Python module): import string max_lens = [max([len(str(r[i])) for r in my_matrix]) for i in range(len(my_matrix[0]))] print "\n".join(["".join([string.ljust(str(e), l + 2) for e, l in zip(r, max_lens)]) for r in my_matrix])
Change from re.findall(regex, text) to nltk.Text.findall(regex) Question: Using Python and the NLTK I have written a regex to find words with start with a capital letter in a body of text but aren't at the beginning of a sentence. Initially I was using it as follow: [w for w in text if re.findall(r'(?<!\.\s)\b[A-Z][a-z]\b',w)] the variable text is created using the treebank corpus as follows: >>> def concat(lists): biglist = [ ] while len(lists)>0: biglist = biglist+lists[0] lists=lists[1:] return biglist >>> tbsents = concat(treebank.sents()[200:250]) >>> text = nltk.Text(tbsents) However this doesn't seem to work, it still returns words that are at the beginning of sentences. So I thought I would try using the text.findall() function instead. I ran the following and it returned all the words with capital letters as required. >>> text.findall("<[A-Z][a-z]{3,}>") The problem I have is I don't how to get the first bit of the regex in to the <..> format required for the second function, and if I do will it even work or am I taking completely the wrong approach? Thanks. Answer: I'm not sure what you're doing with the first list comprehension: you're using findall on each individual word, _not_ on the text itself. The simplest way to do what you want with the treebank corpus, since you already have them divided by sentence, is: import itertools non_starting_words = list(itertools.chain(*[s[1:] for s in treebank.sents()])) uppercase_words = [w for w in non_starting_words if w[0].isupper()] Perhaps this is what you wanted to do with the "concat" function, but that just got a list of all words- it didn't remove the first of each sentence. If you do want to concatenate a list of lists, a much better way is the list(itertools.chain(*lists)) thing I did above. ETA: Given that you have to work with a list of tokens, the best solution is then not to use regexes but rather: punctuation_marks = ".!?" first_word = True uppercase_words = [] for w in text: if not first_word and re.match("[A-Z][a-z]*$", w): uppercase_words.append(w) first_word = w in punctuation_marks print uppercase_words
Linear interpolation using pycuda (lerp) Question: I am a recreational pythonista who just got into pyCUDA. I am trying to figure out how to implement a linear interpolation (lerp) using pyCUDA. The CUDA CG function is: <http://http.developer.nvidia.com/Cg/lerp.html> My ultimate goal is a bilinear interpolation in pycuda from a set of weighted random points. I've never programmed C, or CUDA for that matter, and am learning as I go. This is how far I've gotten: import pycuda.autoinit import pycuda.driver as drv import pycuda.compiler as comp lerpFunction = """__global__ float lerp(float a, float b, float w) { return a + w*(b-a); }""" mod = comp.SourceModule(lerpFunction) # This returns an error telling me a global must return a void. :( Any help on this would be fantastic! Answer: The error message is pretty explicit - CUDA kernels cannot return values, they must be declared `void`, and modifiable arguments passed as pointers. It would make more sense for your lerp implementation to be declared as a device function like this: __device__ float lerp(float a, float b, float w) { return a + w*(b-a); } and then called from inside a kernel for each value that requires interpolation. Your lerp function lacks a lot of "infrastructure" to be a useful CUDA kernel. * * * EDIT: A really basic kernel along the same lines might look something like this: __global__ void lerp_kernel(const float *a, const float *b, const float w, float *y) { int tid = threadIdx.x + blockIdx.x*blockDim.x; // unique thread number in the grid y[tid] = a[tid] + w*(b[tid]-a[tid]); }
Python CGI not executing on Mac OSX 10.6.7 Question: Recently I started reading Mark Lutz's "Programming Python - Fourth Edition". I am a mac user, using ActivePython and OSX 10.6.7. Anyways, everything was going fine until the first instance of CGI in the book. The code example creates a form, and uses a POST method for finding someone's name: <html> <title>Interactive Page</title> <body> <form method=POST action="cgi-bin/testing.cgi"> <p><b>Enter your name:</b> <p><input type="text" name="user"> <p><input type="submit"> </form> </body> </html> The CGI script is then put into a subdirectory, as shown in the HTML and looks like this: #!/usr/bin/python import cgi form = cgi.FieldStorage() print("Content-type: text/html\n") print("<title>Reply Page</title>" if not 'user' in form: print("<h1>Who are you?</h1>") else: print("<h1>Hello <i>%s</i>!</h1>" % cgi.escape(form['user'].value)) However when I load the html and run a test, the script does not execute. What occurs is that either the browser loads the entire script as Hypertext, or that I download a .py file; depending on the browser I use (Eclipse and Safari show me text, Chrome and Firefox download a file). If it means anything, when I open the .html file it opens using file:// and not http://. I'm not sure if this could be a problem with my script, or with a variety of other things. If anyone has any suggestions on executing python-based CGI on a mac that would be great. Answer: You need to configure and run a webserver, then access the file through that webserver with a url like <http://localhost:8080/cgi/foo.py>, and not the local path to the file.
Python - Multiple choice markup parsing Question: Consider this text: > Would you like to have responses to your questions sent to you via email ? I'm going to propose multiple choices for several words by marking up them like that: > Would you like [to get]|[having]|g[to have] responses to your questions sent > [up to]|g[to]|[on] you via email ? The choices are **bracketted** and separated by **pipes** The good choice is preceded by a **g** I would like to parse this sentence to get the text formatted like that: > Would you like __ responses to your questions sent __ you via email ? With a list like: [ [ {"to get":0}, {"having":0}, {"to have":1}, ], [ {"up to":0}, {"to":1}, {"on":0}, ], ] Is my markup design ok ? How to regex the sentence to get the needed result and generate the list ? **edit** : User oriented markup language needed Answer: I would add some grouping parentheses `{}`, and output not list of list of dicts, but list of dicts. Code: import re s = 'Would you like {[to get]|[having]|g[to have]} responses to your questions sent {[up to]|g[to]|[on]} you via email ?' def variants_to_dict(variants): dct = {} for is_good, s in variants: dct[s] = 1 if is_good == 'g' else 0 return dct def question_to_choices(s): choices_re = re.compile(r'{[^}]+}') variants_re = re.compile(r'''\|?(g?) \[ ([^\]]+) \] ''', re.VERBOSE) choices_list = [] for choices in choices_re.findall(s): choices_list.append(variants_to_dict(variants_re.findall(choices))) return choices_re.sub('___', s), choices_list question, choices = question_to_choices(s) print question print choices Output: Would you like ___ responses to your questions sent ___ you via email ? [{'to have': 1, 'to get': 0, 'having': 0}, {'to': 1, 'up to': 0, 'on': 0}]
heatmap using scatter dataset python matplotlib Question: I am writing a script to make a heatmap for scatter data on two dimensionS. The following is a toy example of what I am trying to do: import numpy as np from matplotlib.pyplot import* x = [1,2,3,4,5] y = [1,2,3,4,5] heatmap, xedges, yedges = np.histogram2d(x, y, bins=50) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] imshow(heatmap, extent = extent) I should expect a the 'warmest' areas to be along y=x but instead they show up along y=-x+5 i.e the heatmap reads one list in the reverse direction. I am not sure why this is happening. Any suggestions? Thanks Answer: Try the `imshow` parameter `origin=lower`. By default it sets the (0,0) element of the array in the upper left corner. For example: import numpy as np import matplotlib.pyplot as plt x = [1,2,3,4,5,5] y = [1,2,3,4,5,5] heatmap, xedges, yedges = np.histogram2d(x, y, bins=10) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] fig = plt.figure() ax1 = fig.add_subplot(211) ax1.imshow(heatmap, extent = extent) ax1.set_title("imshow Default"); ax2 = fig.add_subplot(212) ax2.imshow(heatmap, extent = extent,origin='lower') ax2.set_title("imshow origin='lower'"); fig.savefig('heatmap.png') Produces: ![enter image description here](http://i.stack.imgur.com/cDl5Q.png)
Gunicorn + Subprocesses raises exception [Errno 10] Question: I've stumbled across a weird exception I haven't been able to resolve... can anyone suggest what is wrong or a new design? I'm running a Gunicorn/Flask application. In the configuration file, I specify some work to do with an `on_starting` hook [1]. Inside that hook code, I have some code like this (nothing fancy): # Called before the server is started my_thread = package.MyThread() my_thread.start() The package.MyThread class looks like the following. The `ls` command is unimportant, it can be any command. class MyThread(threading.Thread): """ Run a command every 60 seconds. """ def __init__(self): threading.Thread.__init__(self) self.event = threading.Event() def run(self): while not self.event.is_set(): ptest = subprocess.Popen(["ls"], stdout=subprocess.PIPE) ptest.communicate() self.event.wait(60) def stop(self): self.event.set() Upon starting up the server, I'm always presented with this exception: Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib64/python2.6/threading.py", line 532, in __bootstrap_inner self.run() File "__init__.py", line 195, in run ptest.communicate() File "/usr/lib64/python2.6/subprocess.py", line 721, in communicate self.wait() File "/usr/lib64/python2.6/subprocess.py", line 1288, in wait pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0) File "/usr/lib64/python2.6/subprocess.py", line 462, in _eintr_retry_call return func(*args) OSError: [Errno 10] No child processes Can anyone suggest what is going on here? I haven't tried implementing the changes in [2], they seemed hacky. [1] - <http://gunicorn.org/configure.html#server-hooks> [2] - [Popen.communicate() throws OSError: "[Errno 10] No child processes"](http://stackoverflow.com/questions/1008858/popen-communicate- throws-oserror-errno-10-no-child-processes) Answer: The error turns out to be related to signal handling of `SIGCHLD`. The `gunicorn` arbiter intercepts `SIGCHLD`, which breaks `subprocess.Popen`. The `subprocess.Popen` module requires that `SIGCHLD` not be intercepted (at least, this is true for Python 2.6 and earlier). According to [bugs.python.org](http://bugs.python.org/issue9127) this bug has been fixed in Python 2.7.
How to create a query for matching keys? Question: I use the key of another User, the sponsor, to indicate who is the sponsor of a User and it creates a link in the datastore for those Users that have a sponsor and it can be at most one but a sponsor can sponsor many users like in this case ID 2002 who sponsored three other users: ![enter image description here](http://i.stack.imgur.com/76Mwj.png) In this case this query does what I want: `SELECT * FROM User where sponsor =KEY('agtzfmJuYW5vLXd3d3ILCxIEVXNlchjSDww')` but I don't know how to program that with python, I can only use it to the datastore. How can I query by key when I want to match the set of users who has the same user as key in the same field? A user in my model can have at most one sponsor and I just want to know who a particular person sponsored which could be a list of users and then they sponsored users in their turn which I also want to query on. The field sponsor is a key and it has a link to the sponsor in the datastore. I set the key just like user2.sponsor = user1.key and now I want to find all that user1 sponsored with a query that should be just like `User.All().filter('sponsor = ', user1.key)` but sponsor is a field of type key so I don't know how to match it to see for example a list a people the active user is a sponsor for and how it becomes a tree when the second generation also have links. How to select the list of users this user is a sponsor for and then the second generation? When i modelled the relation simply like u1=u2.key ie user2.sponsor=user1.key. Thanks for any hint The following workaround is bad practice but is my last and only resort: def get(self): auser = self.auth.get_user_by_session() realuser = auth_models.User.get_by_id(long( auser['user_id'] )) q = auth_models.User.query() people = [] for p in q: try: if p.sponsor == realuser.key: people.append(p) except Exception, e: pass if auser: self.render_jinja('my_organization.html', people=people, user=realuser,) ## Update The issues are that the keyproperty is not required and that Guido Van Rossum has reported this as a bug in the ndb when I think it's a bug in my code. Here's what I'm using now, which is a very acceptable solution since every real user in the organization except possibly programmers, testers and admins are going the be required to have a sponsor ID which is a user ID. from ndb import query class Myorg(NewBaseHandler): @user_required def get(self): user = auth_models.User.get_by_id(long(self.auth.get_user_by_session()['user_id'])) people = auth_models.User.query(auth_models.User.sponsor == user.key).fetch() self.render_jinja('my_organization.html', people=people, user=user) class User(model.Expando): """Stores user authentication credentials or authorization ids.""" #: The model used to ensure uniqueness. unique_model = Unique #: The model used to store tokens. token_model = UserToken sponsor = KeyProperty() created = model.DateTimeProperty(auto_now_add=True) updated = model.DateTimeProperty(auto_now=True) # ID for third party authentication, e.g. 'google:username'. UNIQUE. auth_ids = model.StringProperty(repeated=True) # Hashed password. Not required because third party authentication # doesn't use password. password = model.StringProperty() ... Answer: The User model is an NDB Expando which is a little bit tricky to query. From the [docs](https://docs.google.com/document/d/1dsx1hihmMXMJm8wIRu49tJR- KEng80o3wkg4Nlbqn-w/edit?hl=en_US#heading=h.j07awmd5m00o) > Another useful trick is querying an Expando kind for a dynamic property. You > won't be able to use class.query(class.propname == value) as the class > doesn't have a property object. Instead, you can use the > ndb.query.FilterNode class to construct a filter expression, as follows: from ndb import model, query class X(model.Expando): @classmethod def query_for(cls, name, value): return cls.query(query.FilterNode(name, '=', value)) print X.query_for('blah', 42).fetch() So try: form ndb import query def get(self): auser = self.auth.get_user_by_session() realuser = auth_models.User.get_by_id(long( auser['user_id'] )) people = auth_models.User.query(query.FilterNode('sponsor', '=', realuser.key)).fetch() if auser: self.render_jinja('my_organization.html', people=people, user=realuser,)
Unresolved import csv Pydev Eclipse Question: I have a love-hate relationship with Pydev on Eclipse. For some reason it is now telling me that it has an unresolved import on the code: import csv Traceback (most recent call last): File "/Users/peterstannett/Documents/Programming/python/eclipse/workspace/myFirstPydev/csv.py", line 1, in <module> import csv File "/Users/peterstannett/Documents/Programming/python/eclipse/workspace/myFirstPydev/csv.py", line 3, in <module> cr = csv.reader(f) AttributeError: 'module' object has no attribute 'reader' It was working fine a few days ago I'm sure! So I started to look at the interpreter and the path where the csv.py file should be and I can see in the System PYTHONPATH that it has the /lib/python2.7 where the csv.py file is held yet I still get an error. ![enter image description here](http://i.stack.imgur.com/enLMu.png) Would someone please help me resolve this as it is most frustrating! Thanks Answer: Since your file is called `csv.py`, it is found before the csv module from the standard library when you `import csv`. Rename your file to something like `myCsv.py` to resolve the ambiguity.
wxpython: Multiple panels Question: I'm new to wxpython so bare with me. I'm having two problems with my program. The code below generates two panels when it should generate 3. It generates `panel1` and `panel2` no problem but `panel3` should be to the right of `panel2` is no where to be seen. `Panel1` and `panel2` are split vertically I'm trying to do the same with `panel2` and `panel3` My second problem is how do I generate another panel below `panel1` without disrupting the splitter between `panel1` and `panel2` and then create a splitter between `panel1` and new created panel below it? import wx class Panels(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title) hbox = wx.BoxSizer(wx.HORIZONTAL) splitter = wx.SplitterWindow(self, -1) vbox1 = wx.BoxSizer(wx.VERTICAL) panel1 = wx.Panel(splitter, -1) panel12 = wx.Panel(panel1, -1, style=wx.BORDER_SUNKEN) st1 = wx.StaticText(panel12, -1, 'Panel 1', (5, 5)) vbox1.Add(panel12, 1, wx.EXPAND) panel1.SetSizer(vbox1) vbox2 = wx.BoxSizer(wx.VERTICAL) panel2 = wx.Panel(splitter, -1) panel22 = wx.Panel(panel2, -1, style=wx.BORDER_RAISED) st2 = wx.StaticText(panel22, -1, 'Panel 2', (5, 5)) vbox2.Add(panel22, 1, wx.EXPAND) panel2.SetSizer(vbox2) vbox3 = wx.BoxSizer(wx.VERTICAL) panel3 = wx.Panel(splitter, -1) panel32 = wx.Panel(panel3, -1, style=wx.BORDER_RAISED) st3 = wx.StaticText(panel32, -1, 'Panel 3', (5, 5)) vbox3.Add(panel32, 1, wx.EXPAND) panel3.SetSizer(vbox3) hbox.Add(splitter, 1, wx.EXPAND | wx.TOP | wx.BOTTOM, 5) self.SetSizer(hbox) self.CreateStatusBar() splitter.SplitVertically(panel1, panel3) splitter.SplitVertically(panel2, panel3) self.Centre() self.Show(True) def ExitApp(self, event): self.Close() app = wx.App() Panels(None, -1, 'Panels') app.MainLoop() Answer: You have a couple options. You could nest your SplitterWindows, which is kind of confusing, but effective. Or you could use the MultiSplitterWindow widget. For the first one, I'd do something like this: 1. Create a main splitter and a sub-splitter 2. In the sub-splitter, but the first two panels 3. Put the sub-splitter and the 3rd panel in the main splitter Or some variation thereof. EDIT: Here's one example: import wx ######################################################################## class RandomPanel(wx.Panel): """""" #---------------------------------------------------------------------- def __init__(self, parent, color): """Constructor""" wx.Panel.__init__(self, parent) self.SetBackgroundColour(color) ######################################################################## class MainPanel(wx.Panel): """""" #---------------------------------------------------------------------- def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent) topSplitter = wx.SplitterWindow(self) hSplitter = wx.SplitterWindow(topSplitter) panelOne = RandomPanel(hSplitter, "blue") panelTwo = RandomPanel(hSplitter, "red") hSplitter.SplitVertically(panelOne, panelTwo) hSplitter.SetSashGravity(0.5) panelThree = RandomPanel(topSplitter, "green") topSplitter.SplitHorizontally(hSplitter, panelThree) topSplitter.SetSashGravity(0.5) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(topSplitter, 1, wx.EXPAND) self.SetSizer(sizer) ######################################################################## class MainFrame(wx.Frame): """""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" wx.Frame.__init__(self, None, title="Nested Splitters", size=(800,600)) panel = MainPanel(self) self.Show() #---------------------------------------------------------------------- if __name__ == "__main__": app = wx.App(False) frame = MainFrame() app.MainLoop() See also might want to look at wx.SashLayoutWindow: <http://www.wxpython.org/docs/api/wx.SashLayoutWindow-class.html>
using Mysql and SqlAlchemy in Pyramid Framework Question: Pyramid Framework comes with a sample tutorial of sql alchemy that uses sqlite. The problem is that i want to use mysql so i change this sqlalchemy.url = sqlite:///%(here)s/tutorial.db Into this sqlalchemy.url = mysql://root:22password@localhost/alchemy when i try to run ../bin/pserve development.ini --reload It gives me the following error File "build/bdist.linux-i686/egg/sqlalchemy/connectors/mysqldb.py", line 52, in dbapi ImportError: No module named MySQLdb I understand that i should include the dependecies of my app in setup.py but i don't know what to include right now some help please my setup.py looks like this import os import sys from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() requires = [ 'pyramid', 'SQLAlchemy', 'transaction', 'pyramid_tm', 'pyramid_debugtoolbar', 'zope.sqlalchemy', ] if sys.version_info[:3] < (2,5,0): requires.append('pysqlite') setup(name='tutorial', version='0.0', description='tutorial', long_description=README + '\n\n' + CHANGES, classifiers=[ "Programming Language :: Python", "Framework :: Pylons", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='', author_email='', url='', keywords='web wsgi bfg pylons pyramid', packages=find_packages(), include_package_data=True, zip_safe=False, test_suite='tutorial', install_requires = requires, entry_points = """\ [paste.app_factory] main = tutorial:main [console_scripts] populate_tutorial = tutorial.scripts.populate:main """, ) Answer: Try adding `"MySQLdb"` to the requires list. It was fine with sqlite3 as that comes with python (as of version 2.5), MySQLdb doesn't and needs to be installed separately. UPDATE: Try `"mysql-python"` in the requires list instead.
How do you make a sprite appear in pygame/python? Question: I'm trying to make a basic (Mario style) game but my sprite(plumber) doesn't appear, it could be hidden behind background? i'm not exactly sure, i am not getting any errors either. import pygame import sys import itertools import pygame from pygame.sprite import Sprite cloud_background = pygame.image.load('clouds.bmp') brick_tile = pygame.image.load('brick_tile.png') pink = (255, 64, 64) w = 640 h = 480 screen = pygame.display.set_mode((w, h)) running = 1 def setup_background(): screen.fill((pink)) screen.blit(cloud_background,(0,0)) brick_width, brick_height = brick_tile.get_width(), brick_tile.get_height() for x,y in itertools.product(range(0,640,brick_width), range(390,480,brick_height)): # print(x,y) screen.blit(brick_tile, (x, y)) pygame.display.flip() while running: setup_background() event = pygame.event.poll() if event.type == pygame.QUIT: sys.exit() class plumber(sprite): def __init__( self, screen, img_filename, init_position, init_direction, speed): Sprite.__init__(self) self.screen = screen self.speed = speed self.base_image = pygame.image.load(Mario_sideways_sprite_2xL.png).convert_alpha() self.image = self.base_image self.pos = 50,50 Answer: First problem found is that you must modify pygame.image.load(Mario_sideways_sprite_2xL.png) with something like. pygame.image.load("Mario_sideways_sprite_2xL.png") Besides this, the code has many problems that impedes it to work. For example, * **you do not instantiate your plumber class**. * `class plumber(sprite)` should be `plumber(Sprite)` (still better `Plumber(Sprite)`) You need something like: myplumber = Plumber() allsprites = pygame.sprite.RenderPlain((myplumber, ....)) clock = pygame.time.Clock() You could see [here](http://pygame.org/docs/tut/chimp/ChimpLineByLine.html) the main parts of a simple program like yours.
Python: Using itertools to get previous, current, and next item in list from text file Question: I have setup my code as outlined in [this answer](http://stackoverflow.com/a/1012089/571600) (shown below): from itertools import tee, islice, chain, izip def previous_and_next(some_iterable): prevs, items, nexts = tee(some_iterable, 3) prevs = chain([None], prevs) nexts = chain(islice(nexts, 1, None), [None]) return izip(prevs, items, nexts) x = open('out2.txt','r') lines = x.readlines() for previous, item, next in previous_and_next(lines): print "Current: ", item , "Next: ", next, "Previous: ", previous if item == '0': print "root" elif item == '2': print "doc" else: print "none" x.close() `out2.txt` looks like this: 0 2 4 6 8 10 This code works fine when using something like `list = [0,2,4,6,8,10]` but not when using the lines of a text file into a list. How can I use the lines of a text file as a list. Isn't `x.readlines()` doing this? Ultimately I need to be able to print output depending on the `item, next, and previous` results. Current output is: Current: 0 Next: 2 Previous: None none Current: 2 Next: 4 Previous: 0 none Current: 4 Next: 6 Previous: 2 none Current: 6 Next: 8 Previous: 4 none Current: 8 Next: 10 Previous: 6 none Current: 10 Next: None Previous: 8 none Desired output should be: Current: 0 Next: 2 Previous: None **root** Current: 2 Next: 4 Previous: 0 **doc** none Current: 4 Next: 6 Previous: 2 none Current: 6 Next: 8 Previous: 4 none Current: 8 Next: 10 Previous: 6 none Current: 10 Next: None Previous: 8 none Answer: The `readlines()` method of a file object returns a list of the lines of the file _including the newline characters_. Your checks compare with strings not including newline characters, so they always fail. One way of getting rid of the newline characters is lines = (line.strip() for line in open("out2.txt")) (Note that you don't need `readlines()` \-- you can directly iterate over the file object itself.)
Draw simple shapes and save to file (pdf) Question: I am looking for a python library that I can use to draw simple shapes and characters and then save to a file (in a format convertible to pdf). I would prefer if I did not need an X-server running. E.g. could look something like this import drawing_lib obj = drawing_lib.Object() for i in range(5): obj.draw_line(from=(i*10, 20), to=(i*10+10, 35)) obj.save_pdf('five_inclined_lines.pdf') Any Ideas? Answer: You can do this with cairo. import math,cairo width, height = 768,768 surface = cairo.PDFSurface ("circle.pdf", width, height) ctx = cairo.Context (surface) ctx.set_source_rgb(1,1,1) ctx.rectangle(0,0,width,height) ctx.fill() ctx.set_source_rgb(1,0,0) ctx.move_to(width/2,height/2) ctx.arc(width/2,height/2,512*0.25,0,math.pi*2) ctx.fill() ctx.show_page() See also: * <http://www.tortall.net/mu/wiki/CairoTutorial> * [What is a good PDF report generator tool for python?](http://stackoverflow.com/questions/177799/what-is-a-good-pdf-report-generator-tool-for-python)
Internal Python ID for first field in database Question: The following is part of my python script: gp.CalculateField_management("parcs", "Apn", "[oldApnfield]") The problem is that the field I am calculating from is going to be named something different in each shapefile, so I can't use the field name in the calculation. Is there an internal ID that python uses to identify fields ? What is the python language for saying "the first field in the database" instead of using the field name ? Thanks for the help. I am very close, but now the calculation results with each row in the new field being PIDNUM instead of the value of PIDNUM..... import arcgisscripting # Create the geoprocessor object gp = arcgisscripting.create(9.3) gp.OverWriteOutput = True # Set the workspace. List all of the folders within gp.Workspace = "C:\ZP44" fcs = gp.ListWorkspaces("*","Folder") # for fc in fcs: print fc gp.MakeFeatureLayer(fc + "\\Parcels.shp", "parcs") fieldList = gp.ListFields("parcs") print fieldList[2].Name field1 = fieldList[2].Name print field1 gp.CalculateField_management("parcs", "Apn", "[field1]") Answer: You could use [`ListFields`](http://webhelp.esri.com/arcgisdesktop/9.2/index.cfm?id=830&pid=785&topicname=ListFields%20method&) to get the name of the field each time.
Neighbourhood of Scipy Labels Question: I've got an array of objects labeled with `scipy.ndimage.measurements.label` called `Labels`. I've got other array `Data` containing stuff related to `Labels`. How can I make a third array `Neighbourhoods` which could serve to map **the nearest label to _x,y_ is _L_** Given `Labels` and `Data`, how can I use python/numpy/scipy to get `Neighbourhoods`? Labels = array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 2, 2, 2, 0], [0, 0, 0, 0, 0, 0, 2, 2, 2, 0], [0, 0, 0, 0, 0, 0, 2, 2, 2, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ) Data = array([[1, 1, 1, 1, 1, 1, 2, 3, 4, 5], [1, 0, 0, 0, 0, 1, 2, 3, 4, 5], [1, 0, 0, 0, 0, 1, 2, 3, 4, 4], [1, 0, 0, 0, 0, 1, 2, 3, 3, 3], [1, 0, 0, 0, 0, 1, 2, 2, 2, 2], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 1, 0, 0, 0, 1], [3, 3, 3, 3, 2, 1, 0, 0, 0, 1], [4, 4, 4, 3, 2, 1, 0, 0, 0, 1], [5, 5, 4, 3, 2, 1, 1, 1, 1, 1]] ) Neighbourhoods = array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 1, 1, 1, 0, 2], [1, 0, 0, 0, 0, 1, 1, 0, 2, 2], [1, 0, 0, 0, 0, 1, 0, 2, 2, 2], [1, 1, 1, 1, 1, 0, 2, 2, 2, 2], [1, 1, 1, 1, 0, 2, 0, 0, 0, 2], [1, 1, 1, 0, 2, 2, 0, 0, 0, 2], [1, 1, 0, 2, 2, 2, 0, 0, 0, 2], [1, 1, 2, 2, 2, 2, 2, 2, 2, 2]] ) Note: I'm not sure what should happen with ties, so used zeros in the above `Neighbourhoods` Answer: As suggested by David Zaslavsky, this is the job for a voroni diagram. Here is a numpy implementation: <http://blancosilva.wordpress.com/2010/12/15/image- processing-with-numpy-scipy-and-matplotlibs-in-sage/> The relevant function is `scipy.ndimage.distance_transform_edt`. It has a `return_indices` option that can be exploited to do what you need (as well as calculate the raw distances (`data` in your example)). As an example: import numpy as np from scipy.ndimage import distance_transform_edt labels = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 2, 2, 2, 0], [0, 0, 0, 0, 0, 0, 2, 2, 2, 0], [0, 0, 0, 0, 0, 0, 2, 2, 2, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ) i, j = distance_transform_edt(labels == 0, return_distances=False, return_indices=True) neighborhoods = labels[i,j] print neighborhoods This yields: array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1, 1, 1, 2, 2], [1, 1, 1, 1, 1, 1, 1, 2, 2, 2], [1, 1, 1, 1, 1, 1, 2, 2, 2, 2], [1, 1, 1, 1, 1, 2, 2, 2, 2, 2], [1, 1, 1, 1, 2, 2, 2, 2, 2, 2], [1, 1, 1, 2, 2, 2, 2, 2, 2, 2], [1, 1, 2, 2, 2, 2, 2, 2, 2, 2]])
Algorithm to extract network info from ifconfig (ubuntu) Question: Im trying to parse info from ifconfig (ubuntu). Normally, I would split a chunk of data like this down into words, and then search for substrings to get what I want. For example, given `line = "inet addr:192.168.98.157 Bcast:192.168.98.255 Mask:255.255.255.0"`, and looking for the broadcast address, I would do: for word in line.split(): if word.startswith('Bcast'): print word.split(':')[-1] >>>192.168.98.255 However, I feel its about time to start learning how to use regular expressions for tasks like this. Here is my code so far. I've hacked through a couple of patterns (inet addr, Bcast, Mask). Questions after code... # git clone git://gist.github.com/1586034.git gist-1586034 import re import json ifconfig = """ eth0 Link encap:Ethernet HWaddr 08:00:27:3a:ab:47 inet addr:192.168.98.157 Bcast:192.168.98.255 Mask:255.255.255.0 inet6 addr: fe80::a00:27ff:fe3a:ab47/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:189059 errors:0 dropped:0 overruns:0 frame:0 TX packets:104380 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:74213981 (74.2 MB) TX bytes:15350131 (15.3 MB)\n\n lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:389611 errors:0 dropped:0 overruns:0 frame:0 TX packets:389611 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:81962238 (81.9 MB) TX bytes:81962238 (81.9 MB) """ for paragraph in ifconfig.split('\n\n'): info = { 'eth_port': '', 'ip_address': '', 'broadcast_address': '', 'mac_address': '', 'net_mask': '', 'up': False, 'running': False, 'broadcast': False, 'multicast': False, } if 'BROADCAST' in paragraph: info['broadcast'] = True if 'MULTICAST' in paragraph: info['multicast'] = True if 'UP' in paragraph: info['up'] = True if 'RUNNING' in paragraph: info['running'] = True ip = re.search( r'inet addr:[^\s]+', paragraph ) if ip: info['ip_address'] = ip.group().split(':')[-1] bcast = re.search( r'Bcast:[^\s]+', paragraph ) if bcast: info['broadcast_address'] = bcast.group().split(':')[-1] mask = re.search( r'Mask:[^\s]+', paragraph ) if mask: info['net_mask'] = mask.group().split(':')[-1] print paragraph print json.dumps(info, indent=4) Here're my questions: 1. Am I taking the best approach for the patterns I have already implemented? Can I grab the addresses without splitting on ':' and then choosing the last of the array.? 2. I'm stuck on HWaddr. What would be a pattern to match this mac address? EDIT: Ok, so here's how I ended up going about this. I started out trying to go about this without the regex... just manipulating stings and lists. But that proved to be a nightmare. For example, what separates `HWaddr` from its address is a `space`. Now take `inet addr` its separated from its address by `:`. Its a total bitch to scrape with differing separators like this. Not only a bitch to code but also a bitch to read. So, I did this with regex. I think this makes a strong case for when to use regular expressions. # git clone git://gist.github.com/1586034.git gist-1586034 # USAGE: pipe ifconfig into script. ie "ifconfig | python pyifconfig.py" # output is a list of json datastructures import sys import re import json ifconfig = sys.stdin.read() print 'STARTINPUT' print ifconfig print 'ENDINPUT' def extract(input): mo = re.search(r'^(?P<interface>eth\d+|eth\d+:\d+)\s+' + r'Link encap:(?P<link_encap>\S+)\s+' + r'(HWaddr\s+(?P<hardware_address>\S+))?' + r'(\s+inet addr:(?P<ip_address>\S+))?' + r'(\s+Bcast:(?P<broadcast_address>\S+)\s+)?' + r'(Mask:(?P<net_mask>\S+)\s+)?', input, re.MULTILINE ) if mo: info = mo.groupdict('') info['running'] = False info['up'] = False info['multicast'] = False info['broadcast'] = False if 'RUNNING' in input: info['running'] = True if 'UP' in input: info['up'] = True if 'BROADCAST' in input: info['broadcast'] = True if 'MULTICAST' in input: info['multicast'] = True return info return {} interfaces = [ extract(interface) for interface in ifconfig.split('\n\n') if interface.strip() ] print json.dumps(interfaces, indent=4) Answer: Rather than reinventing the wheel: * <https://pypi.python.org/pypi/python-ifconfig/0.1> Or if you want a portable-ish version that works on multiple platforms.. * <https://pypi.python.org/pypi/netifaces/>
Control loop for a number-guessing game in Python Question: I'm trying to write a program which generates a pseudo-random number and allows the user to guess it. When the user guesses the number wrong, as is most likely, I would like the function to return to the beginning of the conditional loop, not the very beginning of the function (which would cause it to generate a new pseudo-random number). Here's what I have so far: def guessingGame(): import random n = random.random() input = raw_input("Guess what integer I'm thinking of.") if int(input) == n: print "Correct!" elif int(input) < n: print "Too low." guessingGame() elif int(input) > n: print "Too high." guessingGame() else: print "Huh?" guessingGame() How could make the pseudo-random number locally immutable so that after a wrong guess the number would not change? Answer: Although looping here is probably the better way to do this, here is how you can implement it recursively with a very minimal change to your code: def guessingGame(n=None): if n is None: import random n = random.randint(1, 10) input = raw_input("Guess what integer I'm thinking of.") if int(input) == n: print "Correct!" elif int(input) < n: print "Too low." guessingGame(n) elif int(input) > n: print "Too high." guessingGame(n) else: print "Huh?" guessingGame(n) By providing an optional parameter to `guessingGame()` you can get the behavior you want. If a parameter is not provided it is the initial call and you need to randomly choose `n`, any time after the current `n` is passed into the call so you don't create a new one. Note that the call to `random()` was replaced with `randint()`, since `random()` returns a float between 0 and 1 and your code appears to expect and integer.
Optimizing matplotlib pyplot: plotting for many small plots Question: I want to make a movie of some plotted points moving around for a rudimentary traffic simulation. Plotting takes forever, though--~10 frames takes 7s!! What's up with that? Python code: import numpy as np import matplotlib.pyplot as plt import cProfile def slowww_plot(): for i in range(10): plt.plot(0, 0, 'bo') plt.savefig('%03i.png' % i) plt.clf() plt.plot(0, 0, 'ro') plt.savefig('%03i.png' % (i+1)) plt.clf() cProfile.run('slowww_plot()', sort = 'cumulative' produces In [35]: %run test.py 2035814 function calls (2011194 primitive calls) in 7.322 seconds Ordered by: cumulative time ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 7.322 7.322 <string>:1(<module>) 1 0.000 0.000 7.322 7.322 test.py:5(slowww_plot) 40 0.006 0.000 3.615 0.090 axes.py:821(cla) 1440/1120 0.044 0.000 3.278 0.003 axis.py:62(__init__) 20 0.000 0.000 3.049 0.152 pyplot.py:468(savefig) 20 0.000 0.000 3.049 0.152 figure.py:1077(savefig) 20 0.001 0.000 3.048 0.152 backend_bases.py:1892(print_figure) 520/360 0.015 0.000 2.523 0.007 axis.py:697(cla) 20 0.010 0.001 2.506 0.125 backend_bases.py:1791(print_png) 20 0.003 0.000 2.495 0.125 backend_agg.py:444(print_png) 520/360 0.006 0.000 2.475 0.007 axis.py:732(reset_ticks) 4340 0.172 0.000 2.373 0.001 lines.py:128(__init__) 20 0.000 0.000 2.198 0.110 pyplot.py:2449(plot) 20 0.000 0.000 2.149 0.107 pyplot.py:683(gca) 20 0.000 0.000 2.149 0.107 figure.py:1030(gca) 20 0.001 0.000 2.149 0.107 figure.py:710(add_subplot) 20 0.000 0.000 2.146 0.107 axes.py:8327(__init__) 20 0.002 0.000 2.139 0.107 axes.py:359(__init__) 20 0.000 0.000 2.075 0.104 pyplot.py:439(clf) 20 0.001 0.000 2.074 0.104 figure.py:782(clf) 20240 0.189 0.000 1.941 0.000 markers.py:114(_recache) 720/560 0.003 0.000 1.720 0.003 axis.py:1803(_get_tick) 80 0.002 0.000 1.600 0.020 axis.py:830(set_clip_path) 160 0.000 0.000 1.592 0.010 spines.py:153(cla) 720/560 0.003 0.000 1.564 0.003 axis.py:1543(_get_tick) 120 0.004 0.000 1.278 0.011 axis.py:1183(get_major_ticks) 20 1.267 0.063 1.267 0.063 {built-in method write_png} 20 0.000 0.000 1.224 0.061 backend_agg.py:394(draw) 1520/20 0.013 0.000 1.200 0.060 artist.py:53(draw_wrapper) 20 0.002 0.000 1.199 0.060 figure.py:815(draw) 20 0.002 0.000 1.175 0.059 axes.py:1866(draw) 40 0.002 0.000 1.100 0.028 axis.py:1029(draw) 10120 0.017 0.000 1.078 0.000 markers.py:132(set_fillstyle) 5780 0.013 0.000 1.032 0.000 markers.py:109(__init__) How can I optimize this? I've tried using the `PdfPages` backend and switching from the stateful wrapper to just using `Axis.plot` but everything is still slow. Answer: You're doing it very inefficiently if you want an animation. Instead of making a new figure each time, just set the new data and redraw the existing figure. For example: import matplotlib.pyplot as plt import numpy as np xy = 100 * np.random.random((2,10)) x, y = xy fig, ax = plt.subplots() points, = ax.plot(x, y, 'bo') for i in range(10): xy += np.random.random(xy.shape) - 0.5 points.set_data(xy) fig.savefig('%03i.png' % i)
Python unittest issue Question: I have a unittest script in a 'tests' directory which I execute like: $ python3 -m unittest mainmodule.tests, the entire class is a super simple one, has an assertEquals(1, 1), the script runs, but it says: 0 tests ran in 0.000 seconds .... OK. No matter how I run the script (from console or via itnerpreter etc). I'm using python 3.1.2 Ideas? Edit: the method starts with 'test'. Answer: I guess your package structure should be something like this: $ tree mainmodule mainmodule/ |--__init__.py |--file1.py |--file2.py |--tests | |--__init__.py | |--test_file1.py In which case you should run: $ python3 -m unittest mainmodule.tests.test_file1 or simply: $ python3 -m unittest and see what output comes out. **Note:** If you're not using relative imports in your test file, you can always add at the end of it something like: if __name__ == '__main__': unittest.main() and then run `$ python3 test_file1.py` to test your code. See the [unittest documentation](http://docs.python.org/release/3.1.2/library/unittest.html) for examples.