text
stringlengths
226
34.5k
Why does this Python Flask router return a 400 error when pinged by a crossdomain AJAX call? Question: I have the below Python Flask router: @app.route('/create', methods=['GET', 'POST']) @crossdomain(origin='*') def create(): if request.method == 'POST': print(request.form) title = request.form['title'] url = request.form['url'] new_mark = Mark( title=title, url=url ) new_mark.save() return new_mark When I do an ajax call (below) it responds with a 400 error. $.ajax({ type: 'POST', url: 'http://localhost:5000/create', data: { 'title': sender.title, 'url': sender.url }, xhrFields: { withCredentials: true }, dataType: 'json' }); When I try printing out `request` it prints an empty `immutableMultiDict`. Any idea why it is giving this 400 and why there is no data? Answer: Your ajax call is sending json-encoded data. I guess you should decode. import json data = json.loads(request.data) print data.get("title")
Writing a Python list of lists to a csv file Question: I have a long list of lists of the following form --- a = [[1.2,'abc',3],[1.2,'werew',4],........,[1.4,'qew',2]] i.e. the values in the list are of different types -- float,int, strings.How do I write it into a csv file so that my output csv file looks like 1.2,abc,3 1.2,werew,4 . . . 1.4,qew,2 Answer: Python's built-in [CSV module](http://docs.python.org/2/library/csv.html) can handle this easily: import csv with open("output.csv", "wb") as f: writer = csv.writer(f) writer.writerows(a) This assumes your list is defined as `a`, as it is in your question. You can tweak the exact format of the output CSV via the various optional parameters to `csv.writer()` as documented in the library reference page linked above.
Python Introspection: Defining dynamic class methods during runtime Question: I'm trying to create a unit test, that checks that every function in `mymodule` has its own `TestCase` instance. To reduce boiler-plate code and manual effort I wanted to use introspection/reflection to dynamically add `lambda` functions as class methods to the initially empty class `Test_TestCases`. The following code kind of works - it does indeed add lambdas as class methods and `unittest.main()` finds and correctly calls them. import unittest from unittest import TestCase import mymodule class Test_TestCases(TestCase): """Class whose test_* methods will be created during runtime.""" pass ################################################################################ if __name__ == "__main__": for item in dir(mymodule): attr = getattr(pws, item) if callable(attr): testname = "Test_%s" % item setattr(Test_TestCases, "test_%s_is_tested" % item, lambda self: self.assertTrue(testname in globals()) and issubclass(getattr(globals(), testname), TestCase)) unittest.main() The problem is, that all tests succeed even though I do have untested functions in my unit test module. After a little trying around I figured out that the variable `testname` has the same value every time the `lambda` is called. I could minimize the problem to this piece of code for reproducability: lambdas = [] for i in range(5): lambdas.append(lambda: str(i)) print ", ".join(f() for f in lambdas) I'd expect this output: 0, 1, 2, 3, 4 but instead I get: 4, 4, 4, 4, 4 It seems that the lambdas are initialized lazily. Could anyone please explain this behaviour or give me a hint on how I would accomplish my goal properly? Thanks in advance Answer: Shadow `testname` with another wrapper function: def assertion(testname=testname): def function(self): return self.assertTrue(testname in globals()) and issubclass(getattr(globals(), testname), TestCase)) return function setattr(Test_TestCases, "test_%s_is_tested" % item, assertion())
using cx_freeze on flask app Question: I am using Flask to develop a python app. At the moment, I want this app to be run locally. It runs locally fine through python, but when I use cx_freeze to turn it into an exe for Windows, I can no longer use the Flask.render_template() method. The moment I try to execute a render_template, I get an http 500 error, exactly as if the html template I'm trying to render does not exist. The main python file is called index.py. At first I tried to run: `cxfreeze index.py`. This did not include the "templates" directory from the Flask project in the cxfreeze "dist" directory. So then I tried using this setup.py script and running `python setup.py build`. This now includes the templates folder and the index.html template, but I still get the http: 500 error when it tries to render the template. from cx_Freeze import setup,Executable includefiles = [ 'templates\index.html'] includes = [] excludes = ['Tkinter'] setup( name = 'index', version = '0.1', description = 'membership app', author = 'Me', author_email = '[email protected]', options = {'build_exe': {'excludes':excludes,'include_files':includefiles}}, executables = [Executable('index.py')] ) Here is an example method from the script: @app.route('/index', methods=['GET']) def index(): print "rendering index" return render_template("index.html") If I run `index.py` then in the console I get: * Running on http://0.0.0.0:5000/ rendering index 127.0.0.1 - - [26/Dec/2012 15:26:41] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [26/Dec/2012 15:26:42] "GET /favicon.ico HTTP/1.1" 404 - and the page is displayed correctly in my browser, but if I run `index.exe`, I get * Running on http://0.0.0.0:5000/ rendering index 127.0.0.1 - - [26/Dec/2012 15:30:57] "GET / HTTP/1.1" 500 - 127.0.0.1 - - [26/Dec/2012 15:30:57] "GET /favicon.ico HTTP/1.1" 404 - and Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application. in my browser. If I return raw html, e.g. @app.route('/index', methods=['GET']) def index(): print "rendering index" return "This works" then it works fine. So a possible work around is to stop using Flask's templates and hardcode all the html logic into the main python file. This gets very messy though, so I'd like to avoid it if possible. I'm using Python 2.7 32-bit, Cx_freeze for Python 2.7 32-bit, and Flask 0.9 Thanks for any help and ideas! Answer: After many false trails trawling through the Flask and Jinga modules, I finally found the problem. CXFreeze does not recognize that jinja2.ext is a dependency, and was not including it. I fixed this by including `import jinja2.ext` in one of the python files. CXFreeze then added `ext.pyc` to library.zip\jinja. (Copying it in manually after the build also works) Just in case anyone else is mad enough to try use Flask to develop locally run apps :)
How can module be visible from one import and not visible from another? Question: So I've got an application that's using `pymysql`, the pure python mysql client implementation. Before I go into my response, I'd like to stress the fact that I am not open to using a different mysql driver. I have a module implementing a data structure that's backed by MySQL. The gist of the module is as follows: import pymysql class Whatever: def __init__(self): # Debug statement print dir(pymysql) # use the cursors submodule self.conn = pymysql.connect( ... , cursorclass=pymysql.cursors.DictCursor) When I import this in my test file, everything is fine. Here is the output of the `print` statement. In particular, I draw your attention to the cursors module: ['BINARY', 'Binary', 'Connect', 'Connection', 'DATE', 'DATETIME', 'DBAPISet', 'DataError', 'DatabaseError', 'Date', 'DateFromTicks', 'Error', 'FIELD_TYPE', 'IntegrityError', 'InterfaceError', 'InternalError', 'MySQLError', 'NULL', 'NUMBER', 'NotSupportedError', 'OperationalError', 'ProgrammingError', 'ROWID', 'STRING', 'TIME', 'TIMESTAMP', 'Time', 'TimeFromTicks', 'Timestamp', 'TimestampFromTicks', 'VERSION', 'Warning', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', 'apilevel', 'charset', 'connect', 'connections', 'constants', 'converters', 'cursors', 'err', 'escape_dict', 'escape_sequence', 'escape_string', 'get_client_info', 'install_as_MySQLdb', 'paramstyle', 'sys', 'thread_safe', 'threadsafety', 'times', 'util', 'version_info'] When I import the module from my main file, I get an `AttributeError`: Traceback (most recent call last): File "xxx.py", line 72, in <module> passwd='', db='test_db') File "yyy.py", line 26, in __init__ passwd=passwd, db=db, cursorclass=pymysql.cursors.DictCursor) AttributeError: 'module' object has no attribute 'cursors' The output of the `dir` print is as follows: ['BINARY', 'Binary', 'Connect', 'Connection', 'DATE', 'DATETIME', 'DBAPISet', 'DataError', 'DatabaseError', 'Date', 'DateFromTicks', 'Error', 'FIELD_TYPE', 'IntegrityError', 'InterfaceError', 'InternalError', 'MySQLError', 'NULL', 'NUMBER', 'NotSupportedError', 'OperationalError', 'ProgrammingError', 'ROWID', 'STRING', 'TIME', 'TIMESTAMP', 'Time', 'TimeFromTicks', 'Timestamp', 'TimestampFromTicks', 'VERSION', 'Warning', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', 'apilevel', 'charset', 'connect', 'constants', 'converters', 'err', 'escape_dict', 'escape_sequence', 'escape_string', 'get_client_info', 'install_as_MySQLdb', 'paramstyle', 'sys', 'thread_safe', 'threadsafety', 'times', 'version_info'] Notably, `cursors` is absent. Checking `pymysql.__file__` is the same in both cases, and the output is: __init__.py charset.py connections.py constants converters.pyc cursors.pyc err.pyc times.py util.py __init__.pyc charset.pyc connections.pyc converters.py cursors.py err.py tests times.pyc util.pyc Clearly `cursors.py` is there. So what gives? Answer: You need to add an explicit `import pymysql.cursors` at the top of your file. the `cursors` subpackage is not listed in the `pymysql`'s `__all__` and thus isn't imported when you do just `import pymysql`.
NameError: name 'Game' is not defined, but it is Question: I am learning python using the book _Learn python the hard way_. I am doing one of the exercises, which contains many if loop's. I met an error which says `Game` is not defined, but I did define it before. Anyone ideas? from sys import exit from random import randint class Game(object): def __init__(self, start): self.quips = [ "You died. You kinda suck at this.", "Nice job, you died ... jackass.", "Such a luser.", "I have a small puppy that's better at this."] slef.start = start def play(self): next = self.start while True: print "\n-------" room = getattr(self, next) next = room() def death(self): print self.quips[randint(0, len(quips)-1)] exit(1) def central_corridor(self): print "The Gothons of Planet Percal #25 have invaded your ship and destroyed" print "your entire crew. You are the last surviving member and your last" print "mission is to get the neutron destrut bomb from the Weapons Armory," print "put it in the bridge, and blow the ship up after getting into an " print "escapr pod." print "\n" print "You're running down the central corridor to the Weapons Armory when" print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume" print "flowing around his hate filled body. He's blocking the door to thr" print "Armory and about to pull a weapon to blast you." action =raw_input("> ") if action == "shoot!": print "Quick on the draw you yank out your blaster and fire it at the Gothan." print "His clown costume is flowing and moving around his body, which throws" print "off your aim. Your laser hits new costume but misses him entirely. This" print "completely ruins his brand new costumr his mother bought him, which" print " makes him fly into an insane rage and blast you repeatedly in the face until" print "you are dead. Then he eats you." return 'death' elif action =="dodge!": print "Like a world class boxer you dodge, weave, slip and slide right" print "as the Gothon's blaster cranks a laser past your head." print "In the middle of your artful dodge your foot slips and you" print "You wake up shortly after only to die as the Gothon stomps on" print "your head and eats you." return 'death' elif action =="tell a joke": print "Lucky for you they made you learn Fothon insults in the acsdemy." print "You tell teh one Gothon k=joke you know:" print "Lbhe zbgure vf fb sng, jura fur fvgf nebhag gur ubhfr, fur fvgf nrbhaq" print "The Gothon stops, tries not to laugh, then busts out laughing and can't" print "While he's laughing you run up and shoot him square in the head" print "putting hm down, then jump through the Weapon Armory door." return 'laser_weapon_asmory' else: print "DOES NOT COMPUTE!" return 'central_corridor' def laser_weapon_armory(self): print " You do a dive roll into the Weapon Armory, crough and scan the room" print "for more Gothans that might be hiding. It's dead quiet, too quiet." print "You stand up and run to the far side of the room and find the" print "neutron bomb in its container. There's a keypad lock on the code" print "and you need the code to get the bomb out. If you get the code" print "wrong 10 times then the lock closes forever and you can't" print "get the bomb. The code is 3 digits." code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9)) guess = raw_input("[keypad]> ") guesses = 0 while guess != code and guesses < 10: print "BZZZZEDDD!" guesses += 1 guess = raw_input("[keypad]> ") if guess == code: print "The container clicks open and the seal breaks, letting gas out." print "You grab the neutron bomb and run as fast as you can to the" print "bridge where you must place it in the right spot." return 'the_bridge' else: print "The lock buzzes one last time and then you hear s sickening" print "melting sound as teh mechanism is fused together." print "You decide to sit there, and finally the Gothons blow up the" return 'death' def the_bridge(self): print "You burst onto the Brisge with the netron destruct bomb" print "under your arm and surprise 5 Gothon who are trying to" print "take control of the ship. Each of them has an even uglier" print "clown costume than the last. They haven't pulled their" print "weapons out yet, as they see the active bomb under your" print "arm and don't want to see it off." action = raw_input("> ") if action == "throw the bomb": print "In a panic you throw the bomb at the group of Gothons" print "and make a leap for the door. Right as you drop it a" print "Gothon shoots you right in the back kiling you." print "As you die you see another Gothon frantically try to disarm" print "the bomb. You die knowing they will probably blow up when" print "it goes off." return 'death' elif action == "slowly place the bomb": print "You point your blaster at teh bomb under your arm" print "and the Gothons put their hand up and start to sweat." print "You inch backwark to the door, open it, and then carefully" print "place the bomb on the floor, pointing your blaster at it." print "You then jump back through the door, punch the close button" print "and blast the lock so the Gothons can't get out." print "Now that the bomb is placed you run to the escape pod to" print "get off this tin can." return 'escapr_pod' else: print "DOES NOT COMPUTE!" return "the_brigde" def escape_pad(self): print "You rush through the ship desperately trying to make it to" print "the escape pod before the whole ship explodes. It seemd like" print "hardly any Gothons are on the ship, so your run is clear of" print "interference. YOu get to the chamber with the excape pod, and" print "now need to pick one to take. Some of them could be damaged" print "but you don't have time to look. There's 5 pots, which one" print "do you take?" good_pod = randint(1,5) guess = raw_input("[pod #]> ") if int(guess) != good_pod: print "You jump into pod %s and hit the eject button." % guess print "The pod escaped out into the void of space, then" print "implodes as the hull ruptures, crushing your body" print "into jam jelly." else: print "You jump into pod %s and hit the eject button." % guess print "The pod eadily slides out into space heading to" print "the planet below. As it flies to the planet, you look" print "back and see your ship implode then explode like a" print "bright star, taking out the Gothon ship at the same" print "time. You won!" exit(0) a_game = Game("central_corridor") a_game.play() Answer: I think this is the result of an indentation error. In your posted code, you have class Game(object): def __init__(self, start): [...] print "time. You won!" exit(0) a_game = Game("central_corridor") a_game.play() So that you're defining `a_game` _inside_ the `Game` class, when `Game` isn't defined yet. Shift it to the left to move it outside the `Game` scope, i.e. a_game = Game("central_corridor") a_game.play() (on the same level as `class Game(object):`).
Parsing html in Python 2.7 with regex - don't really understand that Question: Sorry for being kinda dumb, but I really need help in Python. ['<a href="needs to be cut out">Foo to BAR</a>', '<a href="this also needs to be cut out">BAR to Foo</a>'] So I have this tuple, and I need to cut out what's inside that href attribute and what's inside `<a>` tag - basically, I want to get a tuple that looks like: [["needs to be cut out", "Foo to BAR"], ["this also needs to be cut out", "BAR to Foo"]] inside href attribute there are a lot of special symbols for example, <a href="?a=p.stops&amp;direction_id=23600&amp;interval=1&amp;t=wml&amp;l=en"> As I think, there's too much trouble in using HTML parsers if I really don't need to try to parse the object tree but only need a few url's and words from the webpage. But I can't really understand how to form regexes. Regexes that I formed seem to be completely wrong. So I'm asking if somebody could help me with it. Answer: Just use a HTML parser anyway. Python comes with a few included, and the [`xml.etree.ElementTree` API](http://docs.python.org/2/library/xml.etree.elementtree.html) is easier to get working than a regular expression for even simple `<a>` tags with arbitrary attributes: from xml.etree import ElementTree as ET texts = [] for linktext in linkslist: link = ET.fromstring(linktext) texts.append([link.attrib['href'], link.text]) If you use `' '.join(link.itertext())` you can get the text out of _anything_ nested under the `<a>` tag, if you find that some of the links have nested `<span>`, `<b>`, `<i>` or other inline tags to mark up the link text further: for linktext in linkslist: link = ET.fromstring(linktext) texts.append([link.attrib['href'], ' '.join(link.itertext())]) This gives: >>> from xml.etree import ElementTree as ET >>> linkslist = ['<a href="needs to be cut out">Foo to BAR</a>', '<a href="this also needs to be cut out">BAR to Foo</a>'] >>> texts = [] >>> for linktext in linkslist: ... link = ET.fromstring(linktext) ... texts.append([link.attrib['href'], ' '.join(link.itertext())]) ... >>> texts [['needs to be cut out', 'Foo to BAR'], ['this also needs to be cut out', 'BAR to Foo']]
Gdata API Installation Question: I have no idea what I'm doing. I'm using Python 2.7 on OSX with the Eclipse PyDev IDE. I've never worked with an API before, but I need to use the google calendar API with a Python application I'm developing. I downloaded the latest gdata module from Google and installed it using this line in Terminal while in the directory into which I downloaded the gdata folder (Downloads): sudo python setup.py install It seemed to install everything into a Python directory deep within my machine's Library, no errors were given. However, now when I attempt to run a program with the following import commands: import gdata.calendar.data import gdata.calendar.client import gdata.acl.data import atom I get the following error: ImportError: No module named gdata.calendar.data Clearly indicating I have done something wrong on the install. Thoughts? Answer: It's probably installed, but you haven't told Eclipse where to look for `gdata`. Right click on the project in Eclipse and choose `Properties -> PyDev - PYTHONPATH -> Source Folders` and click "Add source folder". The folder will (probably) be in `/Library/Python/2.7/site-packages/gdata`, depending on the version and where you installed it. It might be somewhere else, like `dist-packages` instead of `site-packages`, but once you find it and add the folder inside Eclipse, the imports should work. **Edit** : Don't forget to do the same for `atom`, too.
Retrieve Only the last values of a row in SQLITE with python 27 Question: I'm using this code to get all data from a sqlite row, but I would like to retrieve only the last 30 entries. import sqlite3 from matplotlib import pyplot fig = pyplot.figure() con = sqlite3.connect('growll.db') con.text_factory = str cur = con.cursor() cur.execute("select temp from GrowLLDados") ar=[r[0] for r in cur.fetchall()] Answer: something like `"select temp from GrowLLDados ORDER BY id DESC LIMIT 30"` where `id` is an auto-incrementing counter or at least means the higher the number the more recent the entry ...
Search for words (exact matches) in multiple texts using Python Question: I want to let the user choose and open multiple texts and perform a search for exact matches in the texts. I want the encoding to be unicode. If I search for "cat" I want it to find "cat", "cat,", ".cat" but not "catalogue". I don't know how to let the user search for two words ("cat" OR "dog") in all of the texts at the same time?????? Maybe I can use RE? So far I have just made it possible for the user to insert the path to the directory containing the text files to search in. Now I want to let the user (raw_input) search for two words in all of the texts, and then print and save the results (e.g. "search_word_1" and "search_word_2" found in document1.txt, "search_word_2" found in document4.txt) in a separate document (search_words). import re, os path = raw_input("insert path to directory :") ex_library = os.listdir(path) search_words = open("sword.txt", "w") # File or maybe list to put in the results thelist = [] for texts in ex_library: f = os.path.join(path, texts) text = open(f, "r") textname = os.path.basename(texts) print textname for line in text.read(): text.close() Answer: You need to split the text in each file on whitespace and punctuation. Once that's done you can simply look for the words you are searching for in the remaining list. You also need to convert everything to lowercase, unless you also want case sensitive search.
Python - Returning max number in an array. Errors Question: I have a Python script that connects to a website via FTP and lists the current version numbers of programs located on the website. I created an array to hold the version numbers till the script would pick the largest number out of the array and tell me what it was. For example my array would usually look like this: array = ['1.04','1.6','1.14'] So I used... max_in_array = max(array) to return the largest value in the array. Unfortunately, I received '1.6' as the largest number when, in fact, '1.14' is the latest version number. The only other thing I could think to do is to cut off the '1.' from the list of arrays so that I receive: array = ['04','6','14'] And then paste it back on to get the full version number. But since this website contains many versions such as '2.02.04' and '1.14.01' I don't know how to efficiently do that. Any help would be greatly appreciated! * * * os.chdir("./gnu/"+_package) pope = len(_package) + 1 ## Cuts off name of program char = len(_package) - 12 ## Cuts off extension ".tar.gz" for tok in glob.glob("*.tar.gz"): token.append(tok) ## Appends name to array bork = max(token) ## Gets max version number (sometimes useless) print bork char = len(bork) - 7 for _gnu in glob.glob("*.tar.gz"): ## Finds only matches with .tar.gz _gnuapp.append(_gnu[pope:char]) ## Appends version number to array spoke = max(_gnuapp) ## Gets max version number _ver = _package + "-" + spoke + ".tar.gz" ## Compiles the package name, ver #, and extension _down(_user, _ver, _package) ## Opens information in download module Answer: **Edit:** Sorry, misinterpreted the question at first - see [this answer](http://stackoverflow.com/questions/1714027/version-number-comparison) for a few methods regarding comparing version numbers. Taking the second answer in there (which suggests using `distutils.version`'s `StrictVersion`), you can try this: In [3]: from distutils.version import StrictVersion In [4]: s = ['1.04','1.6','1.14', '2.02.04', '1.14.01'] In [5]: max(s, key=StrictVersion) Out[5]: '2.02.04' * * * One thing to note is that you are actually comparing strings and not numbers. One thing you can do to ensure that you are comparing the number themselves (disregarding that you want to do with the item afterwards) is to provide a key to the `max` function: In [1]: s = ['1.04','1.6','1.14'] In [2]: max(s, key=float) Out[2]: '1.6' Since you are looking to compare float values (and not the strings), this compares the float equivalents of the strings. However it may be best to convert those to floats before proceeding: In [4]: s = ['1.04','1.6','1.14'] In [5]: s_floats = [float(x) for x in s] In [6]: s_floats Out[7]: [1.04, 1.6000000000000001, 1.1399999999999999] You can then use max as you expect: In [9]: max(s_floats) Out[9]: 1.6000000000000001
adding noise to a signal in python Question: I want to add some random noise to some 100 bin signal that I am simulating in Python - to make it more realistic. On a basic level, my first thought was to go bin by bin and just generate a random number between a certain range and add or subtract this from the signal. I was hoping (as this is python) that there might a more intelligent way to do this via numpy or something. (I suppose that ideally a number drawn from a gaussian distribution and added to each bin would be better also.) Thank you in advance of any replies. * * * I'm just at the stage of planning my code, so I don't have anything to show. I was just thinking that there might be a more sophisticated way of generating the noise. In terms out output, if I had 10 bins with the following values: Bin 1: 1 Bin 2: 4 Bin 3: 9 Bin 4: 16 Bin 5: 25 Bin 6: 25 Bin 7: 16 Bin 8: 9 Bin 9: 4 Bin 10: 1 I just wondered if there was a pre-defined function that could add noise to give me something like: Bin 1: 1.13 Bin 2: 4.21 Bin 3: 8.79 Bin 4: 16.08 Bin 5: 24.97 Bin 6: 25.14 Bin 7: 16.22 Bin 8: 8.90 Bin 9: 4.02 Bin 10: 0.91 If not, I will just go bin-by-bin and add a number selected from a gaussian distribution to each one. Thank you. * * * It's actually a signal from a radio telescope that I am simulating. I want to be able to eventually choose the signal to noise ratio of my simulation. Answer: You can generate a noise array, and add it to your signal import numpy as np noise = np.random.normal(0,1,100) # 0 is the mean of the normal distribution you are choosing from # 1 is the standard deviation of the normal distribution # 100 is the number of elements you get in array noise
overlay a smaller image on a larger image python OpenCv Question: Hi I am creating a program that replaces a face in a image with someone else's face. However, I am stuck on trying to insert the new face into the original, larger image. I have researched ROI and addWeight(needs the images to be the same size) but I haven't found a way to do this in python. Any advise is great. I am new to opencv. I am using the following test images: smaller_image: ![enter image description here](http://i.stack.imgur.com/pCZfV.png) larger_image: ![enter image description here](http://i.stack.imgur.com/Ddvzd.jpg) Here is my Code so far... a mixer of other samples: import cv2 import cv2.cv as cv import sys import numpy def detect(img, cascade): rects = cascade.detectMultiScale(img, scaleFactor=1.1, minNeighbors=3, minSize=(10, 10), flags = cv.CV_HAAR_SCALE_IMAGE) if len(rects) == 0: return [] rects[:,2:] += rects[:,:2] return rects def draw_rects(img, rects, color): for x1, y1, x2, y2 in rects: cv2.rectangle(img, (x1, y1), (x2, y2), color, 2) if __name__ == '__main__': if len(sys.argv) != 2: ## Check for error in usage syntax print "Usage : python faces.py <image_file>" else: img = cv2.imread(sys.argv[1],cv2.CV_LOAD_IMAGE_COLOR) ## Read image file if (img == None): print "Could not open or find the image" else: cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml") gray = cv2.cvtColor(img, cv.CV_BGR2GRAY) gray = cv2.equalizeHist(gray) rects = detect(gray, cascade) ## Extract face coordinates x1 = rects[0][3] y1 = rects[0][0] x2 = rects[0][4] y2 = rects[0][5] y=y2-y1 x=x2-x1 ## Extract face ROI faceROI = gray[x1:x2, y1:y2] ## Show face ROI cv2.imshow('Display face ROI', faceROI) small = cv2.imread("average_face.png",cv2.CV_LOAD_IMAGE_COLOR) print "here" small=cv2.resize(small, (x, y)) cv2.namedWindow('Display image') ## create window for display cv2.imshow('Display image', small) ## Show image in the window print "size of image: ", img.shape ## print size of image cv2.waitKey(1000) Answer: A simple way to achieve what you want: import cv2 s_img = cv2.imread("smaller_image.png") l_img = cv2.imread("larger_image.jpg") x_offset=y_offset=50 l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img ![the result image](http://i.stack.imgur.com/k1LQZ.png) ## Update I suppose you want to take care of the alpha channel too. Here is a quick and dirty way of doing so: s_img = cv2.imread("smaller_image.png", -1) for c in range(0,3): l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1], c] = s_img[:,:,c] * (s_img[:,:,3]/255.0) + l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1], c] * (1.0 - s_img[:,:,3]/255.0) ![result image with alpha](http://i.stack.imgur.com/Iuf35.jpg)
Django output html time is 8 hours ahead of database time Question: I'm very new to **Django** and I've been learning the framework from the book _"Practical django Projects"_ (the book teaches us to write a cms). My code runs fine, but I have time problem with the `get_absolute_url` function below. It's actually outputting the link 8 hours ahead of the time saved in my database. I used python shell to look at the saved time in the database and the time saved in the admin interface, they are all correct. But when I use the `get_absolute_url func` below to generate the link in browser, it becomes 8 hours ahead and throws the day off. I set the correct zone in my Django setting file. I cannot figure out what's wrong. How I can fix this (I'm using sqlite3 for my database, Django 1.4.1)? Here is my code for the Entry class: import datetime from django.db import models from django.contrib.auth.models import User from tagging.fields import TagField from markdown import markdown from django.conf import settings from django.utils.encoding import smart_str class Entry(models.Model): live = LiveEntryManager() objects = models.Manager() #define constant options LIVE_STATUS = 1 DRAFT_STATUS = 2 HIDDEN_STATUS = 3 STATUS_CHOICES = ( (LIVE_STATUS, 'Live'), (DRAFT_STATUS,'Draft'), (HIDDEN_STATUS, 'Hidden'), ) #adding features to admin interface class Meta: ordering = ['-pub_date'] verbose_name_plural = "Entries" #define model fields: title = models.CharField(max_length=250) excerpt = models.TextField(blank=True) #It's ok to not add anything for this field body = models.TextField() pub_date = models.DateTimeField(default=datetime.datetime.now()) slug = models.SlugField(unique_for_date='pub_date') enable_comments = models.BooleanField(default=True) featured = models.BooleanField(default=False) status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS) #HTML excerpt_html = models.TextField(editable=False, blank=True) body_html = models.TextField(editable=False, blank=True) #third party: tag = TagField() #relationship fields: categories = models.ManyToManyField(Category) author = models.ForeignKey(User) #define methods: def save(self, force_insert=False, force_update=False):#modify the model.save() method self.body_html = markdown(self.body) if self.excerpt: self.excerpt_html = markdown(self.excerpt)#from excerpt field to excerpt_html super(Entry, self).save(force_insert, force_update) def get_absolute_url(self): return "%s" % self.pub_date.strftime("year:%Y/day:%d/hour:%H/minute:%M/second:%S") #@models.permalink #def get_absolute_url(self): #return ('coltrane_entry_detail', (), {'year': self.pub_date.strftime("%Y"), 'month': self.pub_date.strftime("%b").lower(), 'day': self.pub_date.strftime("%d"), 'slug': self.slug}) def __unicode__(self): return self.title This is my entry_archive.html: {% extends "base_entries.html"%} {%block title%}{{block.super}} | Latest entries{% endblock %} {% block content %} {% for entry in latest %} <h2>{{entry.title}}</h2> <p>Published on {{ entry.pub_date|date:"F j P s, Y" }}</p> {% if entry.excerpt_html%} {{entry.excerpt_html|safe}} {% else %} {{entry.body_html|truncatewords_html:"50"|safe}} {% endif%} <p><a href="{{entry.get_absolute_url}}">Read full entry ...</a></p> {% endfor %} {%endblock%} {%block whatis%} <p>This is a list of the latest {{latest.count}} entries published in my blog.</p> {% endblock %} I couldn't post screenshot because i'm a new user. {{ entry.pub_date|date:"F j P s, Y" }} in my html give me correct time: December 28 11:24 a.m. 45, 2012. But {{entry.get_absolute_url}} gives me year:2012/day:28/hour:19/minute:24/seconds:45 I add the () to pub_date = models.DateTimeField(default=datetime.datetime.now()) as you guys suggested, but the result is still the same(the book actually suggests not to add () ). The thing troubles me is that {{ entry.pub_date|date:"F j P s, Y" }} gives me the correct time on my html, but {{entry.get_absolute_url}} is 8 hours ahead. I set my setting.py time zone to TIME_ZONE = 'America/Los_Angeles'. Thanks for all the quick response, but this is killing me... Answer: change the following: pub_date = models.DateTimeField(default=datetime.datetime.now) to Either pub_date = models.DateTimeField(default=datetime.datetime.now()) or pub_date = models.DateTimeField(auto_now_add=True)
Convert number to Italian and Italian to number in python Question: I need Python code to convert numbers to and from Italian. Looking at previous questions I learned that pynum2word does one way (num -> words) in several languages but alas, not in Italian. If no such code exist in Python, I wouldn't mind translating such code from Perl/Ruby/Java. Thanks. Answer: To do the conversion from italian to number it's pretty simple using regexes: import re NUMBERS_SEQ = ( ('dieci', '10'), ('undici', '11'), ('dodici', '12'), ('tredici', '13'), ('quattordici', '14'), ('quindici', '15'), ('sedici', '16'), ('diciasette', '17'), ('diciotto', '18'), ('diciannove', '19'), ('venti', '20'), ('trenta', '30'), ('quaranta', '40'), ('cinquanta', '50'), ('sessanta', '60'), ('settanta', '70'), ('ottanta', '80'), ('novanta', '90'), ('cento', '100'), ('mille', '1000'), ('mila', '1000'), ('milione', '1000000'), ('milioni', '1000000'), ('miliardo', '1000000000'), ('miliardi', '1000000000'), ('uno', '1'), ('un', '1'), ('due', '2'), ('tre', '3'), ('quattro', '4'), ('cinque', '5'), ('sei', '6'), ('sette', '7'), ('otto', '8'), ('nove', '9'), ) NUMBERS = dict(NUMBERS_SEQ) TOKEN_REGEX = re.compile('|'.join('(%s)' % num for num, val in NUMBERS_SEQ)) def normalize_text(num_repr): '''Return a normalized version of *num_repr* that can be passed to let2num.''' return num_repr.lower().translate(None, ' \t') def let2num(num_repr): '''Yield the numeric representation of *num_repr*.''' result = '' for token in (tok for tok in TOKEN_REGEX.split(num_repr) if tok): try: value = NUMBERS[token] except KeyError: if token not in ('di', 'e'): raise ValueError('Invalid number representation: %r' % num_repr) continue if token == 'miliardi': result += '0'*9 elif token in ('mila','milioni'): zeros = '0' * value.count('0') piece = result[-3:].lstrip('0') result = (result[:-len(piece)-len(zeros)] + piece + zeros) elif not result: result = value else: length = len(value) non_zero_values = len(value.strip('0')) if token in ('cento', 'milione', 'miliardo'): if result[-1] != '0': result = (result[:-length] + result[-1] + '0' * value.count('0')) continue result = (result[:-length] + value.rstrip('0') + result[len(result) -length + non_zero_values:]) return add_thousand_separator(result) def add_thousand_separator(s, sep='.'): '''Return the numeric string s with the thousand separator.''' rev_s = s[::-1] tokens = [rev_s[i:i+3][::-1] for i in range(0, len(s), 3)][::-1] return sep.join(tokens) Result: >>> let2num('unmilione') '1.000.000' >>> let2num('unmilionemilleduecento') '1.001.200' >>> let2num('unmilionemilleduecentotre') '1.001.203' >>> let2num('ventiquattro') '24' >>> let2num(normalize_text('Dieci milioni e CentoQuarantaTreMila miliardi di miliardi di miliardi Otto cento e quattro')) '10.143.000.000.000.000.000.000.000.000.000.804' >>> let2num('ventiquattromiliardicentotrentatremilionitredicimiladuecentouno') '24.133.013.201' Note that you must spell the number correctly. In the last example if you put in input the string: `'...centotrentatremilione...'`, with the (_wrong_)singular `milione` instead of `milioni` you get: >>> let2num('ventiquattromiliardicentotrentatremilionetredicimiladuecentouno') '24.003.013.201' Which is not "correct". But the spelling is actually wrong. I believe it shouldn't be too hard to allow `milione` as exact synonim for `milioni`, or to do add some error checking such that it would raise an error if it finds an incorrect spelling. Just be aware of this. As a suggestion for debugging the above code(if you want to make changes) is to add a line like: print 'token:', token, 'current result:', result As first instruction of the `for` loop. Then watching what is being done you should be able to recognize the "reasoning" behind the code and see where the bug lays. I think for the other conversion it'd be easy to implement something based on `pynum2word`. If you don't know italian I may try to help writing it.
Looping and Naming Variables in Python Bar Chart Question: I'm using matplotlib in Python to create a stacked bar chart showing order volume over the course of the day by hour, versus a calendar equivalent day last year. I've already arranged an array that includes today's and last year's order volume: allorders=[(23, 28), (15, 7), (15, 5), (8, 9), (4, 2), (5, 3), (4, 6), (8, 10), (28, 24), (45, 46), (55, 65), (0, 74), (0, 64), (0, 58), (0, 62), (0, 62), (0, 42), (0, 43), (0, 38), (0, 39), (0, 32), (0, 40), (0, 41), (0, 16)] For stacked bars, you would normally use the following syntax: import matplotlib.pyplot as plt import numpy as np n=2 ind = np.arange(n) width = 0.35 plt.ylabel('Orders') plt.xticks(ind+width/2., ('Today', 'Last Year on Calendar Equivalent')) plt.yticks(np.arange(0,plottotal,10)) p1= plt.bar(ind, allorders[0], width, color='#000099') p2= plt.bar(ind, allorders[1], width, color='#000099', bottom=allorders[0]) however, this can be daunting with large amount of stacked charts. Therefore, I'm trying to create a loop to go through the 'allorders' array and stack them via: for i in allorders: if i=0: p1=plt.bar(ind, allorders[i], width, color='#000099') bottomcounter=allorders[i] else: 'p+i' = plt.bar(ind, allorders[i], width, color='r', bottom=bottomcounter) bottomcounter=bottomcounter+allorders[i] but, I get all sorts of errors, including that the clause 'if i=0' has invalid syntax, and that 'p+i'cannot be used to auto-name variables. So, SO wizards: 1) how do you name new variables automatically in a loop (so when i=0, the variable is named p0, when i=1, the variable is named p1, etc.) 2) what's wrong with including the 'if i=0' clause? Since I'm new to Python (coming from R and Stata), please treat me like an infant, with step-by-step code if you can! Thanks! Answer: To start with, you need to read and understand the official [tutorial](http://docs.python.org/2/tutorial/). Second, to fix your code: import itertools allorders=[(23, 28), (15, 7), (15, 5), (8, 9), (4, 2), (5, 3), (4, 6), (8, 10), (28, 24), (45, 46), (55, 65), (0, 74), (0, 64), (0, 58), (0, 62), (0, 62), (0, 42), (0, 43), (0, 38), (0, 39), (0, 32), (0, 40), (0, 41), (0, 16)] width = .35 plts = [] colors = ['k','r','b'] for i,order in enumerate(allorders): bottom_counter = 0 loc_plts = [] for o,c in zip(order,itertools.cycle(colors)): tmp_plt = plt.bar(i, o, width, color=c, bottom=bottom_counter) loc_plts.append(tmp_plt) bottom_counter+=o plts.append(loc_plts)
Subprocess: Execute two or more preexec_fn Question: I was wondering if there is a way of creating a [subprocess](http://docs.python.org/2/library/subprocess.html) (through `subprocess.Popen`) that calls secuentially two (or more) `preexec_fn`. For instance, calling `setegid` and `seteuid` (just for example purposes). So far, I found this workaround (and well... it works, but it doesn't look too... direct or "clean") #!/usr/bin/python2.7 import subprocess import os def preExecuter(listOfFunctions): for functionEntry in listOfFunctions: functionEntry["function"](* functionEntry.get("args", []), **functionEntry.get("kwargs", {})) listOfFunctions = [ { "function": os.setegid, "args": [1000], }, { "function": os.seteuid, "args": [1000], }, ] if __name__ == "__main__": sp = subprocess.Popen(["whoami"], preexec_fn=preExecuter(listOfFunctions)) sp.communicate() Is there a better way of doing this? Thank you in advance. Answer: That's not even going to work, since the call to preExecuter actually executes the setegid and seteuid operations, and is done before Popen is called. What's wrong with def my_pre_exec() : os.setegid(1000) os.seteuid(1000) subprocess.Popen( ..., preexec_fn = my_pre_exec )
Python 3 parsing iTunes library plist file using plistlib Question: I'm trying to parse a iTunes media library file, which is a plist file using python & plistlib. I wrote a simple python script: import plistlib plist = plistlib.readPlist('tunes.xml') print(plist['Tracks']) But when I try and run it an error occurs on line 3: UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 21970: ordinal not in range(128) I've tried to load the file with a utf-8 encoding convert to a `bytearray` and use `plistlib.readPlistFromBytes` but still the error occurs Which is the best way to fix this? Answer: Chances are the terminal session or console you're running this in is not set to a UTF-8 compatible `locale`. See <https://wiki.archlinux.org/index.php/Locale> for more info. For example, in US English locales: export LANG=en_US.UTF-8
Django 1.4 on GAE: sqlite "ImportError: cannot import name utils" Question: I'm trying to get sqlite3 support working on Django 1.4 on Google App Engine 1.7.4 on Python 2.7. I fiddled around with the "Google Cloud SQL" database backend, all worked well (syncdb, insert/update/delete, ...). But then I enabled sqlite (as Google Cloud SQL is slow when on localhost): import os if (os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine') or os.getenv('SETTINGS_MODE') == 'pushtolive'): # Running on production App Engine, so use a Google Cloud SQL database. DATABASES = { 'default': { 'ENGINE': 'google.appengine.ext.django.backends.rdbms', 'INSTANCE': 'xyz:xyz', 'NAME': 'my_database', } } else: # Running in development, so use a local SQLite database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/tmp/mysite.db', } } and when I open any url (e.g. 127.0.0.1:8080) then I run into [this monstrous stack trace](https://gist.github.com/raw/4405464/76f6a6c31fb56d54bc8e9668ddea40d508ea714c/sqlite.traceback). I stripped down the stack trace so it's more readable: ERROR 2012-12-29 09:07:06,223 base.py:215] Internal Server Error: /favicon.ico Traceback (most recent call last): File "/Users/philipp/python/mysite/urls.py", line 4, in <module> from django.contrib import admin File ".../google_appengine/lib/django_1_4/django/contrib/admin/__init__.py", line 3, in <module> from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME File ".../google_appengine/lib/django_1_4/django/contrib/admin/helpers.py", line 2, in <module> from django.contrib.admin.util import (flatten_fieldsets, lookup_field, File ".../google_appengine/lib/django_1_4/django/contrib/admin/util.py", line 1, in <module> from django.db import models File ".../google_appengine/lib/django_1_4/django/db/__init__.py", line 40, in <module> backend = load_backend(connection.settings_dict['ENGINE']) File ".../google_appengine/lib/django_1_4/django/db/__init__.py", line 34, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File ".../google_appengine/lib/django_1_4/django/db/utils.py", line 92, in __getitem__ backend = load_backend(db['ENGINE']) File ".../google_appengine/lib/django_1_4/django/db/utils.py", line 24, in load_backend return import_module('.base', backend_name) File ".../google_appengine/lib/django_1_4/django/utils/importlib.py", line 35, in import_module __import__(name) File ".../google_appengine/lib/django_1_4/django/db/backends/sqlite3/base.py", line 14, in <module> from django.db import utils ImportError: cannot import name utils From the stack trace I read that the execution runs to the `django.db.utils` module, then into `django.db.backends.sqlite3.base`, then it tries to jump into `django.db.utils` again but that then strangely fails. The problem seems to be in the GAE environment, since this works: python mysite/manage.py syncdb And this as well: python mysite/manage.py shell >>> from django.contrib.auth.models import User >>> u = User(username="hans") >>> u.save() >>> User.objects.all() [<User: hans>] **What I tried so far:** * switched from/to Django 1.3/1.4 * [uninstalled GAE](http://stackoverflow.com/questions/9189054/how-do-i-uninstall-google-app-engine-sdk#answer-14081488), installed it again * I tried through all the solutions google reveals for "ImportError from django.db import utils" * there is [this similar question](http://stackoverflow.com/questions/7866256). I tried executing the statements in the question and I don't run into the problem. I'm on OS X 10.8.2 My PYTHONPATH is `:/usr/local/google_appengine:/usr/local/google_appengine/lib/django_1_4` Answer: As it's [not good practice to use sqlite in dev and mysql (as used by Cloud SQL) in production](http://stackoverflow.com/questions/2306048/django-sqlite- for-dev-mysql-for-prod) I don't recommend this setup to anyone. Then, there is the option `--use_sqlite`: This is used to speed up development when using the Google Data*store*. There is no similar option for Cloud SQL.
Import error in pyzmq after updating libzmq Question: I have an error when I attempt to update my ZeroMQ to the new version 3.2. This is the ouput that I have: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/zmq/__init__.py", line 51, in <module> from zmq import core, devices File "/usr/local/lib/python2.7/dist-packages/zmq/core/__init__.py", line 26, in <module> from zmq.core import (constants, error, message, context, ImportError: /usr/local/lib/python2.7/dist-packages/zmq/core/socket.so: undefined symbol: zmq_sendmsg I really don't know what's going on. I'm using Ubuntu 12.04 and I develop in Python. I've already checked on Stack Overflow but I did not see anything. It worked well before but I started to have this error after installing pyzmq 2.2.0.1. Could anyone help me with this? Thanks MAXA Answer: As I [replied to you](http://lists.zeromq.org/pipermail/zeromq- dev/2012-December/019868.html) on the zeromq-dev list, you must rebuild pyzmq any time you do a major upgrade of libzmq.
Days of the week Django Question: please, explain me, how do this thing: I have a week number (52, for example) and year (2012). So, how I can get the days number (monday - 24, tuesday - 25, etc). Yes, I read [this](http://docs.python.org/2/library/datetime.html), but I cant understand, how to do it. Thanks. Answer: I would do it like this: from datetime import date, timedelta def get_weekdays(year, week): january_first = date(year, 1, 1) monday_date = january_first + timedelta(days=week * 7 - january_first.weekday()) # monday, tuesday, .. sunday return [(monday_date + timedelta(days=d)).day for d in range(7)] (my weeks start at monday)
How do you invoke a function on a bunch of lines selected via Ctrl-v? Question: I am selecting some text via Ctrl-v (visual mode). Then I type \s to align those lines and sort them like so: "Strip trailing space :map <Leader>S :1,$ s/\s\+$//g<CR> :imap <Leader>S :1,$ s/\s\+$//g<CR> How do I pass all the selected lines to Sort(). I thought the **vim.current.range** object might do it but that didn't work out. Currently the Sort() function reads text 1 line at a time via cr[0]. What I need to do is store the split lines in a matrix, compute the required length/column and print them out into the buffer. function! Sort() python << EOF import vim cr = vim.current.range line = cr[0] line = line.split() fmt_str = ['%8s' for word in line] fmt_str = ' '.join(fmt_str) line = tuple([word for word in line]) print(fmt_str) cr[0]= fmt_str % line EOF endfunction "Sort and align :map <Leader>s :call Sort()<CR> Answer: When you want a mapping to work on the visual selection, you need to use `:vnoremap`. An Ex command (like `:call`) will then automatically have the visual range `'<,'>` prepended. An ordinary function would then be invoked once per line, but you can define a special kind of function (cp. `:help function-range-example`) that handles the range itself. Since you seem to want to use Python, I'd just drop the prepended range via `<C-u>` and access the selection's bounds via the `<` and `>` marks, then access and modify the lines via `vim.current.buffer[lnum]`: :vnoremap <Leader>s :<C-u>call Sort()<CR> function! Sort() ... start = vim.current.buffer.mark('<')[0] end = vim.current.buffer.mark('>')[0]
Trouble with Apache, mod_wsgi, and Django configuration Question: Just set up a 64 bit ubuntu EC2 instance using the Bitnami DjangoStack image. So far I have installed a few python dependencies and removed the Project django app which was created by default. I created a new app with 'django- admin.py startproject projectname'. I then followed the instructions here: <http://wiki.bitnami.org/Components/Django>, attempting to setup apache. Here is my projectname.conf file: Alias /static "/opt/bitnami/apps/django/lib/python2.7/site-packages/django/contrib/admin/static" <Directory '/opt/bitnami/apps/django/lib/python2.7/site-packages/django/contrib/'> Order allow,deny Allow from all </Directory> WSGIScriptAlias /URL_mount_point "/opt/bitnami/apps/django/scripts/projectname.wsgi" <Directory '/opt/bitnami/apps/django/scripts'> Order allow,deny Allow from all </Directory> Here is my projectname.wsgi import os, sys sys.path.append('/opt/bitnami/apps/django/django_projects') sys.path.append('/opt/bitnami/apps/django/django_projects/projectname') os.environ['DJANGO_SETTINGS_MODULE'] = 'projectname.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() Here are the last three lines of my httpd.conf: Include "/opt/bitnami/apache2/conf/ssi.conf" Include "/opt/bitnami/apache2/conf/bitnami/httpd.conf" Include "/opt/bitnami/apps/django/conf/projectname.conf" After doing this and restarting apache, hitting mydomain.com/projectname still comes up with a 404 (the Bitnami landing page comes up just fine at mydomain.com). Am I missing something here? Are my paths in projectname.wsgi incorrect (I have not strayed from the default Bitnami directory structure). Or is there some additional step I am missing here? Answer: You should be accessing: http://mydomain.com/URL_mount_point Since it appears you have not shown your original configuration, hard to say whether that is the issue or whether is a typo of sorts.
Error running Pyserial Question: I just installed Pyserial 2.6 and I have Python 2.7.3 unfortunately it either did not install correctly or I am not using it correctly. I installed it through terminal using the line sudo easy_install pyserial Unfortunately it gave me 2 warnings: warning: no files found matching 'examples/miniterm.py' warning: no files found matching 'test/test_io_lib.py' Other than that it seemed to install correctly. When I run this in Python I keep getting the farther below error import serial serial_input = serial.Serial('/dev/tty/.usbmodem3d241',9600) while True: ser.readline() Error: Traceback (most recent call last): File "/Users/ben/Documents/Arduino_to_Python.py", line 5, in <module> serial_input = serial.Serial('/dev/tty/.usbmodem3d241',9600) File "build/bdist.macosx-10.7-intel/egg/serial/serialutil.py", line 261, in __init__ self.open() File "build/bdist.macosx-10.7-intel/egg/serial/serialposix.py", line 278, in open raise SerialException("could not open port %s: %s" % (self._port, msg)) SerialException: could not open port /dev/tty/.usbmodem3d241: [Errno 20] Not a directory: '/dev/tty/.usbmodem3d241' Whatever serial port I try it never seems to work. I have tried the ones in the Arduino program Tools>Serial Port and all of the prompts at <http://pyserial.sourceforge.net/shortintro.html#opening-serial-ports> Any help would be greatly appreciated. Thanks. Answer: This `serial_input = serial.Serial('/dev/tty/.usbmodem3d241',9600)` should be without the additional `/.` between `/dev/tty` and `usbmodem3d241`. Also, open your console and go see if `ttyusbmodem3d241` exists. In the console type `cd /dev` then `ls` and see if it is listed.
installing pybrain Question: I am trying to install pybrain using : git clone git://github.com/pybrain/pybrain.git I installed git and then used windows command prompt to execute the above command. Everything goes well but when I open my python IDE, I cant import pybrain. The module doesn't exist. I wonder if I should've done something extra. Answer: As per the [PyBrain documentation](http://pybrain.org/docs/#installation), you're missing a second step, which is to install the code. So open a command prompt in the pybrain source directory (it'll have a `setup.py` file in it) and then run the following command: python setup.py install For reference, more detailed installation instructions can be found at the [PyBrain Github wiki](https://github.com/pybrain/pybrain/wiki/installation)
Pygame: Converting all white pixels to fully transparent in png image Question: I have been trying to create an image processing program to take all the white pixels (255,255,255) in a loaded image and set their alpha channels to 0 (non- opaque), and then save the image. I've been using Python's pygame extension to help me achieve this, but so far I cannot find a simple way to do what I just described above. Keep in mind I'm not trying to display an image, I'm trying to manipulate it. Answer: I also suggest using PIL or [ImageMagick](http://imagemagick.org/script/index.php "ImageMagick"), but here is a way to do it in pygame: import pygame def convert(): pygame.init() pygame.display.set_mode() image = pygame.image.load("triangle.png").convert_alpha() for x in range(image.get_width()): for y in range(image.get_height()): if image.get_at((x, y)) == (255, 255, 255, 255): image.set_at((x, y), (255, 255, 255, 0)) pygame.image.save(image, "converted.png") if __name__ == "__main__": convert() The above works for a white background. Here's how _triangle.png_ and _converted.png_ look using magenta instead of white so you can see the difference: ![magenta bg](http://i.stack.imgur.com/lzvWe.png) ![transparent bg](http://i.stack.imgur.com/1kLrX.png) With the ImageMagick utility instead, it's as easy as running this on the command line: convert original.png -transparent white converted.png
python: I want to find the first record in google place result but getting first character Question: I'm using google place API to return a list of locations. I would like to find the first name from the result set. I'm getting a list of values, but when I try to get just the first name, it gives me the first character instead. name2 = simplejson.dumps([s['name'] for s in result['results']], indent=0)[0] Obviously, there has to be a better way to get what I want, but I haven't found it. Seems like I'm missing something pretty basic. Following is the whole function: import simplejson, urllib PLACE_SEARCH = 'https://maps.googleapis.com/maps/api/place/textsearch/json' def placelatlng(name,city, state, sensor,**geo_args): geo_args.update({ 'name': name, 'city': city, 'state': state, 'sensor': sensor }) concat=name+'+'+city+'+'+state query = {"query": concat } key="MyKey" url = PLACE_SEARCH + '?' + urllib.unquote(urllib.urlencode(query))+ '&' + "sensor="+sensor +'&' + "key="+key result = simplejson.load(urllib.urlopen(url)) name2 = simplejson.dumps([s['name'] for s in result['results']], indent=0) Thanks. Answer: dumps() returns a string. `[0]` gets the first character in it. To get the first result's name: print result['results'][0]['name']
what "self" is doing in the selenium python code? Question: > **Possible Duplicate:** > [Python ‘self’ > explained](http://stackoverflow.com/questions/2709821/python-self-explained) I just wrote a code as below with the help of `selenium` documentation, but confused with one what `self` does some methods `argument list`? Why I need to import `unittest` class? import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys class PythonOrgSearch(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() def test_search_in_python_org(self): driver = self.driver driver.get("http://www.python.org") self.assertIn("Python", driver.title) elem = driver.find_element_by_name("q") elem.send_keys("selenium") elem.send_keys(Keys.RETURN) self.assertIn("Google", driver.title) def tearDown(self): self.driver.close() if __name__ == "__main__": unittest.main() Answer: `self` is used to represent the calling instance of a class in case of member methods. This is required so that the member methods of a class act on the correct object. This does not have anything to do with Selenium, but is a general feature of the language. It is similar to the `this` argument in C++ When a class is defined, the `self` argument is used when defining data members of the class as is being done in your class.
Viewing html text between tags (python, lxml, urllib, xpath) Question: I am trying to parse some html and I want to retrieve the actual html between the tags, but instead my code is giving me what I believe is the location of the elements. Here is my code so far: import urllib.request, http.cookiejar from lxml import etree import io site = "http://somewebsite.com" cj = http.cookiejar.CookieJar() request = urllib.request.Request(site) opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) request.add_header('User-agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0') html = etree.HTML(opener.open(request).read()) xpath = "//li[1]//cite[1]" filtered_html = html.xpath(xpath) print(filtered_html) Here is a piece of the html: <div class="f kv"> <cite> www. <b>hello</b> online.com/ </cite> <span class="vshid"> </div> Currently my code returns: [<Element cite at 0x36a65e8>, <Element cite at 0x36a6510>, <Element cite at 0x36a64c8>] How do I extract the actual html code between the cite tags? If I add "/text()" to the end of my xpath it gets me closer, but it leaves out what is in the b tags. My ultimate goal is for my code to give me "www.helloonline.com/". Thank you Answer: Use `//text()` to get _all_ text elements from a given location: text = filtered_html.xpath('//text()') print ''.join(t.strip() for t in text) # prints "www.helloonline.com/"
How do I use python's choice just once? Question: Consider the following: I'm making a secret santa script for my family for next year using python, and although I have figured out how to draw names (see code below), I need to execute it just once. I'm planning to use the flask framework to create a page counts down the days until the draw (which I've figured out as well), but how do i make it so it does the draw, just once, and not everytime somebody logs on to that page? Get what I mean? Anyway, I'll show you my code here: # imports & initial Flask set up above def do_matchup(names, draw, matches=None): if matches is None: matches = [] while names: member = names.pop() recipient = choice(draw) if recipient != member: matches.append("%s=%s" % (member, recipient)) draw.remove(recipient) else: names.append(member) return matches @app.route("/") def index(): now = dt.datetime.now() draw_date = dt.datetime.strptime('10/1/2013', '%m/%d/%Y') days = draw_date - now family = ["member1", "member2", "member3", "member4", "member5", "Me"] hat_names = [name for name in family] matchup = do_matchup(family, hat_names) return render_template("base.html", now=now, draw_date=draw_date, days=days, matchup=matchup) The template is a basic html page that says {% if now < draw_date %} "There are x-amount of days until the draw", {% else %} "Show the draw results". Every time the page is loaded, it does a new draw. How do I make it so it just does the draw once and not give every family member different results? Answer: If you are not using a database and just need this small amount of saved results, you could just pickle the matchup to a file. Then in your index you just check if the file exists and if so, read the file and return that matchup. Otherwise you generate a new matchup, save it, and return results.
Python Spacing Between Print Calls Question: I would like to make the spacing between print statements the same. I thought that the spacing would be the same but between the third and fourth lines of text there is a larger gap. Here is my code import random import time def UserInfo(): UserName = input ("Player 1 what is your name?\n") return UserName def Introduction(UserName): time.sleep(.5) print ("Hello " + UserName + ",\n") time.sleep(1) print ("You are an unfortunate soul\n") UserName = UserInfo() Introduction(UserName) The result i am getting is Player 1 what is your name? Patrick Hello Patrick, You are an unfortunate soul But I dont want the gap between the third and fourth lines Answer: If you don't want extra linebreaks, don't use extra `\n`s. `print` adds a line feed by default.
threading python bind several ports Question: I want to do a simple thing: just bind two ports to wait for incoming connections and continous with the application code. This is the code. import socket import threading import Queue q = Queue.Queue() q2 = Queue.Queue() def escucha_9003(): s = socket.socket() s.bind(("localhost",9023)) s.listen(10) sc, address = s.accept() q.put(sc) def escucha_9004(): s2 = socket.socket() s2.bind(("localhost",9024)) s2.listen(10) sc2, address2 = s2.accept() q.put(sc2) hilo = threading.Thread(target=escucha_9003).start() sc2=q.get() hilo2 = threading.Thread(target=escucha_9004).start() sc=q2.get() print "i never arrive here" I need to get some parameters that are returned in each function. I use Queue library to do it. But the problem is that i want to keep working with the code and I never arrive to the line: print "i never arrive here". At least it is never printed. How need I do it to continue developing after launch those two threads and work with the incoming connections. Thank you very much Answer: Both `.get()` calls are blocking calls. Also, the `.accept()` calls in your threads are blocking. Technically you should never even get past the two `.accept()` calls if no connections are coming in from clients. Because the main thread is waiting on `get()` calls from the queues, but the queues never put anything because the threads are waiting on accepting a future connection. What you would need to do is handle your queues from within threads instead of inside of the main thread. Otherwise, you will need to use `.get(timeout=someSeconds)` inside of an event loop where you keep checking for more stuff in your queues for a certain amount of time, and then move on to do more continuous processing. You may want to explain exactly what you are trying to achieve, and then restructure these threads to handle a bit more of their own work before blocking the main thread to receive data.
list inteprolation removing arbitary values - np.interp Question: I am new to python coding: I have a list of temperatures, for days where temperature was not recorded the value 9999 is used. I want to use np.interp tp interpolate through the list to remove 9999, with an estimated value. E.g. max_temp = [40, 35, 32, 31, 9999, 9999, 9999, 26, 27, ... ... 40, 42] Answer: Solved - Used: from pandas import * a = [1,2,3,None,5] b = Series(a).interpolate() b = [1,2,3,4,5] Simpler than np.interp()
Python SSL Socket Client Authentification Question: I'm trying to set up a server and client in python where the server authenticates clients using SSL with certificates. There are a lot of examples of SSL certificates online, but everything I've found has the server providing a certificate to the client and the client checking it. I need the server to ensure that the client has the authority to connect to the server. I understand how to generate and send certificates and the basics of how they work. I would type out my code, but my client/server without SSL is working fine and I've been referencing [this](http://docs.python.org/2/library/ssl.html) for SSL. The client/server example at the bottom of that page summarizes my understanding of SSL certs in python. I realize this isn't much to go on, but if someone could explain the basic modifications to that example to have the server authenticate the client instead of the other way around, that would be awesome. Alternatively, a link to an example or even just some socket methods to investigate would be very helpful. Let me know if more information is needed. I don't mean to be vague and promise I've spent all morning looking for info myself :). Edit: I'm trying to stick to the basic ssl library. Aka "import ssl". Answer: You would use [SSLSocket.getpeercert](http://docs.python.org/2/library/ssl.html#ssl.SSLSocket.getpeercert) to get the certificate. The client would need to specify a key and certificate when wrapping the socket just like the server side. On the server side, you will also need to pass ca_certs="path_to_ca_cert_file" and probably also want to specify cert_reqs=CERT_REQUIRED (see. args for [ssl.wrap_socket](http://docs.python.org/2/library/ssl.html#ssl.wrap_socket). In addition to this, it sounds like you might be looking to do certificate based client authentication/authorization? This is a simple matter of using getpeercert to get the client certificate and accessing fields within the certificate to use in a normal authentication path (i.e. Common Name == User Id)
Equivalent to: import * Question: I am creating a Perl equivalent to my Python project. Description: I have a base module "base.py" that is used by all my scripts via "from base import *" The base module has common subroutines/functions that can be executed inside the scripts My attempt for Perl was placing inside each script "use base.pm". However the subroutines in Perl were not locally imported to the script so I needed to make a call to the "base" module each time I wanted to execute a subroutine. What is the Perl equivalent to Python's "from base import *"? Answer: You generally specify which functions to import just as a list of names: use List::Util 'max', 'min'; Most modules that export things will follow these semantics: use MyBase; # imports default exports (if any) use MyBase 'baz'; # imports only baz use MyBase (); # import nothing Inside the module, an import class method is called that can choose what to export, usually having a default list but using the list passed if there is one. The Exporter module exists to help you do this: package MyBase; use Exporter 'import'; our @EXPORT = ( 'foo', 'bar' ); our @EXPORT_OK = ( 'baz', 'quux' ); There is also a facility for grouping exports by tag and allowing importing a whole group easily, see the Exporter docs. Variables can also be exported, not just subs. With that background, to finally answer your question: For modules that use Exporter (not all do), you can specify imports with a regular expression enclosed in //: use List::Util '/./';
Python, subprocess, call(), check_call and returncode to find if a command exists Question: I've figured out how to use call() to get my python script to run a command: import subprocess mycommandline = ['lumberjack', '-sleep all night', '-work all day'] subprocess.call(mycommandline) This works but there's a problem, what if users don't have lumberjack in their command path? It would work if lumberjack was put in the same directory as the python script, but how does the script know it should look for lumberjack? I figured if there was a command-not-found error then lumberjack wouldn't be in the command path, the script could try to figure out what its directory is and look for lumberjack there and finally warn the user to copy lumberjack into one of those two places if it wasn't found in either one. How do I find out what the error message is? I read that check_call() can return an error message and something about a returncode attribute. I couldn't find examples on how to use check_call() and returncode, what the message would be or how I could tell if the message is command-not-found. Am I even going about this the right way? Answer: A simple snippet: try: subprocess.check_call(['executable']) except subprocess.CalledProcessError: pass # handle errors in the called executable except OSError: pass # executable not found
Could not import settings in zc.buildout Question: I just setup my project and I'm having a problem getting Django to work. Here's my `buildout.cfg`: [buildout] parts = python django develop = . eggs = myproject [python] recipe = zc.recipe.egg interpreter = python eggs = ${buildout:eggs} [django] recipe = djangorecipe project = myproject settings = settings wsgi = true fcgi = true I generated my Django project by running $ bin/django startproject myproject src/ The settings file definitely exists and looks fine, but I get the following error: > Error: Could not import settings 'myproject.settings' (Is it on sys.path?): > No module named myproject.settings Any ideas as to what's going wrong? Answer: You haven't told your `[django]` part which eggs to use. You normally have two or three parts in a buildout where you need the very same eggs. In your case the `[django]` and `[python]` part. Best practice is to add an `eggs` option to `[buildout]` (as you've done) and to use that in the other relevant parts as `eggs = ${buildout:eggs}`. So... you're only missing that line in your `[django]` part.
How to download images from a list of scraped URLs? Question: > **Possible Duplicate:** > [How to download image using > requests](http://stackoverflow.com/questions/13137817/how-to-download-image- > using-requests) I have this Python script for scraping image URLs of a tumblr blog, and would like to download them to a local folder on my desktop. How would I go about implementing this import requests from bs4 import BeautifulSoup def make_soup(url): #downloads a page with requests and creates a beautifulsoup object raw_page = requests.get(url).text soup = BeautifulSoup(raw_page) return soup def get_images(soup): #pulls images from the current page images = [] foundimages = soup.find_all('img') for image in foundimages: url = img['src'] if 'media.tumblr.com' in url: images.append(url) return images def scrape_blog(url): # scrapes the entire blog soup = make_soup(url) next_page = soup.find('a' id = 'nextpage') while next_page is not none: soup = make_soup(url + next_page['href']) next_page = soup.find('a' id = 'nextpage') more_images = get_images(soup) images.extend(more_images) return images url = 'http://x.tumblr.com' images = scrape_blog(url) Answer: Python's "[urllib2](http://docs.python.org/2/howto/urllib2.html)" is probably what you're looking for. If you need to do anything complicated (such as with cookies or authentication) it may be worth looking into a wrapper library such as [Requests](https://github.com/kennethreitz/requests), which provides a nice wrapper around a lot of the more cumbersome features of the standard library.
Set a cookie and retrieve it with Python and WSGI Question: a lot of questions exists that are similar to this, but none of them helped me out. Basically I'm using WSGI start_response() method [link](http://www.python.org/dev/peps/pep-0333/#the-start-response-callable). I tried to set a dummy header in the response with the tuple [('Set-Cookie', 'token=THE_TOKEN')] and add it to start response like this: status = '200 OK' response = 'Success' start_response(status,[('Set-Cookie', "DMR_TOKEN=DMR_TOKEN")]) return response I'm not pretty sure that is working correctly, but it's here [setting cookies](http://pylonsbook.com/en/1.1/the-web-server-gateway-interface- wsgi.html#changing-the-status-and-headers). Now, let's suppose the header is correct and in following requests I want to authenticate a token. What would be the correct way to catch that cookie/header setted in the past ? I've been reading and find I need something like this: (environ.get("HTTP_COOKIE","")) but that has been yielding empty string all the time, so I'm just assuming the header/cookie is not correctly set. Thanks guys Answer: I think you need to set the path explicitly to get useful behavior out of cookies, try something like:... from Cookie import SimpleCookie def my_app(environ, start_response): session_cookie = SimpleCookie() session_cookie['session'] = "somedata" session_cookie['session']["Path"] = '/' headers = [] headers.extend(("set-cookie", morsel.OutputString()) for morsel in session_cookie.values()) start_response("200 OK", headers)
Issue while importing nltk package in Python Question: When I type import nltk in the Python interpreter, it gives me this -- >>> import nltk Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/nltk/__init__.py", line 105, in <module> from collocations import * File "/usr/local/lib/python2.7/dist-packages/nltk/collocations.py", line 38, in <module> from nltk.metrics import ContingencyMeasures, BigramAssocMeasures, TrigramAssocMeasures File "/usr/local/lib/python2.7/dist-packages/nltk/metrics/__init__.py", line 16, in <module> from nltk.metrics.scores import (accuracy, precision, recall, f_measure, File "/usr/local/lib/python2.7/dist-packages/nltk/metrics/scores.py", line 16, in <module> from scipy.stats.stats import betai File "/usr/lib/python2.7/dist-packages/scipy/stats/__init__.py", line 7, in <module> from stats import * File "/usr/lib/python2.7/dist-packages/scipy/stats/stats.py", line 198, in <module> import distributions File "/usr/lib/python2.7/dist-packages/scipy/stats/distributions.py", line 87, in <module> from new import instancemethod File "new.py", line 3 ^ IndentationError: expected an indented block I took a look at new.py which I found in /usr/lib/python2.7/ and found everything ok. """Create new objects of various types. Deprecated.This module is no longer required except for backward compatibility. Objects of most types can now be created by calling the type object. """ from warnings import warnpy3k warnpy3k("The 'new' module has been removed in Python 3.0; use the 'types' " "module instead.", stacklevel=2) del warnpy3k from types import ClassType as classobj from types import FunctionType as function from types import InstanceType as instance from types import MethodType as instancemethod from types import ModuleType as module from types import CodeType as code Any solutions? Answer: You have a _local_ file named `new.py`. Check your current directory and rename it or delete it. You can see this in the traceback: File "/usr/lib/python2.7/dist-packages/scipy/stats/distributions.py", line 87, in <module> from new import instancemethod File "new.py", line 3 The preceding module has a full filepath, but the `new.py` file does not, making it a local file that is shadowing the relative import in `scipy.stats.distributions`.
Processing data after returning content - GAE Python Question: I want to collect some statistical data which needs some time to process, but it is not going affect user content which is returning. I am currently doing it by first caching, then processing it with a cron job. Is there any way to do this job immediately after returning user content? It should be like: def post(self): self.response.out.write("some output") # here user should not wait any more output # loading should be end in user browser. collectSomeStatistics(self) (I am using Python 2.7) Answer: You can use the [deferred library](https://developers.google.com/appengine/articles/deferred) from google.appengine.ext import deferred def do_something_expensive(a, b, c=None): logging.info("Doing something expensive!") # Do your work here # Somewhere else deferred.defer(do_something_expensive, "Hello, world!", 42, c=True) So your code becomes: def post(self): deferred.defer(collectSomeStatistics,args) self.response.out.write("some output") This then executes your function as a separate task, and the call to deferred returns immediately. Of course you won't be able to include any results from that deferred function in the content you return to the user.
Convert a string to a whitespace separated list w/quoted elements Question: Is there a simple way in Python to convert a string to a list using whitespaces as separators, but ignoring the whitespace within quoted text? IE: each word is treated as a separate search term, but any quoted text is treated as one term. Answer: Yes, by using the [`shlex.split()` function](http://docs.python.org/2/library/shlex.html#shlex.split): >>> import shlex >>> shlex.split('Some whitespace "separated string"') ['Some', 'whitespace', 'separated string']
Ensure two Pandas DatetimeIndexes are the same? Question: I have run into an issue when comparing two `DatetimeIndex`'s with different lengths in an `assert` like the following: In [1]: idx1 = pd.date_range('2010-01-01','2010-12-31',freq='D') In [2]: idx2 = pd.date_range('2010-01-01','2010-11-01',freq='D') In [3]: assert (idx1 == idx2).all() I get the error: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-17-ad2cfd6d11c2> in <module>() ----> 1 assert (idx1 == idx2).all() /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas-0.10.1.dev_dcd9df7-py2.7-macosx-10.8-x86_64.egg/pandas/tseries/index.pyc in wrapper(self, other) 75 result = func(other) 76 ---> 77 return result.view(np.ndarray) 78 79 return wrapper AttributeError: 'NotImplementedType' object has no attribute 'view' Which is fine if this is not implemented, yet, but is there some **pandas** way of doing this? **Note:** I have used the following with success: In [3]: assert list(idx1) == list(idx2) So, the following also works: In [3]: assert list(df.index) == list(testindex) But I would like to know if there is a more `pandas`-ish way of doing this. Answer: In [1]: import pandas as pd In [2]: idx1 = pd.date_range('2010-01-01','2010-12-31',freq='D') In [3]: idx2 = pd.date_range('2010-01-01','2010-11-01',freq='D') In [4]: idx3 = pd.date_range('2010-01-01','2010-12-31',freq='D') In [5]: help(idx1.equals) Help on method equals in module pandas.tseries.index: equals(self, other) method of pandas.tseries.index.DatetimeIndex instance Determines if two Index objects contain the same elements. In [6]: print(idx1.equals(idx2)) False In [7]: print(idx1.equals(idx3)) True
Pygame installation for Python 3.3 Question: I am trying to import [Pygame](https://en.wikipedia.org/wiki/Pygame) to use for my version of [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), 3.3. The downloads on the Pygame website only have Python 3.1 and 3.2. I cannot seem to be able to import Pygame though I thought I had it installed in the correct path. I have tried both the 3.1 and 3.2 Pygame downloads. Is Pygame just not installed in the correct file path or is Pygame not compatible with my version of Python (3.3)? I am running Windows 7 and here is the error: Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> import pygame File ".\pygame\__init__.py", line 95, in <module> from pygame.base import * ImportError: DLL load failed: The specified module could not be found. Answer: The main Pygame page seems to be rarely updated. You can download Pygame releases direct from [Bitbucket](http://en.wikipedia.org/wiki/Bitbucket) at <https://bitbucket.org/pygame/pygame/downloads>.
Boost::python wrapper for derived class method Question: I have C++ class and its wrapper for boost::python: class CApp { public: virtual bool FOOs (){}; //does not matter for now bool Run( const char * First,const char * Last) { ... return "Running..." }; struct pyApp : CApp, wrapper<CApp> //derived class { ... // wrappers for virtual methods } #include <boost/python.hpp> using namespace boost::python; BOOST_PYTHON_MODULE( myApp ) { class_<pyApp, boost::noncopyable>("CApp", init<>() ) ... .def("Run",&pyMOOSApp::Run); } Compiling is OK. But when i'm invoking Python code from myApp import * class pyApp(CApp): def __init__(self): print "INIT-->" CClass = CApp() pyClass = pyApp() CClass.Run('myApp','bar') pyClass.Run('myApp','bar') I have an error: INIT--> Running... // this is from CClass.Run Traceback (most recent call last): File "./pytest.py", line 18, in <module> pyClass.Run('myApp','bar') Boost.Python.ArgumentError: Python argument types in CApp.Run(pyApp, str, str) did not match C++ signature: Run(CApp {lvalue}, char const*, char const*) So I've tries to write a wrapper for Run method that is converting str to char placed in derived class c++ code: bool Run(std::string a, std::string b) { char * cstrA; char * cstrB; cstrA = new char[a.size()+1]; cstrB = new char[b.size()+1]; strcpy(cstrA,a.c_str()); strcpy(cstrB,b.c_str()); return this -> CApp::Run(cstrA, cstrB); } But the only change was in the last stroke: did not match C++ signature: Run(pyApp {lvalue}, std::string, std::string) **I'm pretty sure that a have bad wrapper for the Run method** , so any help will be appreciated. Thank you. Answer: I just saw your other question ([Using derived class (C++) by Python BOOST](http://stackoverflow.com/q/14076708/82896)) and believe this has the same solution. You need to call init() on the base class if you provide an init in the derived class. See my solution here - <http://stackoverflow.com/a/14742937/82896>.
gui locked when calling QWebView.print_() Question: I'm working with **Python 2.7** and **PySide** , and i need to export a big html-file to a pdf-file. I have tried loading it with a `QWebView` and then printing it to a `QPrinter` configured for pdf-format. this works fine. However, there is one big problem with my solution: when I call `QWebView.print_()`, the gui is locked up, and for windows it looks like my program has crashed. This happens because of the big size of my html (1000 pages and more). So my question is: is there a clean way to avoid this 'crash' ? EDIT: I tried to do the printing in a separate thread, like jadkik94 suggested. As far as I understand the code below should work. Unfortunately it crashes randomly. ;) Any ideas why this is the case? import sys from PySide import QtGui, QtWebKit, QtCore class PrintThread(QtCore.QThread): def __init__(self, webview, printer, parent=None): super(PrintThread, self).__init__(parent) self._webview = webview self._printer = printer def run(self): self._webview.print_(self._printer) class MyWindow(QtGui.QMainWindow): def __init__(self): super(MyWindow,self).__init__() # a printer to print on self._myPrinter = QtGui.QPrinter() self._myPrinter.setOutputFormat(QtGui.QPrinter.PdfFormat) self._myPrinter.setPrintRange(QtGui.QPrinter.AllPages) self._myPrinter.setOrientation(QtGui.QPrinter.Portrait) self._myPrinter.setPaperSize(QtGui.QPrinter.A4) self._myPrinter.setNumCopies(1) # a webview for loading the html and printing it self._webview = QtWebKit.QWebView(self) self.setCentralWidget( self._webview ) self._webview.loadFinished.connect(self.webViewLoadFinished) # print-preview-dialog self._previewDlg = QtGui.QPrintPreviewDialog(self._myPrinter) #self._previewDlg.paintRequested.connect(self.dlgPaintRequestNoThread) # works but freezes the mainthread self._previewDlg.paintRequested.connect(self.dlgPaintRequestWithThread) # as far is i understand this should work... but crashes randomly ;) # load the html self._webview.load('index.htm') # file is 2MB def webViewLoadFinished(self): # when webview has finished loading, show the dialog self._previewDlg.show() def dlgPaintRequestNoThread(self): self._webview.print_(self._myPrinter) def dlgPaintRequestWithThread(self): self.printPages() # wait for the print-thread to finish without blocking the mainthread eventLoop = QtCore.QEventLoop() self.worker.finished.connect(eventLoop.quit) eventLoop.exec_() def printPages(self): self.worker = PrintThread(self._webview, self._myPrinter) self.worker.finished.connect(self.donePrinting) self.progressDlg = QtGui.QProgressDialog() self.progressDlg.setCancelButton(None) self.progressDlg.show() self.worker.start() def donePrinting(self): self.progressDlg.close() if __name__ == '__main__': app = QtGui.QApplication(sys.argv) window = MyWindow() window.show() app.exec_() Answer: I believe you need to use threads to solve this problem. It appears that `QWebView.print_()` runs in the main thread, and thus blocks your GUI from running. You have 2 options, you either use Python's `threading` module or Qt's `QThread`s. [This question](http://stackoverflow.com/questions/10044197/how-to-get- qthreads-to-work-in-a-console-pyside-program) shows how you can use `QThread`s. Basically: class PrintThread(QtCore.QThread): def __init__(self, webview, parent=None): super(PrintThread, self).__init__(parent) self.webview = webview def run(self): # Get a printer from somewhere self.webview.print_(printer) And then: def printPage(self): worker = PrintThread(self.page) worker.finished.connect(self.donePrinting) # Show a loading dialog worker.start() def donePrinting(self): # Close the loading dialog pass You could apply the same thing with the threading module, but since you are already using pyside, why not use it for that too. Also, I am not sure if another thread (other than QThread) can mess with the Qt GUI, it might just tell you you cannot access the GUI thread from another thread (not sure though).
Python list comprehension expensive Question: Im trying to find the effeciency of list comprehension but it look like its more expensive than a normal function operation. Can someone explain? def squares(values): lst = [] for x in range(values): lst.append(x*x) return lst def main(): t = timeit.Timer(stmt="lst = [x*x for x in range(10)]") print t.timeit() t = timeit.Timer(stmt="squares",setup="from __main__ import squares") print t.timeit() lst = [x*x for x in range(10)] print lst print squares(10) ----Output:--- 2.4147507644 0.0284455255965 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] For the same output, the normal function calculates in very less time compared to the list comprehension. I thought the list comprehension is more effecient. Answer: You are never _calling_ your `squares` function, so it is not doing anything. List comprehensions _are_ in fact faster: >>> import timeit >>> def squares(values): ... lst = [] ... for x in range(values): ... lst.append(x*x) ... return lst ... >>> def squares_comp(values): ... return [x*x for x in range(values)] ... >>> timeit.timeit('f(10)', 'from __main__ import squares as f') 3.9415171146392822 >>> timeit.timeit('f(10)', 'from __main__ import squares_comp as f') 2.3243820667266846 If you use the `dis` module to look at the bytecode for each function, you can see why: >>> import dis >>> dis.dis(squares) 2 0 BUILD_LIST 0 3 STORE_FAST 1 (lst) 3 6 SETUP_LOOP 37 (to 46) 9 LOAD_GLOBAL 0 (range) 12 LOAD_FAST 0 (values) 15 CALL_FUNCTION 1 18 GET_ITER >> 19 FOR_ITER 23 (to 45) 22 STORE_FAST 2 (x) 4 25 LOAD_FAST 1 (lst) 28 LOAD_ATTR 1 (append) 31 LOAD_FAST 2 (x) 34 LOAD_FAST 2 (x) 37 BINARY_MULTIPLY 38 CALL_FUNCTION 1 41 POP_TOP 42 JUMP_ABSOLUTE 19 >> 45 POP_BLOCK 5 >> 46 LOAD_FAST 1 (lst) 49 RETURN_VALUE >>> dis.dis(squares_comp) 2 0 BUILD_LIST 0 3 LOAD_GLOBAL 0 (range) 6 LOAD_FAST 0 (values) 9 CALL_FUNCTION 1 12 GET_ITER >> 13 FOR_ITER 16 (to 32) 16 STORE_FAST 1 (x) 19 LOAD_FAST 1 (x) 22 LOAD_FAST 1 (x) 25 BINARY_MULTIPLY 26 LIST_APPEND 2 29 JUMP_ABSOLUTE 13 >> 32 RETURN_VALUE The `squares` function looks up the `.append()` method of the list in each iteration, and calls it. The `.append()` function has to grow the list by one element each time it is called. The list comprehension on the other hand doesn't have to do that work. Instead, python uses the `LIST_APPEND` bytecode, which uses the C API to append a new element to the list, without having to do the lookup and a python call to the function.
Two Columns of a pandas dataframe - Concat in Python Question: New to pandas python. I have a dataframe (df) with two columns of cusips. I want to turn those columns into a list of the unique entries of the two columns. My first attempt was to do the following: cusips = pd.concat(df['long'], df['short']). This returned the error: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). I have read a few postings, but I am still having trouble with why this comes up. What am I missing here? Also, what's the most efficient way to select the unique entries in a column or a dataframe? Can I call it in one function? Does the function differ if I want to create a list or a new, one-coulmn dataframe? Thank you. Answer: To obtain the unique values in a column you can use the [`unique`](http://pandas.pydata.org/pandas- docs/dev/generated/pandas.Series.unique.html#pandas.Series.unique) Series method, which will return a numpy array of the unique values _(and it is fast!)_. df.long.unique() # returns numpy array of unique values You could then use [`numpy.append`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html): np.append(df.long.unique(), df.short.unique()) Note: This just appends the two unique results together and so itself is not unique! . Here's a (trivial) example: import pandas as pd import numpy as np df = pd.DataFrame([[1, 2], [1, 4]], columns=['long','short']) In [4]: df Out[4]: long short 0 1 2 1 1 4 In [5]: df.long.unique() Out[5]: array([1]) In [6]: df.short.unique() Out[6]: array([2, 4]) And then [appending the resulting two arrays](http://stackoverflow.com/a/9775378/1240268): In [7]: np.append(df.long.unique(), df.short.unique()) Out[7]: array([1, 2, 4]) Using @Zalazny7's `set` is significantly faster (since it runs over the array only once) and somewhat upsettingly it's even faster than [`np.unique`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html) _(which sorts the resulting array!)_.
What do I import: file_name or class in Python? Question: I have a file named **schedule.py** : class SchedGen: """ Class creates a pseudo random Schedule. With 3/4 of total credit point required for graduation""" def __init__(self, nof_courses=40): random.seed() self.courses = {} self.nof_courses = nof_courses for i in xrange(nof_courses): self.courses[i] = college.Course(i) self.set_rand_cred() self.set_rand_chance() self.set_rand_preq_courses() def set_rand_cred(self): """ Set random credit to courses uniformly between 2 and 6""" temp_dict = self.courses.copy() While importing content of schedule do I do `import schedule` like: import schedule If that's correct how can I access the function set_rand_cred(self) from SchedGen class? Answer: You can either do import schedule schedgen = schedule.SchedGen() schedgen.set_rand_red() or from schedule import SchedGen schedgen = SchedGen() schedgen.set_rand_red() This link provides some information how Pythons [import statement](http://effbot.org/zone/import-confusion.htm) works.
Protocol error between Android and Python using SSL Question: This question has been asked, in various flavors, several times. Unfortunately, none of the answers have yielded a solution for me. I am attempting to connect to a python web server (code to follow) using the https protocol, with client side authentication included. When I connect via a python client that I wrote for testing, I have no problems. Fast forward, I am now trying to connect from an Android device (code to follow again) and am getting a javax.net.ssl.SSLProtocolException I have a self signed CA, which has issued two certificates. One for the client and one for the server. I removed the passphrase from the server private key using: `openssl rsa -in serverKey.pem -out serverKey.pem` and issued a request using openssl from the linux command line. For the client I issued a request, created the certificate and then used keytool with the BouncyCastle provider to import the CA into a trust store and the client certificate into a key store (I realize they are the same format, it just helps me to keep them separated if I refer to them by different names). Relevant server code: class ReuseHTTPServer(BaseHTTPServer.HTTPServer): def __init__(self, address, handler): BaseHTTPServer.HTTPServer.__init__(self, address, handler) self.address = address ssl_socket = ssl.wrap_socket(socket.socket(self.address_family, self.socket_type), keyfile = KEY_PATH, certfile = CERTIFICATE_PATH, server_side = True, cert_reqs = ssl.CERT_REQUIRED, ssl_version = ssl.PROTOCOL_SSLv23, ca_certs = CA_PATH) s = self.socket.getsockname() print "serving:", s[0], "on port:", s[1] self.socket = ssl_socket self.server_bind() self.server_activate() def server_bind(self): BaseHTTPServer.HTTPServer.server_bind(self) Android client code: //add bouncy castle to the list of security providers Security.insertProviderAt(new BouncyCastleProvider(), 1); //load the trusted CA KeyStore trusted = KeyStore.getInstance("BKS"); InputStream in = getResources().openRawResource(R.raw.mobilecastore); trusted.load(in, "password".toCharArray()); in.close(); TrustManagerFactory trust_factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trust_factory.init(trusted); //load the client keystore KeyStore client = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream client_in = getResources().openRawResource(R.raw.client); client.load(client_in, "password2".toCharArray()); client_in.close(); KeyManagerFactory key_factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); key_factory.init(client, "password2".toCharArray()); SSLContext ssl_context = SSLContext.getInstance("SSL"); ssl_context.init(key_factory.getKeyManagers(), trust_factory.getTrustManagers(), null); URL url = new URL("https", IP, 60000, "/cgi-bin/www_sel_jf"); connection = (HttpsURLConnection) url.openConnection(); connection.setSSLSocketFactory(ssl_context.getSocketFactory()); connection.setDoInput(true); connection.setRequestMethod("GET"); connection.connect(); The error: 12-31 07:23:37.917: W/System.err(3666): javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake terminated: ssl=0x16bab18: Failure in SSL library, usually a protocol error 12-31 07:23:37.917: W/System.err(3666): error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure (external/openssl/ssl/s3_pkt.c:1234 0x16bf980:0x00000003) 12-31 07:23:37.917: W/System.err(3666): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:460) 12-31 07:23:37.917: W/System.err(3666): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:257) 12-31 07:23:37.917: W/System.err(3666): at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:210) 12-31 07:23:37.917: W/System.err(3666): at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:477) 12-31 07:23:37.917: W/System.err(3666): at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:441) 12-31 07:23:37.917: W/System.err(3666): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282) 12-31 07:23:37.917: W/System.err(3666): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232) 12-31 07:23:37.917: W/System.err(3666): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80) 12-31 07:23:37.917: W/System.err(3666): at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:164) 12-31 07:23:37.917: W/System.err(3666): at com.dsndata.sds2mobile.status.activities.ServerJobs$RetrieveJobNames.doInBackground(ServerJobs.java:143) 12-31 07:23:37.917: W/System.err(3666): at com.dsndata.sds2mobile.status.activities.ServerJobs$RetrieveJobNames.doInBackground(ServerJobs.java:1) 12-31 07:23:37.917: W/System.err(3666): at android.os.AsyncTask$2.call(AsyncTask.java:264) 12-31 07:23:37.925: W/System.err(3666): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 12-31 07:23:37.925: W/System.err(3666): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 12-31 07:23:37.925: W/System.err(3666): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 12-31 07:23:37.925: W/System.err(3666): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 12-31 07:23:37.925: W/System.err(3666): at java.lang.Thread.run(Thread.java:856) 12-31 07:23:37.925: W/System.err(3666): Caused by: javax.net.ssl.SSLProtocolException: SSL handshake terminated: ssl=0x16bab18: Failure in SSL library, usually a protocol error 12-31 07:23:37.925: W/System.err(3666): error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure (external/openssl/ssl/s3_pkt.c:1234 0x16bf980:0x00000003) 12-31 07:23:37.925: W/System.err(3666): at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native Method) 12-31 07:23:37.925: W/System.err(3666): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:410) 12-31 07:23:37.925: W/System.err(3666): ... 16 more 12-31 07:23:37.925: W/System.err(3666): javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake terminated: ssl=0x16bab18: Failure in SSL library, usually a protocol error 12-31 07:23:37.925: W/System.err(3666): error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure (external/openssl/ssl/s3_pkt.c:1234 0x16bf980:0x00000003) 12-31 07:23:37.925: W/System.err(3666): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:460) 12-31 07:23:37.925: W/System.err(3666): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:257) 12-31 07:23:37.925: W/System.err(3666): at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:210) 12-31 07:23:37.925: W/System.err(3666): at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:477) 12-31 07:23:37.925: W/System.err(3666): at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:441) 12-31 07:23:37.925: W/System.err(3666): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282) 12-31 07:23:37.925: W/System.err(3666): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232) 12-31 07:23:37.925: W/System.err(3666): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80) 12-31 07:23:37.925: W/System.err(3666): at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:164) 12-31 07:23:37.925: W/System.err(3666): at com.dsndata.sds2mobile.status.activities.ServerJobs$RetrieveJobNames.doInBackground(ServerJobs.java:143) 12-31 07:23:37.932: W/System.err(3666): at com.dsndata.sds2mobile.status.activities.ServerJobs$RetrieveJobNames.doInBackground(ServerJobs.java:1) 12-31 07:23:37.932: W/System.err(3666): at android.os.AsyncTask$2.call(AsyncTask.java:264) 12-31 07:23:37.932: W/System.err(3666): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 12-31 07:23:37.932: W/System.err(3666): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 12-31 07:23:37.932: W/System.err(3666): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 12-31 07:23:37.932: W/System.err(3666): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 12-31 07:23:37.932: W/System.err(3666): at java.lang.Thread.run(Thread.java:856) 12-31 07:23:37.932: W/System.err(3666): Caused by: javax.net.ssl.SSLProtocolException: SSL handshake terminated: ssl=0x16bab18: Failure in SSL library, usually a protocol error 12-31 07:23:37.932: W/System.err(3666): error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure (external/openssl/ssl/s3_pkt.c:1234 0x16bf980:0x00000003) 12-31 07:23:37.932: W/System.err(3666): at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native Method) 12-31 07:23:37.932: W/System.err(3666): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:410) 12-31 07:23:37.932: W/System.err(3666): ... 16 more It should be noted that I am using the javax.net.ssl library and not the apache one. EDIT: The python server is hosted on a Windows machine. Is there any extra configuration that needs to be taken into account for ssl on a Windows port? EDIT: Yes, there is something that needs to be done to allow SSL on a windows port. Switched to port 443 (designated for SSL traffic) and am making (slow) progress. EDIT: I am now able to track the request using Wireshark (I am learning a lot for this problem!) and Wireshark is telling me that there is a 405 error. Which in SSL means that the certificate format is not recognized. The python server is using PEM certificates (the only format allowed according to python docs) and the certificates imported into the keystore on the Android device are DER (to my knowledge the only format accepted by BKS). Any help would be greatly appreciated. Answer: This can be a SSL/TLS version or algorithms mismatch error. Your server uses SSL v.2-3, while this is quite old and TLS 1.0-1.2 should be used. The best way to debug this is to run Wireshark, and see which client and server's SSL/TLS handshake packets are sent and when connection is dropped.
Killing child process when parent crashes in python Question: I am trying to write a python program to test a server written in C. The python program launches the compiled server using the `subprocess` module: pid = subprocess.Popen(args.server_file_path).pid This works fine, however if the python program terminates unexpectedly due to an error, the spawned process is left running. I need a way to ensure that if the python program exits unexpectedly, the server process is killed as well. Some more details: * Linux or OSX operating systems only * Server code can not be modified in any way Answer: I would [`atexit.register`](http://docs.python.org/2/library/atexit.html) a function to terminate the process: import atexit process = subprocess.Popen(args.server_file_path) atexit.register(process.terminate) pid = process.pid Or maybe: import atexit process = subprocess.Popen(args.server_file_path) @atexit.register def kill_process(): try: process.terminate() except OSError: pass #ignore the error. The OSError doesn't seem to be documented(?) #as such, it *might* be better to process.poll() and check for #`None` (meaning the process is still running), but that #introduces a race condition. I'm not sure which is better, #hopefully someone that knows more about this than I do can #comment. pid = process.pid * * * Note that this doesn't help you if you do something nasty to cause python to die in a non-graceful way (e.g. via `os._exit` or if you cause a `SegmentationFault` or `BusError`)
Creating a hook to a frequently accessed object Question: I have an application which relies heavily on a `Context` instance that serves as the access point to the context in which a given calculation is performed. If I want to provide access to the `Context` instance, I can: 1. rely on `global` 2. pass the `Context` as a parameter to all the functions that require it I would rather not use `global` variables, and passing the `Context` instance to all the functions is cumbersome and verbose. How would you "hide, but make accessible" the calculation `Context`? For example, imagine that `Context` simply computes the state (position and velocity) of planets according to different data. class Context(object): def state(self, planet, epoch): """base class --- suppose `state` is meant to return a tuple of vectors.""" raise NotImplementedError("provide an implementation!") class DE405Context(Context): """Concrete context using DE405 planetary ephemeris""" def state(self, planet, epoch): """suppose that de405 reader exists and can provide the required (position, velocity) tuple.""" return de405reader(planet, epoch) def angular_momentum(planet, epoch, context): """suppose we care about the angular momentum of the planet, and that `cross` exists""" r, v = context.state(planet, epoch) return cross(r, v) # a second alternative, a "Calculator" class that contains the context class Calculator(object): def __init__(self, context): self._ctx = context def angular_momentum(self, planet, epoch): r, v = self._ctx.state(planet, epoch) return cross(r, v) # use as follows: my_context = DE405Context() now = now() # assume this function returns an epoch # first case: print angular_momentum("Saturn", now, my_context) # second case: calculator = Calculator(my_context) print calculator.angular_momentum("Saturn", now) Of course, I could add all the operations directly into "Context", but it does not feel right. In real life, the `Context` not only computes positions of planets! It computes many more things, and it serves as the access point to a lot of data. So, to make my question more succinct: how do you deal with objects which need to be accessed by many classes? I am currently exploring: python's context manager, but without much luck. I also thought about dynamically adding a property "context" to all functions directly (functions are objects, so they can have an access point to arbitrary objects), i.e.: def angular_momentum(self, planet, epoch): r, v = angular_momentum.ctx.state(planet, epoch) return cross(r, v) # somewhere before calling anything... import angular_momentum angular_momentum.ctx = my_context ## edit Something that would be great, is to create a "calculation context" with a `with` statement, for example: with my_context: h = angular_momentum("Earth", now) Of course, I can already do that if I simply write: with my_context as ctx: h = angular_momentum("Earth", now, ctx) # first implementation above Maybe a variation of this with the [Strategy pattern](http://en.wikipedia.org/wiki/Strategy_pattern)? Answer: You generally don't want to "hide" anything in Python. You may want to signal human readers that they should treat it as "private", but this really just means "you should be able to understand my API even if you ignore this object", not "you can't access this". The idiomatic way to do that in Python is to prefix it with an underscore—and, if your module might ever be used with `from foo import *`, add an explicit `__all__` global that lists all the public exports. Again, neither of these will actually prevent anyone from seeing your variable, or even accessing it from outside after `import foo`. See [PEP 8](http://www.python.org/dev/peps/pep-0008/#global-variable-names) on Global Variable Names for more details. Some style guides suggest special prefixes, all-caps-names, or other special distinguishing marks for globals, but PEP 8 specifically says that the conventions are the same, except for the `__all__` and/or leading underscore. Meanwhile, the behavior you want is clearly that of a global variable—a single object that everyone implicitly shares and references. Trying to disguise it as anything other than what it is will do you no good, except possibly for passing a `lint` check or a code review that you shouldn't have passed. All of the problems with global variables come from being a single object that everyone implicitly shares and references, not from being directly in the `globals()` dictionary or anything like that, so any decent fake global is just as bad as a real global. If that truly is the behavior you want, make it a global variable. Putting it together: # do not include _context here __all__ = ['Context', 'DE405Context', 'Calculator', … _context = Context() Also, of course, you may want to call it something like `_global_context` or even `_private_global_context`, instead of just `_context`. But keep in mind that globals are still members of a module, not of the entire universe, so even a public `context` will still be scoped as `foo.context` when client code does an `import foo`. And this may be exactly what you want. If you want a way for client scripts to import your module and then control its behavior, maybe `foo.context = foo.Context(…)` is exactly the right way. Of course this won't work in multithreaded (or gevent/coroutine/etc.) code, and it's inappropriate in various other cases, but if that's not an issue, in some cases, this is fine. Since you brought up multithreading in your comments: In the simple style of multithreading where you have long-running jobs, the global style actually works perfectly fine, with a trivial change—replace the global `Context` with a global [`threading.local`](http://docs.python.org/library/threading.html) instance that contains a `Context`. Even in the style where you have small jobs handled by a thread pool, it's not much more complicated. You attach a context to each job, and then when a worker pulls a job off the queue, it sets the thread-local context to that job's context. However, I'm not sure multithreading is going to be a good fit for your app anyway. Multithreading is great in Python when your tasks occasionally have to block for IO and you want to be able to do that without stopping other tasks—but, thanks to the GIL, it's nearly useless for parallelizing CPU work, and it sounds like that's what you're looking for. Multiprocessing (whether via the `multiprocessing` module or otherwise) may be more of what you're after. And with separate processes, keeping separate contexts is even simpler. (Or, you can write thread-based code and switch it to multiprocessing, leaving the `threading.local` variables as-is and only changing the way you spawn new tasks, and everything still works just fine.) It may make sense to provide a "context" in the context manager sense, as an external version of the standard library's [`decimal`](http://docs.python.org/library/decimal.html) module did, so someone can write: with foo.Context(…): # do stuff under custom context # back to default context However, nobody could really think of a good use case for that (especially since, at least in the naive implementation, it doesn't actually solve the threading/etc. problem), so it wasn't added to the standard library, and you may not need it either. If you want to do this, it's pretty trivial. If you're using a private global, just add this to your `Context` class: def __enter__(self): global _context self._stashedcontext = _context _context = self def __exit__(self, *args): global context _context = self._stashedcontext And it should be obvious how to adjust this to public, thread-local, etc. alternatives. Another alternative is to make everything a member of the `Context` object. The top-level module functions then just delegate to the global context, which has a reasonable default value. This is exactly how the standard library [`random`](http://docs.python.org/library/random.html) module works—you can create a `random.Random()` and call `randrange` on it, or you can just call `random.randrange()`, which calls the same thing on a global default `random.Random()` object. If creating a `Context` is too heavy to do at import time, especially if it might not get used (because nobody might ever call the global functions), you can use the singleton pattern to create it on first access. But that's rarely necessary. And when it's not, the code is trivial. For example, the [source](http://hg.python.org/cpython/file/2.7/Lib/random.py) to `random`, starting at line 881, does this: _inst = Random() seed = _inst.seed random = _inst.random uniform = _inst.uniform … And that's all there is to it. And finally, as you suggested, you could make everything a member of a different `Calculator` object which owns a `Context` object. This is the traditional OOP solution; overusing it tends to make Python feel like Java, but using it when it's appropriate is not a bad thing.
installing libjpeg for pil and Google app engine on mac Mountain Lion Question: I'm sure there's a duplicate of this somewhere out there but I looked and am about at the end of my rope. I'm trying get PIL working on my mac OS X 10.8 so that I can use `dev_appserver.py` to test an imaging feature. First I had trouble installing PIL until I got Homebrew and installed it using `brew install pil`. I was under the opinion that brew installed all the necessary dependencies but when I tried to resize a jpeg in my app, it says `IOError: decoder jpeg is not available`. So I looked online and most places said I needed to (1) uninstall PIL, (2) install libjpeg from source and (3) reinstall PIL. So, I `brew uninstall PIL`, and then curl -O www.ijg.org/files/jpegsrc.v7.tar.gz tar zxvf jpegsrc.v7.tar.gz cd jpeg-7d/ ./configure make make install and finally `brew install pil`. I restart dev_appserver.py and reload the page on localhost, but same error. I tested pil out from the `python` command-line with >>> from PIL.Image import Image >>> f = open("someimagefile", "rb") >>> i = Image() >>> i.fromstring(f.read(), decoder_name="jpeg") Traceback blah blah blah IOError: decoder jpeg not available I don't have much experience installing utilities from command-line, so I probably missed something obvious. Again, sorry if there are duplicates, but like I said, I looked and couldn't find anything that seemed to work. Answer: Finally got it working! Thanks to @zgoda and this [link](https://sites.google.com/site/asidoothings/python-pil). Here are the steps I ended up with for those of you who have the same problem: First make sure PIL is not installed. Download libjpeg from <http://www.ijg.org/files/jpegsrc.v8c.tar.gz>, unpacked it, `./configure`, and `make`. When I tried to `make install` it couldn't find the directory to store the man pages so installation failed. I looked at the information on the above link and decided to `cp -r ~/Downloads/jpeg-6d/ /usr/local/jpeg` I suspect if the installation goes fine than that line isn't necessary. Then edit the following line in PIL's setup.py: JPEG_ROOT = None to JPEG_ROOT = "/usr/local/jpeg" finally: $ python setup.py build $ python setup.py install
Issue with finding parent of a particular tag in html using python Question: I am trying to fetch parent element of a particular tag using below mentioned code: # -*- coding: cp1252 -*- import csv import urllib2 import sys import time from bs4 import BeautifulSoup from itertools import islice page1= urllib2.urlopen('http://www.sfr.fr/mobile/telephones?vue=000029&tgp=toutes-les-offres&typesmartphone=se-android&typesmartphone=se-apple&typesmartphone=se-bada&typesmartphone=se-rim-blackberry&typesmartphone=se-windows&p=0').read() soup1 = BeautifulSoup(page1) price_parent = soup1.findParents('div') print price_parent **Problem:** Output which I am getting after running this code returns Null array `[]`, if I use `findParent` instead of Parents then also it returns `None` value. My actual problem is similar to this [BeautifulSoup - findAll not within certain tag](http://stackoverflow.com/questions/10777250/beautifulsoup- findall-not-within-certain-tag) To solve my actual problem I need to get parents of elements for which I am getting `None` value as mentioned above. Please help me in solving this issue and pardon my ignorance as I am new to programming. Answer: `.findParents()` does not do what you think it does. It finds the parents of the _current element_ that match the search. You are trying to find the parents of a page element, which is already the top-level element. If you had a structure like this: <html> <body> <div class="foo"> <span id="bar">Some text</span> </div> </body> </html> where `soup` is a BeautifulSoup variable for the whole structure, you can find the `span` with: spanelement = soup.find('span', id='bar') and then calling `.findParent('div')` will return a result, namely the `<div class="foo">` element. So, calling `.findParents()` on a top-level element will _always_ return an empty result, there _are no parents_. Call it on something that does have a parent element instead.
How to store OAuth token for Github in a Python script? Question: I am working on a Python script that access Github using basic authentication. I want to use OAuth so that user doesn't have to enter credentials every time he uses the script. Most importantly, user's password does not get saved in the `.bash_history`. This Github API has the code to get token using [Basic authentication](http://developer.github.com/v3/oauth/#create-a-new- authorization). `curl -u $USER_NAME --silent https://api.github.com/authorizations` User is asked to enter password and gets token in the response. 1. Now where do I save this token securely so that next time when the script is run user doesn't have to enter anything? 2. The aim is to avoid storing the password or asking the user to enter every time he uses the script. Is there some other way to achieve these? Answer: You should probably save the token in a config file in the user's home directory. Preferably, you can restrict permissions on the file to make sure that only that user may access the config file.
Celery - Programmatically list workers Question: How can I programmatically, using Python code, list current workers and their corresponding `celery.worker.consumer.Consumer` instances? Answer: You can use [celery.control.inspect](http://docs.celeryproject.org/en/master/userguide/workers.html#inspecting- workers) to inspect the running workers: >>> import celery >>> celery.current_app.control.inspect().ping() {u'celery@host': {u'ok': u'pong'}}
Compare list of datetimes with datetime in Python Question: I have a list of datetime objects and would like to find the ones which are within a certain time frame: import datetime dates = [ datetime.datetime(2007, 1, 2, 0, 1), datetime.datetime(2007, 1, 3, 0, 2), datetime.datetime(2007, 1, 4, 0, 3), datetime.datetime(2007, 1, 5, 0, 4), datetime.datetime(2007, 1, 6, 0, 5), datetime.datetime(2007, 1, 7, 0, 6) ] #in reality this is a list of over 25000 dates mask = (dates>datetime.datetime(2007,1,3)) & \ (dates<datetime.datetime(2007,1,6)) However, this results in the following error: "TypeError: can't compare datetime.datetime to list" How can I fix my code? Answer: You can mask a [`numpy.array`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html) in the syntax you describe _(but not a list)_ : import numpy as np date1 = np.array(dates) mask = (dates1 > datetime.datetime(2007,1,3)) & \ (dates1 < datetime.datetime(2007,1,6)) In [14]: mask Out[14]: array([False, True, True, True, False, False], dtype=bool) In [15]: dates1[mask] Out[15]: array([2007-01-03 00:02:00, 2007-01-04 00:03:00, 2007-01-05 00:04:00], dtype=object) _(since this question is tagged numpy, presumably this is what you were intending.)_
Passing parameters to a webapp2.RequestHandler object in python Question: Is there any way to pass parameters to a RequestHandler object when I create my WSGIApplication instance? I mean app = webapp2.WSGIApplication([ ('/', MainHandler), ('/route1', Handler1), ('/route2', Handler2) ], debug=True) Is it possible to pass some arguments to `MainHandler`, `Handler1` or `Handler2`? Thanks in advance Answer: You can also pass parameters through a configuration dictionary. First you define a configuration: import webapp2 config = {'foo': 'bar'} app = webapp2.WSGIApplication(routes=[ (r'/', 'handlers.MyHandler'), ], config=config) Then access it as you need. Inside a RequestHandler, for example: import webapp2 class MyHandler(webapp2.RequestHandler): def get(self): foo = self.app.config.get('foo') self.response.write('foo value is %s' % foo) From here: [webapp2 v2.5.1 documentation](http://webapp- improved.appspot.com/guide/app.html#guide-app-config)
Python - Convert negative decimals from string to float Question: I need to read in a large number of .txt files, each of which contains a decimal (some are positive, some are negative), and append these into 2 arrays (genotypes and phenotypes). Subsequently, I wish to perform some mathematical operations on these arrays in scipy, however the negative ('-') symbol is causing problems. Specifically, I cannot convert the arrays to float, because the '-' is being read as a string, causing the following error: ValueError: could not convert string to float: Here is my code as it's currently written: import linecache gene_array=[] phen_array=[] for i in genotype: for j in phenotype: genotype='/path/g.txt' phenotype='/path/p.txt' g=linecache.getline(genotype,1) p=linecache.getline(phenotype,1) p=p.strip() g=g.strip() gene_array.append(g) phen_array.append(p) gene_array=map(float,gene_array) phen_array=map(float,phen_array) I am fairly certain at this point that it is the negative sign that is causing the problem, but it is not clear to me why. Is my use of Linecache the problem here? Is there an alternative method that would be better? The result of print gene_array is ['-0.0448022516321286', '-0.0236187263814157', '-0.150505384829925', '-0.00338459268479522', '0.0142429109897682', '0.0286253352284279', '-0.0462358095345649', '0.0286232317578776', '-0.00747425206137217', '0.0231790239373428', '-0.00266935581919541', '0.00825077426011094', '0.0272744527203547', '0.0394829854063242', '0.0233109171715023', '0.165841084392078', '0.00259693465334536', '-0.0342590874424289', '0.0124600520095644', '0.0713627590092807', '-0.0189374898081401', '-0.00112750710611284', '-0.0161387333242288', '0.0227226505624106', '0.0382173405035751', '0.0455518646388402', '-0.0453048799717046', '0.0168570746329513'] Answer: The issue seems to be with empty string or space as evident from your error message ValueError: could not convert string to float: To make it work, convert the map to a list comprehension gene_array=[float(e) for e in gene_array if e] phen_array=[float(e) for e in phen_array if e] By empty string means `float(" ")` or `float("")` would give value errors, so if any of the items within `gene_array` or `phen_array` has space, this will throw an error while converting to float There could be many reasons for empty string like * empty or blank line * blank line either at the beginning or end
why does python require __init__.py to treat directories as containing packages? Question: While going through 6.4 Packages section of [python manual](http://docs.python.org/2/tutorial/modules.html) I came across the following line: > The `__init__.py` files are required to make Python treat the directories as > containing packages; this is done to prevent directories with a common name, > such as string, from unintentionally hiding valid modules that occur later > on the module search path. I understand that `__init__.py` is required to mark directories as containing packages, but I don't understand what it means by `prevent directories with a common name...from unintentionally hiding valid modules...`. Could someone explain why the `__init__.py` is required? Answer: Lets say you had a project that contained a directory called `math` that contained some numerical data. If no `__init__.py` were required, then when you did `import math`, it would try to import that directory instead of the real `math` module. But since your directory just contained data and not actual Python code, the import would fail. Thus your `math` directory would block you from importing the real `math` module from the standard library, even though your `math` directory doesn't contain Python code at all. The `__init__.py` is like a confirmation, the directory saying "Yes, I really am a Python package, not just a directory full of files. It makes sense to import me." Any directories that don't "announce" themselves in this way are skipped over because Python knows they can't be imported. This is good, because the Python standard library has modules with lots of common names (os, math, time, symbol, resource, etc.). Without the `__init__.py` requirement, you would never be able to use any of those names for _any_ directory on your Python path -- not even to store data or files unrelated to Python. `string` is actually not the best example in this case. There is a module called `string` but it is not so useful these days because most of its functions are available as methods on the `str` type. But, like I mentioned, there are lots of other modules with common names.
IncompleteRead using httplib Question: I have been having a persistent problem getting an rss feed from a particular website. I wound up writing a rather ugly procedure to perform this function, but I am curious why this happens and whether any higher level interfaces handle this problem properly. This problem isn't really a show stopper, since I don't need to retrieve the feed very often. I have read a solution that traps the exception and returns the partial content, yet since the incomplete reads differ in the amount of bytes that are actually retrieved, I have no certainty that such solution will actually work. #!/usr/bin/env python import os import sys import feedparser from mechanize import Browser import requests import urllib2 from httplib import IncompleteRead url = 'http://hattiesburg.legistar.com/Feed.ashx?M=Calendar&ID=543375&GUID=83d4a09c-6b40-4300-a04b-f88884048d49&Mode=2013&Title=City+of+Hattiesburg%2c+MS+-+Calendar+(2013)' content = feedparser.parse(url) if 'bozo_exception' in content: print content['bozo_exception'] else: print "Success!!" sys.exit(0) print "If you see this, please tell me what happened." # try using mechanize b = Browser() r = b.open(url) try: r.read() except IncompleteRead, e: print "IncompleteRead using mechanize", e # try using urllib2 r = urllib2.urlopen(url) try: r.read() except IncompleteRead, e: print "IncompleteRead using urllib2", e # try using requests try: r = requests.request('GET', url) except IncompleteRead, e: print "IncompleteRead using requests", e # this function is old and I categorized it as ... # "at least it works darnnit!", but I would really like to # learn what's happening. Please help me put this function into # eternal rest. def get_rss_feed(url): response = urllib2.urlopen(url) read_it = True content = '' while read_it: try: content += response.read(1) except IncompleteRead: read_it = False return content, response.info() content, info = get_rss_feed(url) feed = feedparser.parse(content) As already stated, this isn't a mission critical problem, yet a curiosity, as even though I can expect urllib2 to have this problem, I am surprised that this error is encountered in mechanize and requests as well. The feedparser module doesn't even throw an error, so checking for errors depends on the presence of a 'bozo_exception' key. Edit: I just wanted to mention that both wget and curl perform the function flawlessly, retrieving the full payload correctly every time. I have yet to find a pure python method to work, excepting my ugly hack, and I am very curious to know what is happening on the backend of httplib. On a lark, I decided to also try this with twill the other day and got the same httplib error. P.S. There is one thing that also strikes me as very odd. The IncompleteRead happens consistently at one of two breakpoints in the payload. It seems that feedparser and requests fail after reading 926 bytes, yet mechanize and urllib2 fail after reading 1854 bytes. This behavior is consistend, and I am left without explanation or understanding. Answer: At the end of the day, all of the other modules (`feedparser`, `mechanize`, and `urllib2`) call `httplib` which is where the exception is being thrown. Now, first things first, I also downloaded this with wget and the resulting file was 1854 bytes. Next, I tried with `urllib2`: >>> import urllib2 >>> url = 'http://hattiesburg.legistar.com/Feed.ashx?M=Calendar&ID=543375&GUID=83d4a09c-6b40-4300-a04b-f88884048d49&Mode=2013&Title=City+of+Hattiesburg%2c+MS+-+Calendar+(2013)' >>> f = urllib2.urlopen(url) >>> f.headers.headers ['Cache-Control: private\r\n', 'Content-Type: text/xml; charset=utf-8\r\n', 'Server: Microsoft-IIS/7.5\r\n', 'X-AspNet-Version: 4.0.30319\r\n', 'X-Powered-By: ASP.NET\r\n', 'Date: Mon, 07 Jan 2013 23:21:51 GMT\r\n', 'Via: 1.1 BC1-ACLD\r\n', 'Transfer-Encoding: chunked\r\n', 'Connection: close\r\n'] >>> f.read() < Full traceback cut > IncompleteRead: IncompleteRead(1854 bytes read) So it is reading all 1854 bytes but then thinks there is more to come. If we explicitly tell it to read only 1854 bytes it works: >>> f = urllib2.urlopen(url) >>> f.read(1854) '\xef\xbb\xbf<?xml version="1.0" encoding="utf-8"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">...snip...</rss>' Obviously, this is only useful if we always know the exact length ahead of time. We can use the fact the partial read is returned as an attribute on the exception to capture the entire contents: >>> try: ... contents = f.read() ... except httplib.IncompleteRead as e: ... contents = e.partial ... >>> print contents '\xef\xbb\xbf<?xml version="1.0" encoding="utf-8"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">...snip...</rss>' [This blog post](http://bobrochel.blogspot.co.nz/2010/11/bad-servers-chunked- encoding-and.html) suggests this is a fault of the server, and describes how to monkey-patch the `httplib.HTTPResponse.read()` method with the `try..except` block above to handle things behind the scenes: import httplib def patch_http_response_read(func): def inner(*args): try: return func(*args) except httplib.IncompleteRead, e: return e.partial return inner httplib.HTTPResponse.read = patch_http_response_read(httplib.HTTPResponse.read) I applied the patch and then `feedparser` worked: >>> import feedparser >>> url = 'http://hattiesburg.legistar.com/Feed.ashx?M=Calendar&ID=543375&GUID=83d4a09c-6b40-4300-a04b-f88884048d49&Mode=2013&Title=City+of+Hattiesburg%2c+MS+-+Calendar+(2013)' >>> feedparser.parse(url) {'bozo': 0, 'encoding': 'utf-8', 'entries': ... 'status': 200, 'version': 'rss20'} This isn't the nicest way of doing things, but it seems to work. I'm not expert enough in the HTTP protocols to say for sure whether the server is doing things wrong, or whether `httplib` is mis-handling an edge case.
Twitter API Python Character Encoding Question: I am experimenting with the Twitter API for Python and have run into a character encoding/decoding issue; when I am collecting tweets for a user (@BBCWorld in this instance), if there is _special_ punctuation I receive the following error: 286952044814794753 : Traceback (most recent call last): File "C:\Python27\lib\encodings\cp850.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\u201c' in position 0: character maps to <undefined> Note: The long number at the start is the ID of the tweet causing the error. The specific character that is causing this problem is an angular (opening) double quotation mark (like those used in MS-Word). Is there a way to display such punctuation in a compatible form? Ideally I want to sanitise tweets to overcome this kind of error by use of replacement, therefore maintaining context, rather that omitting characters. This is the core of the code: tweets=api.GetUserTimeline('BBCWorld') try: for tweet in tweets: print tweet.id, ": ", (tweet.text) except UnicodeEncodeError as uee: print uee Thanks for any pointers, Milutin Answer: This problem does not seem to be an issue of python-twitter or python for that matter - it's a problem with Windows cmd. If you try this under a suitable Unix terminal, this is what you get: >>> import twitter >>> api = twitter.Api() >>> print api.GetStatus('286952044814794753').text “How do you change mindsets at a societal level, in a country of 1.2bn people?” - Viewpoints from India http://t.co/RiP4t71q #Delhigangrape Take a look at this question for a discussion of how to deal with this under Windows: [Unicode not printing correctly to cp850 (cp437), play card suits](http://stackoverflow.com/questions/4233227/unicode-not-printing- correctly-to-cp850-cp437-play-card-suits) My best bet for you would be to change your console font and codepage to a unicode compliant, as outlined here: <http://stackoverflow.com/a/4234515/679897> or here: <http://www.velocityreviews.com/forums/t717717-python-unicode-and-windows-cmd- exe.html>
Importing Python Librarys over C#? Question: So I'm new to Python and I work with IronPython in Visual Studio. So in my C# Project I call the Python Script for executing some tasks. Now I work in a bigger company and so a lot of File Paths etc. are different. And I'm wondering if it's possible to pass the Python file a Path, and then import the Modules (for example urlib) from this path. So in C# with IronPython it's possible to execute a Python script with var ipy = Python.CreateRuntime(); dynamic PYthon_Script = ipy.UseFile("test.py"); And in my Python SCript I got the following Code: import sys path = "C:\Program Files (x86)\IronPython 2.7\Lib" sys.path.append(path) import urllib import httplib ... So I was wondering if it's possible to pass a parameter for the variable path, so sys.path.append(path) will change with the parameter given and the libraries are imported correctly. Answer: You just want to pass a parameter to the script? Sure, that's easy. The main way to do that is by using `sys.argv`: import sys path = sys.argv[1] sys.path.append(path) import urllib import httplib Then instead of doing this: py.exe myscript.py You do this: py.exe myscript.py "C:\Program Files (x86)\IronPython 2.7\Lib" If you're running this directly from within a .NET launcher program, you can also just insert the variable dynamically: PYthon_Script.SetVariable("path", "C:\Program Files (x86)\IronPython 2.7\Lib") Then, from within the script, you can use that variable. Or you can even modify `sys.path` itself from the launcher. See the `Runtime` docs for details. If you want to add multiple paths, just change these two lines: paths = sys.argv[1:] sys.path.extend(paths) If you want something that sticks around in your environment, so you don't have to pass it every time, that's what environment variables are for. There's actually a standard environment variable named `IRONPYTHONPATH` that should work without you having to do anything. I've never used it myself, but if it works, you don't need to do anything explicit in your code at all. Just set it in your `cmd.exe` shell, in your Control Panel, in the C# program you're launching `myscript.py` from, whatever's appropriate. [This answer](http://stackoverflow.com/questions/3701646/how-to-add-to-the- pythonpath-in-windows-7) has examples for the first two. (They're setting `PYTHONPATH`, which affects CPython, instead of `IRONPYTHONPATH`, which affects IronPython, but it should be obvious what to change.) If that doesn't work, you can do the same thing manually: import os import sys path = os.environ['MY_IRONPYTHON_EXTRA_PATH'] sys.path.append(path) import urllib import httplib Now, you can set that `MY_IRONPYTHON_EXTRA_PATH` environment variable instead of `IRONPYTHON_PATH`. Here, because you just have a string instead of a list, if you want to specify multiple paths, you need to add a separator. The standard path separator on Windows is a semicolon. So: paths = os.environ['MY_IRONPYTHON_EXTRA_PATH'].split(';') sys.path.extend(paths)
When is __lldb_init_module called? Question: I'm following WWDC session 412 - Debugging in Xcode. There is a demo there about creating custom LLDB summaries for your own classes. I simply can't get the summaries to show up. By inserting print calls in the Python script I have been able to determine that: 1. The script file is getting imported 2. __lldb_init_module is never called Any idea about what could prevent __lldb_init_module from being called? Is there a specific time when you need to import the script? Answer: For me this worked by adding command script import /path/to/CustomSummaries.py to the `~/.lldbinit` file and restarting Xcode, or by setting a breakpoint in "main" and executing the import command in the debugger console. I tested it with a minimal custom description script: import lldb def myobject_summary(valueObject, dictionary): return 'MyCustomDescription' def __lldb_init_module(debugger, dict): debugger.HandleCommand('type summary add MyObject -F CustomSummaries.myobject_summary') and this is the view in the Xcode debugger window: ![enter image description here](http://i.stack.imgur.com/J9cFd.png) Note that you have to restart Xcode after changes to the script. It also seems that the output of "print" statements in the init method is not shown if the script is imported in the Xcode debugger console.
Python: compare list items to dictionary keys twice in one for loop? Question: ## I'm stuck in a script I have to write and can't find a way out... I have two files with partly overlapping information. Based on the information in one file I have to extract info from the other and save it into multiple new files. The first is simply a table with IDs and group information (which is used for the splitting). The other contains the same IDs, but each twice with slightly different information. **What I'm doing:** I create a list of lists with ID and group informazion, like this: table = [[ID, group], [ID, group], [ID, group], ...] Then, because the second file is huge and not sorted in the same way as the first, I want to create a dictionary as index. In this index, I would like to save the ID and where it can be found inside the file so I can quickly jump there later. The problem there, of course, is that every ID appears twice. My simple solution (but I'm in doubt about this) is adding an -a or -b to the ID: index = {"ID-a": [FPos, length], "ID-b": [FPOS, length], "ID-a": [FPos, length], ...} The code for this: for line in file: read = (line.split("\t"))[0] if not (read+"-a") in indices: index = read + "-a" length = len(line) indices[index] = [FPos, length] else: index = read + "-b" length = len(line) indices[index] = [FPos, length] FPos += length What I am wondering now is if the next step is actually valid (I don't get errors, but I have some doubts about the output files). for name in table: head = name[0] ## first round (FPos,length) = indices[head+"-a"] file.seek(FPos) line = file.read(length) line = line.rstrip() items = line.split("\t") output = ["@" + head +" "+ "1:N:0:" +"\n"+ items[9] +"\n"+ "+" +"\n"+ items[10] +"\n"] name.append(output) ##second round (FPos,length) = indices[head+"-b"] file.seek(FPos) line = file.read(length) line = line.rstrip() items = line.split("\t") output = ["@" + head +" "+ "2:N:0:" +"\n"+ items[9] +"\n"+ "+" +"\n"+ items[10] +"\n"] name.append(output) Is it ok to use a for loop like that? Is there a better, cleaner way to do this? Answer: Use a `defaultdict(list)` to save all your file offsets by ID: from collections import defaultdict index = defaultdict(list) for line in file: # ...code that loops through file finding ID lines... index[id_value].append((fileposn,length)) The [defaultdict](http://docs.python.org/2/library/collections.html#collections.defaultdict) will take care of initializing to an empty list on the first occurrence of a given id_value, and then the (fileposn,length) tuple will be appended to it. This will accumulate all references to each id into the index, whether there are 1, 2, or 20 references. Then you can just search through the given fileposn's for the related data.
Converting nested JSON content dump to XLS Question: I have a JSON dump from a content management site which follows the format: [ { id: "obj1", children: [...] }, { id: "obj2", children: [...] } ] There are 2-4 nesting levels. What would be the best way to convert this to Microsoft Excel XLS so that nested levels are handled somehow, for the Excel-able customer to play with their data? With this particular data, one way to do this would create a new sheet for each top level folder (nesting level). All sheets would contain the same column names picked from the JSON objects in that particular folder. Are there any ready-made tools for importing JSON to Excel? Preferably as a command-line tool and if scripting is required then in Python. Answer: It depends on your data. If the nesting happens without any kind of repetition then simplest option is to replicate everything or leave blank spaces if your data is complete enough to be able to assume a repetition where you find a blank. This means the XLS as a CSV will look like this: Element1 Element1.1 Element1.1.1 ... Element1 Element1.1 Element1.1.2 ... Element2 Element2.1 Element2.1.1 ... Where each element is a child of the one at its left. You can see a parent repeats as many times as children it has multiplied by how many times does each of the children appear. You can also do a very simple table with two columns: **Parent** **Child** Element1 Element1.1 Element1.1 Element1.1.1 Element1.1 Element1.1.2 Element2 Element2.1 Element2.1 Element2.1.1 ... What an element is depends on your granularity. You can group pairs of key=values as a string, you can group several fields into one and parse it back with regular expressions, or you can separate everything and consider the key as an element and the value as another one. Finally, if there is some regularity then you can take a more interesting approach, assume you have some repeating fieldnames, in that case you can take any of the previous approaches but using the fieldnames to generate a matrix instead of a list. The first example is trivial since it is obviously a tuple list that does already have an implicit ordinal header, the second one is a table and may look like a matrix already, but you can do this. **Parent** **Child (default)** **Repeating key1** **Repeating key2** e1 e1.1 e1.1 e1.1.1 e.1.1.1 something e.1.1 e.1.1.2 e.1.1.2 somethingelse So basically in the end you have a sparse matrix. There are very interesting ways to store matrixes with three dimensions using several sheets on an XLS, but human-readability may drop with it. It boils down to the data you are using, **there is no general solution**.
Memory leak in tornado generator engine with try/finally block when connections are closed Question: This awesome code, shows memory leak in tornado's `gen` module, when connections are closed without reading the response: import gc from tornado import web, ioloop, gen class MainHandler(web.RequestHandler): @web.asynchronous @gen.engine def get(self): gc.collect() print len(gc.garbage) # print zombie objects count self.a = '*' * 500000000 # ~500MB data CHUNK_COUNT = 100 try: for i in xrange(CHUNK_COUNT): self.write('*' * 10000) # write ~10KB of data yield gen.Task(self.flush) # wait for reciever to recieve print 'finished' finally: print 'finally' application = web.Application([ (r"/", MainHandler), ]) application.listen(8888) ioloop.IOLoop.instance().start() and now, run a simple test client, multiple times #!/usr/bin/python import urllib urlopen('http://127.0.0.1:8888/') # exit without reading response Now, server output shows, incremental memory usage: 0 WARNING:root:Write error on 8: [Errno 104] Connection reset by peer 1 WARNING:root:Read error on 8: [Errno 104] Connection reset by peer WARNING:root:error on read Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/iostream.py", line 361, in _handle_read if self._read_to_buffer() == 0: File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/iostream.py", line 428, in _read_to_buffer chunk = self._read_from_socket() File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/iostream.py", line 409, in _read_from_socket chunk = self.socket.recv(self.read_chunk_size) error: [Errno 104] Connection reset by peer 2 ERROR:root:Uncaught exception GET / (127.0.0.1) HTTPRequest(protocol='http', host='127.0.0.1:8888', method='GET', uri='/', version='HTTP/1.0', remote_ip='127.0.0.1', body='', headers={'Host': '127.0.0.1:8888', 'User-Agent': 'Python-urllib/1.17'}) Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/web.py", line 1021, in _stack_context_handle_exception raise_exc_info((type, value, traceback)) File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/web.py", line 1139, in wrapper return method(self, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/gen.py", line 120, in wrapper runner.run() File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.1-py2.7.egg/tornado/gen.py", line 345, in run yielded = self.gen.send(next) File "test.py", line 10, in get self.a = '*' * 500000000 MemoryError ERROR:root:500 GET / (127.0.0.1) 3.91ms If you set `CHUNK_COUNT` to 1, the 10KB of data can be written to OS connection buffer, and 'finished' and 'finally' texts will be printed to console, and because generator is completed, no memory leak occurs. **But the strange part** is that if your remove the try/finally block, the problem disappears!! (even with `CHUNK_COUNT` set to 100) Is this a bug on CPython or tornado or ...?! Answer: This bug tested with Tornado 2.4.1 (the latest version when this question asked), and reported on <https://github.com/facebook/tornado/issues/660> . The problem fixed in commit <https://github.com/facebook/tornado/commit/769bc52e11656788782a6e7a922ef646503f9ab0> and included in Tornado 3.0.
socket programming in python doubts Question: i am having trouble and a lot of questions about socket programming attached code below ( all parts have been taken from the and written together) i am trying to send mouse data to the client ,howver getting the error: Traceback (most recent call last): File "srvr.py", line 29, in <module> serv.sendall(status) File "/usr/lib/python2.7/socket.py", line 224, in meth return getattr(self._sock,name)(*args) TypeError: must be string or buffer, not int Questions: 1.how do we send data over sockets other then strings or specifically without the .send("...") statement .continously changing data?? 2.what things should be kept in mind when sending stream of data?? 3.code written here is a mess, would gladly appreciate help to teach some code sense into me Thank YOu Code: server side: from socket import * #import the socket library ##let's set up some constants HOST = '' #we are the host PORT = 29876 #arbitrary port not currently in use ADDR = (HOST,PORT) #we need a tuple for the address BUFSIZE = 4096 #reasonably sized buffer for data ## now we create a new socket object (serv) ## see the python docs for more information on the socket types/flags serv = socket( AF_INET,SOCK_STREAM) ##bind our socket to the address serv.bind((ADDR)) #the double parens are to create a tuple with one element serv.listen(5) print 'listening...' conn,addr = serv.accept() #accept the connection print '...connected!' mouse = file('/dev/input/mouse0') while True: status, dx, dy = tuple(ord(c) for c in mouse.read(3)) def to_signed(n): return n - ((0x80 & n) << 1) dx = to_signed(dx) dy = to_signed(dy) conn.send(status) conn.close() client: ##client.py from socket import * HOST = 'localhost' PORT = 29876 #our port from before ADDR = (HOST,PORT) BUFSIZE = 4096 cli = socket( AF_INET,SOCK_STREAM) cli.connect((ADDR)) data = cli.recv(BUFSIZE) while data != '': print data cli.close() Answer: While transferring data over network, it is very usual to pack it according to the big-endian byte order. Even though you have only three separates bytes at a time, and thus byte ordering doesn't matter, I still prefer to pack and unpack simply because it is a common way to communicate. Also, a common thing to do, when receiving network data, is to check whether you actually received the amount you were expecting, otherwise you have to request for more data. For simplicity, consider the following function for that: def recv(sock, size): data = '' to_receive = size while to_receive > 0: data += sock.recv(to_receive) to_receive = size - len(data) return data Now, what is lacking in your code is a common protocol. The client is acting as a receiver of raw meaningless data. Instead, it should be acting as a receiver of triplets. Besides that, I suggest to let the client request how many triplets he wants. Taking this into consideration, that is how I would change your client code to: import sys import socket import struct serv_host = '' serv_port = 29876 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((serv_host, serv_port)) # Tell the server how many triplets I want. amount = int(sys.argv[1]) s.sendall(struct.pack('!i', amount)) pack_size = struct.calcsize('!bbb') while amount: status, dx, dy = struct.unpack('!bbb', recv(s, pack_size)) print status, dx, dy amount -= 1 s.close() Now the server also needs to respect this newly imposed protocol. Note that a negative value effectively makes the client receive infinite triplets, that is intentional. Here is the modified server: import socket import struct def to_signed(n): return n - ((0x80 & n) << 1) mouse = open('/dev/input/mouse0') host = '' port = 29876 backlog = 5 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port)) s.listen(backlog) print 'Listening' while True: client, address = s.accept() # Obtain the number of triplets the client wants. amount = struct.unpack('!i', recv(client, 4))[0] while amount: # Send the triplets as they become available. status, dx, dy = map(ord, mouse.read(3)) dx, dy = to_signed(dx), to_signed(dy) print status, dx, dy client.sendall(struct.pack('!bbb', status, dx, dy)) amount -= 1 client.close()
How to use multiprocessing with class instances in Python? Question: I am trying to create a class than can run a separate process to go do some work that takes a long time, launch a bunch of these from a main module and then wait for them all to finish. I want to launch the processes once and then keep feeding them things to do rather than creating and destroying processes. For example, maybe I have 10 servers running the dd command, then I want them all to scp a file, etc. My ultimate goal is to create a class for each system that keeps track of the information for the system in which it is tied to like IP address, logs, runtime, etc. But that class must be able to launch a system command and then return execution back to the caller while that system command runs, to followup with the result of the system command later. My attempt is failing because I cannot send an instance method of a class over the pipe to the subprocess via pickle. Those are not pickleable. I therefore tried to fix it various ways but I can't figure it out. How can my code be patched to do this? What good is multiprocessing if you can't send over anything useful? Is there any good documentation of multiprocessing being used with class instances? The only way I can get the multiprocessing module to work is on simple functions. Every attempt to use it within a class instance has failed. Maybe I should pass events instead? I don't understand how to do that yet. import multiprocessing import sys import re class ProcessWorker(multiprocessing.Process): """ This class runs as a separate process to execute worker's commands in parallel Once launched, it remains running, monitoring the task queue, until "None" is sent """ def __init__(self, task_q, result_q): multiprocessing.Process.__init__(self) self.task_q = task_q self.result_q = result_q return def run(self): """ Overloaded function provided by multiprocessing.Process. Called upon start() signal """ proc_name = self.name print '%s: Launched' % (proc_name) while True: next_task_list = self.task_q.get() if next_task is None: # Poison pill means shutdown print '%s: Exiting' % (proc_name) self.task_q.task_done() break next_task = next_task_list[0] print '%s: %s' % (proc_name, next_task) args = next_task_list[1] kwargs = next_task_list[2] answer = next_task(*args, **kwargs) self.task_q.task_done() self.result_q.put(answer) return # End of ProcessWorker class class Worker(object): """ Launches a child process to run commands from derived classes in separate processes, which sit and listen for something to do This base class is called by each derived worker """ def __init__(self, config, index=None): self.config = config self.index = index # Launce the ProcessWorker for anything that has an index value if self.index is not None: self.task_q = multiprocessing.JoinableQueue() self.result_q = multiprocessing.Queue() self.process_worker = ProcessWorker(self.task_q, self.result_q) self.process_worker.start() print "Got here" # Process should be running and listening for functions to execute return def enqueue_process(target): # No self, since it is a decorator """ Used to place an command target from this class object into the task_q NOTE: Any function decorated with this must use fetch_results() to get the target task's result value """ def wrapper(self, *args, **kwargs): self.task_q.put([target, args, kwargs]) # FAIL: target is a class instance method and can't be pickled! return wrapper def fetch_results(self): """ After all processes have been spawned by multiple modules, this command is called on each one to retreive the results of the call. This blocks until the execution of the item in the queue is complete """ self.task_q.join() # Wait for it to to finish return self.result_q.get() # Return the result @enqueue_process def run_long_command(self, command): print "I am running number % as process "%number, self.name # In here, I will launch a subprocess to run a long-running system command # p = Popen(command), etc # p.wait(), etc return def close(self): self.task_q.put(None) self.task_q.join() if __name__ == '__main__': config = ["some value", "something else"] index = 7 workers = [] for i in range(5): worker = Worker(config, index) worker.run_long_command("ls /") workers.append(worker) for worker in workers: worker.fetch_results() # Do more work... (this would actually be done in a distributor in another class) for worker in workers: worker.close() Edit: I tried to move the `ProcessWorker` class and the creation of the multiprocessing queues outside of the `Worker` class and then tried to manually pickle the worker instance. Even that doesn't work and I get an error > RuntimeError: Queue objects should only be shared between processes through > inheritance . But I am only passing references of those queues into the worker instance?? I am missing something fundamental. Here is the modified code from the main section: if __name__ == '__main__': config = ["some value", "something else"] index = 7 workers = [] for i in range(1): task_q = multiprocessing.JoinableQueue() result_q = multiprocessing.Queue() process_worker = ProcessWorker(task_q, result_q) worker = Worker(config, index, process_worker, task_q, result_q) something_to_look_at = pickle.dumps(worker) # FAIL: Doesn't like queues?? process_worker.start() worker.run_long_command("ls /") Answer: So, the problem was that I was assuming that Python was doing some sort of magic that is somehow different from the way that C++/fork() works. I somehow thought that Python only copied the class, not the whole program into a separate process. I seriously wasted days trying to get this to work because all of the talk about pickle serialization made me think that it actually sent everything over the pipe. I knew that certain things could not be sent over the pipe, but I thought my problem was that I was not packaging things up properly. This all could have been avoided if the Python docs gave me a 10,000 ft view of what happens when this module is used. Sure, it tells me what the methods of multiprocess module does and gives me some basic examples, but what I want to know is what is the "Theory of Operation" behind the scenes! Here is the kind of information I could have used. Please chime in if my answer is off. It will help me learn. When you run start a process using this module, the whole program is copied into another process. But since it is not the "`__main__`" process and my code was checking for that, it doesn't fire off yet another process infinitely. It just stops and sits out there waiting for something to do, like a zombie. Everything that was initialized in the parent at the time of calling multiprocess.Process() is all set up and ready to go. Once you put something in the multiprocess.Queue or shared memory, or pipe, etc. (however you are communicating), then the separate process receives it and gets to work. It can draw upon all imported modules and setup just as if it was the parent. However, once some internal state variables change in the parent or separate process, those changes are isolated. Once the process is spawned, it now becomes your job to keep them in sync if necessary, either through a queue, pipe, shared memory, etc. I threw out the code and started over, but now I am only putting one extra function out in the `ProcessWorker`, an "execute" method that runs a command line. Pretty simple. I don't have to worry about launching and then closing a bunch of processes this way, which has caused me all kinds of instability and performance issues in the past in C++. When I switched to launching processes at the beginning and then passing messages to those waiting processes, my performance improved and it was very stable. BTW, I looked at this link to get help, which threw me off because the example made me think that methods were being transported across the queues: <http://www.doughellmann.com/PyMOTW/multiprocessing/communication.html> The second example of the first section used "next_task()" that appeared (to me) to be executing a task received via the queue.
convert date to number python Question: > **Possible Duplicate:** > [Fetching datetime from float and vice versa in > python](http://stackoverflow.com/questions/6706231/fetching-datetime-from- > float-and-vice-versa-in-python) Like many people I switched from `Matlab` to `Python`. `Matlab` represents each date as a number. (`Integers` being days since `00-00-0000`, and fractions being time in the day). I believe that `python` does the same except off a different start date `0-0-0001` I have been playing around with `datetime`, but cant seem to get away from `datetime` objects and `timedeltas`. I am sure this is dead simple, but how do I work with plain old numbers (floats)? perhaps as a bit of context: i bring in a date and time stamp and concatenate them to make one time value: from datetime import datetime date_object1 = datetime.strptime(date[1][0] + ' ' + date[1][1], '%Y-%m-%d %H:%M:%S') date_object2 = datetime.strptime(date[2][0] + ' ' + date[2][1], '%Y-%m-%d %H:%M:%S') Answer: Try this out: import time from datetime import datetime t = datetime.now() t1 = t.timetuple() print time.mktime(t1) It prints out a decimal representation of your date.
How do I check gnome-shell notifications with Python? Question: I'm having quite some trouble doing that : I'm using Conky on my Archlinux distro and coded a quick script in python to check if I have a new mail in my gmail. In my conkyrc this script executes every 5 minutes and returns a number of mails (0 if I don't have any). Works fine. What I wanted to do is : If the number of mail is > 0 then display a notification (a gnome-shell notification). The only problem I have now is that if I have unread mails (for example 4 mails unread), each 5 minutes, there will be a NEW notification saying that I have 4 mails unread. What I would like to do is checking if there is already a notification so that I don't have to display it again... Does anyone know how to solve that kind of problem ? Here is my code : #!/usr/bin/python from gi.repository import Notify from urllib.request import FancyURLopener url = 'https://%s:%[email protected]/mail/feed/atom' % ("username", "password") opener = FancyURLopener() page = opener.open(url) contents = page.read().decode('utf-8') ifrom = contents.index('<fullcount>') + 11 ito = contents.index('</fullcount>') unread = contents[ifrom:ito] print(unread) if unread != "0" : Notify.init ("New Mail") Hello=Notify.Notification.new ("New mail","You have "+unread+" new mail(s)","/usr/share/icons/Faenza/actions/96/mail-forward.png") Hello.show () I must precise that I'm quite new to python. Thanks in advance if anyone got a solution :) Answer: One possible solution is serialise the value of unread into a file. Then change your check from if the number of mails is greater than 0, to if the number of mails is greater than zero or different from the last serialised count from file. An extension of this is to also serialise the time when a notification is run along with the mail count, this way you extend the check to show the repeat notification (showing 4 emails twice, not every 5 minutes say, but every 3 hours). So your original check was `if unread != "0" :` it would become something like `if unread != "0" && unread != serialisedvalue:` . In the show repeat notification time threshold case it becomes if unread != "0": if ((datetime.now() - serialiseddate) < threshold) : if unread != serialisedvalue: Where `threshold = 3600*3` is for 3 hours. Sample code for serialising and deserialising is below #Serialising try: # This will create a new file or **overwrite an existing file**. f = open("mailcount.txt", "w") try: f.write(unread + "\n") # Write a string to a file f.write(datetime.now().strftime('%b %d %Y %I:%M%p')) finally: f.close() except IOError: pass #Deserialising try: f = open("mailcount.txt", "r") try: # Read the entire contents of a file at once. serialisedvalue = f.readline() serialseddate = datetime.strptime(f.readline(), '%b %d %Y %I:%M%p') finally: f.close() except IOError: pass Another possible solution would be to get the current active notification count somehow and add that to your condition, though I couldn't find a method for doing that using the [API that Notify uses](http://developer.gnome.org/libnotify/0.7/).
Reading Chinese characters in a file and sending them to a browser Question: I'm trying to make a program that: * reads a list of Chinese characters from a file, makes a dictionary from them (associating a sign with its meaning). * picks a random character and sends it to the browser using the `BaseHTTPServer` module when it gets a GET request. Once I managed to read and store the signs properly (I tried writing them into another file to check that I got them right and it worked) I couldn't figure out how to send them to my browser. I connect to 127.0.0.1:4321 and the best I've managed is to get a (supposedly) url-encoded Chinese character, with its translation. Code: # -*- coding: utf-8 -*- import codecs from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from SocketServer import ThreadingMixIn import threading import random import urllib source = codecs.open('./signs_db.txt', 'rb', encoding='utf-16') # Checking utf-16 works fine with chinese characters and stuff : #out = codecs.open('./test.txt', 'wb', encoding='utf-16') #for line in source: # out.write(line) db = {} next(source) for line in source: if not line.isspace(): tmp = line.split('\t') db[tmp[0]] = tmp[1].strip() class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() message = threading.currentThread().getName() rKey = random.choice(db.keys()) self.wfile.write(urllib.quote(rKey.encode("utf-8")) + ' : ' + db[rKey]) self.wfile.write('\n') return class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Handle requests in a separate thread.""" if __name__ == '__main__': server = ThreadedHTTPServer(('localhost', 4321), Handler) print 'Starting server, use <Ctrl-C> to stop' server.serve_forever() If I don't urlencode the chinese character, I get an error from python : self.wfile.write(rKey + ' : ' + db[rKey]) Which gives me this: > UnicodeEncodeError : 'ascii' codec can't encode character u'\u4e09' in > position 0 : ordinal not in range(128) I've also tried encoding/decoding with 'utf-16', and I still get that kind of error messages. Here is my test file: Sign Translation 一 One 二 Two 三 Three 四 Four 五 Five 六 Six 七 Seven 八 Eight 九 Nine 十 Ten So, my question is: "How can I get the Chinese characters coming from my script to display properly in my browser"? Answer: Declare the encoding of your page by writing a meta tag and make sure to encode the entire Unicode string in UTF-8: self.wfile.write(u'''\ <html> <headers> <meta http-equiv="content-type" content="text/html;charset=UTF-8"> </headers> <body> {} : {} </body> </html>'''.format(rKey,db[rKey]).encode('utf8')) And/or declare the HTTP content type: self.send_response(200) self.send_header('Content-Type','text/html; charset=utf-8') self.end_headers()
Is it possible to push data from Excel sheet using Python into a database? Question: I have a requirement where using Python I need to write into excel cell , the data which i will be collecting from web page. But not getting an option how to do that. any idea from you people? _**As per @Marcin comments here is the more clear requirement I am looking for_** **Why is python a requirement?** -> _Yes I am using Python with Beautiful Soup module to fetch data from web page._ **Where is excel running, or is it running at all?** -> _Excel is needed when a script would complete its data collection from the web page,and will take an attempt to the next page to do the same tasks,I want the current data to be saved into an excel format._ **How is this related to the web? What exactly are you trying to achieve?** _Hope this answer is given to the above question of your._ **Could you just work with a CSV file?** _Yes,I can work with it,but my final goal is to push the data back to an database,which could be an Oracle or Access database._ **_Architecture_** ------------------ | web | | page | ------------------ | | | Python and BS4(Data Extraction) | | | ------------------ | Excel | | data | ------------------ | | | Python to Push Data(Oracle/Access) | | | ------------------ | Any | | DB | ------------------ **EDIT** **As per @Thang** I have tried but getting the error: Microsoft Windows [Version 6.1.7600] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\Happy>python Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import win32com.client Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named win32com.client >>> Answer: You have a few options, actually, depending on what exactly you're trying to do. [`xlwt`](https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/doc/xlwt.html) \- I think this is great for manipulating Excel files from Python. I've linked you to the documentation. [DataNitro](https://datanitro.com/) \- for Python scripting from within Excel. It's a little slow, but I've used it plenty. You are able to (with VBA in general) have Excel make a web request and pull in a table. Before I knew how to program, that was how I did all of my web scraping.
Importing class from another file in python - I know the fix, but why doesn't the original work? Question: I can make this code work, but I am still confused why it won't work the first way I tried. I am practicing python because my thesis is going to be coded in it (doing some cool things with Arduino and PC interfaces). I'm trying to import a class from another file into my main program so that I can create objects. Both files are in the same directory. It's probably easier if you have a look at the code at this point. #from ArduinoBot import * #from ArduinoBot import ArduinoBot import ArduinoBot # Create ArduinoBot object bot1 = ArduinoBot() # Call toString inside bot1 object bot1.toString() input("Press enter to end.") Here is the very basic ArduinoBot class class ArduinoBot: def toString(self): print ("ArduinoBot toString") Either of the first two commented out import statements will make this work, but not the last one, which to me seems the most intuitive and general. There's not a lot of code for stuff to go wrong here, it's a bit frustrating to be hitting these kind of finicky language specific quirks when I had heard some many good things about Python. Anyway I must be doing something wrong, but why doesn't the simple 'import ClassName' or 'import FileName' work? Thank you for your help. Answer: consider a file (`example.py`): class foo(object): pass class bar(object): pass class example(object): pass Now in your main program, if you do: import example what should be imported from the file `example.py`? Just the class `example`? should the class `foo` come along too? The meaning would be too ambiguous if `import module` pulled the whole module's namespace directly into your current namespace. The idea is that namespaces are wonderful. They let you know where the class/function/data came from. They also let you group related things together (or equivalently, they help you keep unrelated things separate!). A module sets up a namespace and you tell python exactly how you want to bring that namespace into the current context (namespace) by the way you use `import`. `from ... import *` says -- bring everything in that module directly into my namespace. `from ... import ... as ...` says, bring only the thing that I specify directly into my namespace, but give it a new name here. Finally, `import ...` simply says bring that module into the current namespace, but keep it separate. This is the most common form in production code because of (at least) 2 reasons. * It prevents name clashes. You can have a local class named `foo` which won't conflict with the `foo` in `example.py` \-- You get access to that via `example.foo` * It makes it easy to trace down which module a class came from for debugging. consider: from foo import * from bar import * a = AClass() #did this come from foo? bar? ... Hmmm... * * * In this case, to get access to the class `example` from `example.py`, you could also do: import example example_instance = example.example() but you can also get `foo`: foo_instance = example.foo()
Python regex: Multiple matches in one line (using findall()) Question: I'm looking for these "tags" inside text: `{t d="var1"}var2{/t}` or `{t d="varA"}varB{/t}` There can be more attributes, only "d" is mandatory: `{t d="var1" foo="bar"}var2{/t}` My problem is - if there are more tags on one line, just one result is returned, not all of them. What is returned (from test string below): `(u'single1', u'Required item3')` What I expect to be returned: `(u'single1', u'required1') (u'single2', u'Required item2') (u'single3', u'Required item3') ` I got stuck with this. It works with one tag per line but doesn't with more tags per one line. # -*- coding: UTF-8 -*- import re test_string = u''' <span><img src="img/ico/required.png" class="icon" alt="{t d="single1"}required1{/t}" title="{t d="single2"}Required item2{/t}" /> {t d="single3"}Required item3{/t}</span> ''' re_pattern = ''' \{t[ ]{1} # start tag name d=" # "d" attribute ([a-zA-Z0-9]*) # "d" attribute content ".*\} # end of "d" attribute (.+) # tag content \{/t\} # end tag ''' rec_pattern = re.compile(re_pattern, re.VERBOSE) res = rec_pattern.findall(test_string) if res is not None: for item in res: print item Answer: Your wildcards are greedy. Change them from `.*` to `.*?` so they'll be non- greedy: re_pattern = ''' \{t[ ]{1} # start tag name d=" # "d" attribute ([a-zA-Z0-9]*) # "d" attribute content ".*?\} # end of "d" attribute (.+?) # tag content \{/t\} # end tag '''
python can not find attribute Thread Question: my python code like this: #!/usr/bin/env python import threading from time import sleep,ctime loops=[4,2] def loop(nloop,nsec): print 'start loop',nloop,'at:',ctime() sleep(nsec) print 'loop',nloop,'done at:',ctime() def main(): print 'starting at:',ctime() threads=[] nloops = range(len(loops)) for i in nloops: t = threading.Thread(target = loop, args = (i,loops[i])) threads.append(t) for i in nloops: threads[i].start() for i in nloops: threads[i].join() print 'all Done at:',ctime() if __name__ == '__main__': main() but python output is: t = threading.Thread(target = loop, args = (i,loops[i])) AttributeError: 'module' object has no attribute 'Thread' Exception AttributeError: '_shutdown' in <module 'threading' i reinstall python ,but this issue still have ,how to fix it? Answer: I bet you have a local file named `threading.py`, and it's masking the system `threading` module. You can verify this by printing `threading.__file__`: import threading print threading.__file__ to get the file path of the module that is being imported. Rename it, or delete it, to fix this.
Install TortoiseHg for mac : No module named mercurial Question: I'm trying to install TortoiseHg for Mac following these instructions : <https://bitbucket.org/tortoisehg/thg/wiki/developers/MacOSX#!alternative- install-via-macports> I'm trying to follow the instructions about the "Alternative: Install via Homebrew" and I have an issue. When I execute `./thg log` as in the instructions it works, TortoiseHg is launching. However when I try to create an App from the python script, the App is created but when I launch it it crashes. Here is the output : Traceback (most recent call last): File "/Users/fabienhenon/Documents/thg-mac-app/dist/TortoiseHg.app/Contents/Resources/__boot__.py", line 316, in <module> _run() File "/Users/fabienhenon/Documents/thg-mac-app/dist/TortoiseHg.app/Contents/Resources/__boot__.py", line 311, in _run exec(compile(source, path, 'exec'), globals(), globals()) File "/Users/fabienhenon/Documents/thg-mac-app/dist/TortoiseHg.app/Contents/Resources/main.py", line 28, in <module> imp.load_source("thg", SCRIPT_DIR + "/bin/thg") File "/Users/fabienhenon/Documents/thg-mac-app/dist/TortoiseHg.app/Contents/Resources/bin/thg", line 56, in <module> from mercurial import demandimport ImportError: No module named mercurial 2013-01-06 12:25:17.436 TortoiseHg[406:707] TortoiseHg Error logout [Opération terminée] When I type : `hg --version` I have the following output : Mercurial Distributed SCM (version 2.4.2+20130102) (see http://mercurial.selenic.com for more information) Copyright (C) 2005-2012 Matt Mackall and others This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Can somebody help me with this issue ? Thank you for your answers Answer: I've found a solution to solve this issue. From the error message I had, the script could not find the module named mercurial. I'm new with Python so I had to make some researches to know how module importation works and I found something about dynamically importing a module using the `'sys'` module. My solution was to edit the tortoisehg source code (the file where the error came from) to dynamically add the path to my mercurial module to the `'sys.path'` so that the program knows where to find the mercurial module. Here is the code (in the 'thg' python file, line 56 (as mentioned by the error)) : import sys sys.path.append("/Library/Python/2.7/site-packages") You have to add this code just before this line : from mercurial import demandimport And the path must correspond to the location of your mercurial folder.
Python how do I overlay random images over images being generated to end up with 2 images with text Question: Here is my code that I have so far. What it does is grabs a random text line from the text file an generates a random color then creates the JPG image with the text on top. What I want to do is take a random picture and overlay it on top of the solid color at opacity of maybe 0.2 or something then put the text on top of that so I end up with > solid color > picture overlayed > text on top. This code generates multiple images. It would be nice to have the text centered vertically also, but I'm not clear on how to do that. import Image, random, textwrap, ImageFont, ImageDraw, os, sys basepath = os.path.dirname(sys.argv[0]) + "/" for n in xrange(10): keywordlist = [] imglist = [] keyword = file(basepath + "text.txt", "r") for line in keyword: keywordlist.append(line.replace("\n", "")) def type(name): value = name[random.randint(0,len(name)-1)] return value def random_color(): return (random.randint(0,155), random.randint(0,155), random.randint(0,155)) astr = ('%s' %(type(keywordlist))) para = textwrap.wrap(astr,width=19) MAX_W,MAX_H=640,400 im = Image.new('RGB', (MAX_W, MAX_H), (random_color())) draw = ImageDraw.Draw(im) font = ImageFont.truetype('C:/windows/fonts/Arialbd.ttf', 58) current_h=0 for line in para: w,h=draw.textsize(line, font=font) draw.text(((MAX_W-w)/2, current_h), line, font=font,) current_h+=h im.save('img%000d.jpg' % n) Here is a sample of the output: ![Example](http://i.stack.imgur.com/aZWfw.jpg) Answer: Use [the `blend` function](http://www.pythonware.com/library/pil/handbook/image.htm#image- blend-function): new_image = Image.blend(solid_color_image, picture, 0.2)
Google App Engine aborts on missing environment variable DJANGO_SETTINGS_MODULE Question: This is a follow-up question for [Google App Engine and Django support](http://stackoverflow.com/questions/14137404/google-app-engine-and- django-support): The tutorial works great for an empty project, however when I try to deploy an existing Django app to Google App Engine, it starts throwing errors: Traceback (most recent call last): File "/python27_runtime/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 223, in Handle result = handler(dict(self._environ), self._StartResponse) File "/python27_runtime/python27_lib/versions/third_party/django-1.4/django/core/handlers/wsgi.py", line 219, in __call__ self.load_middleware() File "/python27_runtime/python27_lib/versions/third_party/django-1.4/django/core/handlers/base.py", line 39, in load_middleware for middleware_path in settings.MIDDLEWARE_CLASSES: File "/python27_runtime/python27_lib/versions/third_party/django-1.4/django/utils/functional.py", line 184, in inner self._setup() File "/python27_runtime/python27_lib/versions/third_party/django-1.4/django/conf/__init__.py", line 40, in _setup raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE) ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. And a second, which might be related: Traceback (most recent call last): File "/python27_runtime/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 223, in Handle result = handler(dict(self._environ), self._StartResponse) File "/python27_runtime/python27_lib/versions/third_party/django-1.4/django/core/handlers/wsgi.py", line 219, in __call__ self.load_middleware() File "/python27_runtime/python27_lib/versions/third_party/django-1.4/django/core/handlers/base.py", line 39, in load_middleware for middleware_path in settings.MIDDLEWARE_CLASSES: File "/python27_runtime/python27_lib/versions/third_party/django-1.4/django/utils/functional.py", line 184, in inner self._setup() File "/python27_runtime/python27_lib/versions/third_party/django-1.4/django/conf/__init__.py", line 42, in _setup self._wrapped = Settings(settings_module) File "/python27_runtime/python27_lib/versions/third_party/django-1.4/django/conf/__init__.py", line 95, in __init__ raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e)) ImportError: Could not import settings 'settings' (Is it on sys.path?): No module named settings I have modified my settings.py as per the tutorial. The app deploys without problems and the syncdb works as well; the database and all required tables are in place. I found [this reference](https://groups.google.com/forum/?fromgroups=#!topic/google- appengine/lJorqc0p3MA) to the error message as shown in the log but its suggested fix did not help. Any ideas what might be causing this? **EDIT:** To shorten this already lengthy question I removed the previously posted `wsgi.py` file. I had nothing to do with this issue. **EDIT 2:** I think I made a small improvement and GAE is now complaining: ImportError: No module named properties I presume there might be an entry missing in my app.yaml file but I have no clue as to which file that may be. I found some references regarding missing modules but none that reflect this error message... Answer: After much trial and error I managed to solve this, albeit partially: I did not manage to get my existing `PyCharm` project deployed (yet). As I was keen to have a version running on GAE I went for a different approach and created a new empty Django project (`project 2`) on my local machine. I first deployed the blank project using [this tutorial](http://howto.pui.ch/post/39245389801/tutorial-django-on-appengine- using-google-cloud-sql) which ran fine. I then copied my `models.py` file from my existing PyCharm project to `project 2` and added an app called `properties` which uses the `models.py` file. Initially this went wrong as GAE kept complaining it could not find my `properties` app. After fiddling about with it, it suddenly appeared in my admin. I'm not sure what caused the initial problem but it's working now. Things crucial to success for me: I added the following to the very top of my settings.py: import os ROOT_PATH = os.path.dirname(__file__) ... and then replaced the default `STATIC_ROOT` with: STATIC_ROOT = ROOT_PATH + os.sep + 'static' Then I ran: python manage.py collectstatic from the dir of `project 2`. This collects the required static files which Django admin uses (image files, css files etc) So, I currently have a stripped down version of my original project running on GAE. Things that are missing: * The original project used `grappelli` for a more styled admin interface. I'm not sure whether this will run on GAE. **EDIT: Deploying Grappelli on GAE is reasonbly easy. Just copy the Grappelli package to your project dir and run`manage.py collectstatic`. Also add grappelli urls as per documention. Redeploy. Done.** * The original project uses a module called `templated_email` to send out templated emails from my `properties` app. Same as `grappelli`: I'm not sure whether this is supported by GAE. Hopefully it will run on GAE as it is crucial for my specific app. **EDIT: I bumped into[this](http://venodesigns.net/2010/07/13/rendering-emails-from-django-templates/) little gem which makes templated_email obsolete and lets me plug into GAE mail system.** To be honest, this approach partially defies the benefits of PyCharm which should fully support Django and GAE out of the box. It will probably require some additional research and tweaking to get that up and running. Any comments or insights re the above are obviously appreciated!
python topN max heap, use heapq or self implement? Question: there's heapq in python, for general usage. i want recording topN(0~20) for 10e7 records. if use heapq, should use '-' to translate max to min; and recording a min number of bottom, to call heapq.heappushpop() should i use heapq or self implement a heap(maybe buggy or less efficient)? #update import heapq class TopN(object): """ v format: (num, value) after looking into http://hg.python.org/cpython/file/2.7/Lib/heapq.py, i find heappushpop already optimize, no need bottom value feed() can be optimize further, if needed: using func object instead of compare len(self.h) each time """ def __init__(self, N): self.N = N self.h = [] def feed(self, v): if len(self.h) < self.N: heapq.heappush(self.h, v) else: heapq.heappushpop(self.h, v) def result(self): self.h.sort(reverse=True) return self.h def t_topn(): topn = TopN(10) for i in xrange(5): topn.feed((i, str(i))) res = topn.result() assert sorted(res, reverse=True) == res def t_topn_random(): import random topn = TopN(10) for i in xrange(100): x = random.randint(0, 1e4) topn.feed((x, str(x))) res = topn.result() assert sorted(res, reverse=True) == res if __name__ == '__main__': t_topn() t_topn_random() Answer: The only problem with `heapq` is that it doesn't provide a `key` function like everything else in the stdlib does. (If you're curious why, Raymond Hettinger explains in [this email](http://code.activestate.com/lists/python- list/162387/). He's right that `heapq` couldn't provide the same interface as other sort functions—but the reasons don't affect your use case, where `key` would just be `lambda x: -x`.) The usual workaround is to decorate-heap-undecorate. That is, put a modified version of your values into the heap that sorts by `key`. Normally, this means one of the following: * Storing `key(x)` instead of `x`, and then accessing `unkey(value)` instead of `value` (assuming `key` is reversible). * Storing `(key(x), x)` instead of `x`, and then accessing `value[1]`. (This can break stability, but `heapq` doesn't promise stability anyway.) * Writing a wrapper class that implements a custom `__le__` method, then storing `Wrapper(x)` instead of `x` and accessing `value.value` instead of `value`. In your case, the key function is reversible. So, just store `-x`, and access `-value`. That's about as trivial as decoration gets. Still, regardless of how simple it is, you should probably write a wrapper, or you will screw it up at some point. For example, you could write a `maxheap` that wraps the minheap in `heapq` like this: import heapq def heapify(x): for i in range(len(x)): x[i] = -x[i] heapq.heapify(x) def heappush(heap, item): heapq.heappush(heap, -item) def heappop(heap): return -heapq.heappop(heap) … and so on for any other functions you need. It may be a bit of a pain, but it's a lot less work than implementing the whole thing from scratch. While you're at it, you may want to wrap the heap in an object-oriented API so you can do `heap.push(x)` instead of `heapq.heappush(heap, x)`, etc. import heapq class MaxHeap(object): def __init__(self, x): self.heap = [-e for e in x] heapq.heapify(self.heap) def push(self, value): heapq.heappush(self.heap, -value) def pop(self): return -heapq.heappop(self.heap) … If you take a quick look around the recipes at ActiveState or the modules on PyPI, you should find that others have already done most of the work for you. Alternatively, you could copy and paste the `heapq` source (it's pure Python) as `maxheapq.py` and just replace the `cmp_lt` function with its opposite. (Of course if you're doing that, it's probably just as easy, and certainly a lot clearer, to modify `cmp_lt` to take a `key` argument in the first place, and modify all the other functions to pass the `key` through—bearing in mind that it won't be as generally applicable anymore, because it can't make the usual guarantee that `key` is only called once.) If you really want to live dangerously (you shouldn't), you could even monkeypatch it: import heapq def cmp_gt(x, y): return y < x if hasattr(y, '__lt__') else not (x <= y) heapq.cmp_lt = cmp_gt But you don't want to do that in real code.
Python QueryFrame returns None, but C++ bindings work Question: In OpenCV 2.3.1 (built from source) on Ubuntu 10.04, the C++ fragment cvNamedWindow("Camera", 1); CvCapture* capture = cvCaptureFromCAM(CV_CAP_ANY); while (1) { IplImage* frame = cvQueryFrame(capture); cvShowImage("Camera", frame); key = cvWaitKey(10); ... will open up a window and show video from my ThinkPad camera, but import cv2.cv as cv # or import cv cv.NamedWindow("Camera", 1) capture = cv.CaptureFromCAM(-1) while True: frame = cv.QueryFrame(capture) cv.ShowImage("Camera", frame) key = cv.WaitKey(10) ... fails (the window is gray), because `cv.QueryFrame` returns `None` (and the light on the laptop camera doesn't come on.) Any idea what may be going on here (and how I might remedy it)? `cv.QueryFrame` works when displaying `.jpg`, so this seems to be a camera issue. Answer: Found a workaround, via [opencv+python+linux+webcam = cannot capture frames](http://stackoverflow.com/questions/12717743/opencvpythonlinuxwebcam- cannot-capture-frames), which I'll leave here for posterity. Install `lib4vl` (`apt-get install libv4l-dev`) and in the `cmake` step of building `OpenCV`, pass `-D WITH_4VL=ON`. (I'd been building with that OFF.) Why C++ works without `lib4vl` but the Python bindings require it to work with a webcam is a puzzle, which perhaps some OpenCV-knowledgable person can explain. I'd love to hear an explanation.
Outlining a Solution Stack Question: please excuse my ignorance as I'm an Aerospace Engineer going headfirst into the software world. I'm building a web solution that allows small computers (think beagleboard) to connect to a server that sends and receives data to these clients. The connection will be over many types including GPRS/3G/4G. The user will interact with clients in real time through webpages served by this central server. The solution must scale well. I've been using python for the client side and some simple ruby code for the servers with Heroku. I have also tried a bit of NodeJS and Ruby on Rails. With so many options i'm struggling to see the forest from the trees and wondering where these languages will fit into my stack. Your help is appreciated; I'm happy to give more details. Answer: It all depends on what you are actually trying to do and what your requirements are. There is no real "right" language for things like these, it's mostly determined by the Frameworks you'll be using on those language (since all are general-purpose programming languages) and your personal preference/experience. I can't comment too much on Python as I never tried it really, but from what I heard/saw it can be used for all things Ruby is also used, although the Community around Python is a bit smaller with Python being used a lot more in the Scientific community (that may be good if your app may be doing any crayz calculations). That leads us to Ruby. Ruby and the Ruby on Rails framework is mostly used to write Web-Applications and Services. Ruby is a very elegant language to program in and the tools are very mature and easy to work with. Rails is a framework on Ruby that makes Web-Development very simple in providing you with a very good set of tools especially suited to write data-driven web-apps. Very flexible and a joy to work with. There are however some drawbacks to Ruby at the moment, mostly related to poor threading. Node.JS is a new language that is focused on paralellism and supports all things Ruby and Python can do, although it's documentation is lacking compared to what Ruby will give you. It's also not the most beginner-friendly choice as JavaScript with all it's quirks and the callback-oriented async model is not of the simplest thing around. That said, Node is very bare metal and makes it very very easy to write arbitrary TCP/UDP Servers that don't necessary work over HTTP. Custom streaming protocols or any custom protocol in fact are almost trivially done in Node.. (I don't advise you do that, but maybe that's important to your task). To be fair there are frameworks that facilitate writing of Web-Apps for node, but the coices are a) not as mature as Rails or Django, and b) you have to pick your framework choices. This means: Where Rails does come with a lot of defaults that guide you, (Rails for example has a default Database stack it's optimized around), Node with Frameworks like Express only provide you with a bare-bones HTTP server where you have to bring in the Database of your choice etc... In closing: All languages and frameworks you asked about are mostly used for writing Web-Applications. They all can however be used to write a client that consumes the service too - it mostly comes down to general preference.
python:Import module from memory Question: > **Possible Duplicate:** > [How to load compiled python modules from > memory?](http://stackoverflow.com/questions/1830727/how-to-load-compiled- > python-modules-from-memory) I have some python file in the memory that may be StringIO.I how to import module file stored in the memory.I do not want to save it to disk and then load. It look like: import StringIO.StrngIO([buf]) Answer: A nice approach is to use custom Meta import hooks as described in [PEP 302](http://www.python.org/dev/peps/pep-0302/#specification- part-2-registering-hooks). One can write a class that imports modules dynamically from a dictionary of strings: """Use custom meta hook to import modules available as strings. Cp. PEP 302 http://www.python.org/dev/peps/pep-0302/#specification-part-2-registering-hooks""" import sys import imp modules = {"a" : """def hello(): return 'Hello World A!'""", "b": """def hello(): return 'Hello World B!'"""} class StringImporter(object): def __init__(self, modules): self._modules = dict(modules) def find_module(self, fullname, path): if fullname in self._modules.keys(): return self return None def load_module(self, fullname): if not fullname in self._modules.keys(): raise ImportError(fullname) new_module = imp.new_module(fullname) exec self._modules[fullname] in new_module.__dict__ return new_module if __name__ == '__main__': sys.meta_path.append(StringImporter(modules)) # Let's use our import hook from a import hello print hello() from b import hello print hello() BTW: If you don't want that much and just want to import one string, then stick to the implementation of the method load_module. All you need is inside it.
python Channel API expiry and usage in google app engine Question: I want to use the channel api to push updates to open pages, What I have done so far is to store the page client ids in ndb - I have included a code summary My question is: How do I manage closed pages and expired tokens? and is this the best way to push updates to many open pages? open page code: import webapp2 import uuid from google.appengine.api import channel from google.appengine.ext import ndb class Frame(ndb.Model): clientID = ndb.StringProperty() date = ndb.DateTimeProperty(auto_now_add=True) class MainHandler(BaseHandler): def get(self): client_id = str(uuid.uuid4()) channel_token = channel.create_channel(client_id) frame = Frame(clientID = client_id) frame.put() self.render_response('home.html',** "token":channel_token,"client_id":client_id) send message code: from google.appengine.api import channel from google.appengine.ext import ndb class Frame(ndb.Model): clientID = ndb.StringProperty() date = ndb.DateTimeProperty(auto_now_add=True) frames = Frame.query().fetch(10) for i in frames: channel.send_message(i.clientID, "some message to update") Answer: When you enable channel_presence, your application receives POSTs to the following URL paths: POSTs to /_ah/channel/connected/ POSTs to /_ah/channel/disconnected/ These signal that the client has connected to the channel and can receive messages or has dicsonnected. [Tracking_Client_Connections_and_Disconnections](https://developers.google.com/appengine/docs/python/channel/overview#Tracking_Client_Connections_and_Disconnections) Dealing with expired tokens: > By default, tokens expire in two hours, unless you explicitly set an > expiration time by providing the duration_minutes argument to the > create_channel() function when generating the token. If a client remains > connected to a channel for longer than the token duration, the socket’s > onerror() and onclose() callbacks are called. At this point, the client can > make an XHR request to the application to request a new token and open a new > channel. So on your `onerror` function you basically do it all over again just like the original connection. [Tokens and security](https://developers.google.com/appengine/docs/python/channel/overview#Tokens_and_Security) To send updates to many open pages simply iterate round your list of connected users and send them the message individually. There is no "transmit to all" functionality. You may also want to build in a "heartbeat" that sends messages to supposedly connected clients and remove them if no reply. This is because sometimes (apparently) the disconnected messages are not sent (power failure, whatever) when the browser window is closed.
How to handle download pop up window using Python and get the file saved? Question: I have a link, which contains downloadble file,now when i am putting that link onto the browser, and hit `ENTER` a popup window is coming to download. Now using Python can we save that file in local machine? say downloadable link : https://xyz.test.com/aems/file/filegetrevision.do?fileEntityId=8120070&cs=LU31NT9us5P9Pvkb1BrtdwaCrEraskiCJcY6E2ucP5s.xyz **Code** it is for preparing the link: but finally i couldn't find a way how to handle this: for a in soup.find_all('a', {"style": "display:inline; position:relative;"}, href=True): href = a['href'].strip() href = "https://xyz.test.com/" + href print(href) [Download window](http://i.stack.imgur.com/5nIcZ.png) Answer: If your intention is not to test the _download popup_ itself, but the existence/content of the file, you can download it using urllib: import urllib urllib.urlretrieve(href, filename) You would need to add the necesary exception handling (to make sure the URL really points to something) and the file processing once downloaded to verify it's content.
exit on KeyboardInterrupt after generating plots in while loop Question: I am monitoring an experiment in real time using matplotlib to generate plots in a while loop. Ideally, the loop should exit on something like a `KeyboardInterrupt`. This works well enough in an Ubuntu test. In Windows 7, using `ipython`, it exits with `"Terminate batch job (Y/N)?"` then closes the interpreter. I would like to avoid this behavior and leave the interpreter open after the KeyboardInterrupt. Here is a test script. [EDIT 2]: This script works fine in Windows if `ipython` is loaded as `ipython --pylab`. import time import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) line, = ax.plot([0], [0], 'b-o') window = 50 plot_data = np.zeros((window, 2)) i = 0 start = time.time() while True: try: data = [time.time() - start, np.random.rand()] print ' '.join('{:.2f}'.format(x) for x in data) if i < window: plot_data[i,:] = data line.set_data(plot_data[0:i+1,0], plot_data[0:i+1,1]) else: plot_data[0:window-1] = plot_data[1:window] plot_data[window-1] = data line.set_data(plot_data[:,0], plot_data[:,1]) ax.relim() ax.autoscale_view(True,True,True) fig.canvas.draw() plt.pause(0.1) i += 1 except KeyboardInterrupt: print "Program ended by user.\n" break print 'Success!' [EDIT 1]: I should be more clear why I tagged this with matplotlib. The below example script executes with no problems in either operating system. i = 0 start = time.time() while True: try: data = [time.time() - start, np.random.rand()] print ' '.join('{:.2f}'.format(x) for x in data) time.sleep(0.1) except KeyboardInterrupt: print "Proram ended by user. \n" break print 'Success!' All of the packages were installed yesterday as part of a clean installation of `Enthought`. Answer: Right now the best way I've found to solve this problem across several Windows machines is as follows... print 'press \'q\' to end run' time.sleep(1.0) fig = plt.figure() ax = fig.add_subplot(111) line, = ax.plot([0], [0], 'b-o') window = 150 plot_data = np.zeros((window, 2)) i = 0 start = time.time() while True: data = [time.time() - start, np.random.rand()] print ' '.join('{:.2f}'.format(x) for x in data) if i < window: plot_data[i,:] = data line.set_data(plot_data[0:i+1,0], plot_data[0:i+1,1]) else: plot_data[0:window-1] = plot_data[1:window] plot_data[window-1] = data line.set_data(plot_data[:,0], plot_data[:,1]) ax.relim() ax.autoscale_view(True,True,True) fig.canvas.draw() plt.pause(delay) i += 1 if msvcrt.kbhit(): if ord(msvcrt.getch()) == 113: print "Program ended by user.\n" break print 'Success!' Unfortunately, this is not at all platform independent, but everything I've read over the past few days leads me to believe that platform-independent keyboard input is not really achievable. The code in my original question works well in Unix and some Windows installations. This code works well in the few Windows installations I've tried. All of this works best when run through `ipython --pylab`. This might have to be good enough for now.
Impossible to initialize Elixir Question: I'm starting with Elixir and SQL Alchemy. I've created a python file connecting with a Mysql database to but as soon as I execute with python I get the error bellow: root@raspberrypi:/Python/mainFlask/yonkiPOPS# python yonki.py Traceback (most recent call last): File "yonki.py", line 1, in <module> from elixir import metadata, Entity, Field File "/usr/local/lib/python2.7/dist-packages/Elixir-0.7.1-py2.7.egg/elixir/__init__.py", line 29, in <module> from elixir.entity import Entity, EntityBase, EntityMeta, EntityDescriptor, \ File "/usr/local/lib/python2.7/dist-packages/Elixir-0.7.1-py2.7.egg/elixir/entity.py", line 17, in <module> from sqlalchemy.orm import MapperExtension, mapper, object_session, \ ImportError: cannot import name ScopedSession I have been looking for it but I don't find the reason. This is the yonki.py file: from elixir import metadata, Entity, Field from elixir import Unicode, UnicodeText from elixir import * class User(Entity): username = Field(String(64)) metadata.bind = 'mysql://root:nomasandroid42@localhost/yonkiPOPS' session.bind.echo = True setup_all() create_all() I think that it's maybe due to a required module not installed but I don't know which one. Answer: Elixir 0.7.1 seems to be incompatible with the latest version of SQLalchemy, 0.8. You can solve that problem with sudo pip install SQLAlchemy==0.7.8
Python BeautifulSoup get text from HTML Question: I have some HTML code like this: <p>aaa</p>bbb <p>ccc</p>ddd How can I get 'bbb' and 'ddd'? Answer: You can read the subsequent sibling of each `p` tag (note this is very specific to this text, so hopefully it can be expanded to your situation): In [1]: from bs4 import BeautifulSoup In [2]: html = """\ ...: <p>aaa</p>bbb ...: <p>ccc</p>ddd""" In [3]: soup = BeautifulSoup(html) In [4]: [p.next_sibling for p in soup.findAll('p')] Out[4]: [u'bbb\n', u'ddd'] This picks up the trailing newline, so you can strip it off if need be: In [5]: [p.next_sibling.strip() for p in soup.findAll('p')] Out[5]: [u'bbb', u'ddd'] The general idea is that you locate the tag(s) before your target text and then find the next sibling element, which should be your text.
Deep version of sys.getsizeof Question: I want to calculate the memory used by an object. `sys.getsizeof` is great, but is shallow (for example, called on a list, it would not include the memory taken by the list's elements). I'd like to write a generic "deep" version of `sys.getsizeof`. I understand there is some ambiguity in the definition of "deep"; I'm perfectly happy with the [definition followed by `copy.deepcopy`](http://docs.python.org/3.4/library/copy.html). Here's my first attempt: def get_deep_sizeof(x, level=0, processed=None): if processed is None: # we're here only if this function is called by client code, not recursively processed = set() processed.add(id(x)) mem = sys.getsizeof(x) if isinstance(x, collections.Iterable) and not isinstance(x, str): for xx in x: if id(xx) in processed: continue mem += get_deep_sizeof(xx, level+1, processed) if isinstance(x, dict): mem += get_deep_sizeof(x[xx], level+1, processed) return mem It suffers from two known problems, and an unknown number of unknown problems: * I don't know how to traverse a generic container in a way that captures all the linked objects. Therefore, I iterated using `in`, and hard coded the case of dictionary (to include values, and not just the keys). Obviously, this will not work for other classes like dictionary. * I had to hard code the exclusion of `str` (which is an iterable, and yet does not have links to any other objects). Again, this will break if there are more objects like that. I suspect that using `in` is not a good idea, but I'm not sure what else to do. Answer: I think that [Pympler](http://packages.python.org/Pympler/) has already beaten you to the punch on this one. From their documentation: >>> from pympler.asizeof import asizeof >>> obj = [1, 2, (3, 4), 'text'] >>> asizeof(obj) 176 If you want a specific example, you can find the source for `asizeof` [here](http://code.google.com/p/pympler/source/browse/trunk/pympler/asizeof.py).
Simply a try/except with lambda - Python? Question: Is there a way to simplify this try/except into a one line with lambda? alist = ['foo','bar','duh'] for j,i in enumerate(alist): try: iplus1 = i+alist[j+1] except IndexError: iplus1 = "" Is there other way other than: j = '' if IndexError else trg[pos] Answer: No, Python doesn't have any shorthands or simplifications to the `try`/`except` syntax. To solve your specific problem, I would probably use something like: for j, i in enumerate(alist[:-1]): iplus1 = i + alist[j + 1] Which would avoid the need for an exception. Or to get super cool and generic: from itertools import islice for j, i in enumerate(islice(alist, -1)): iplus1 = i + alist[j + 1] Alternative, you could use: `itertools.iziplongest` to do something similar: for i, x in itertools.izip_longest(alist, alist[1:], fillvalue=None): iplus1 = i + x if x is not None else "" Finally, one small note on nomenclature: `i` is traditionally used to mean "index", so using `for i, j in enumerate(…)` would be more "normal".
Minimal HTTP server with Werkzeug - Internal Server Error Question: To demonstrate basics HTTP handling, I'm in the process of trying to define a really minimal HTTP server demonstration. I have been using the excellent [werkzeug](http://werkzeug.pocoo.org/) library that I'm trying to "dumb" down a bit more. My current server does too much :) #!/usr/bin/env python2.7 # encoding: utf-8 if __name__ == '__main__': from werkzeug.serving import run_simple run_simple('127.0.0.1', 6969, application=None) `run_simple` is handling already too many things. When making a request for this server, → http GET http://127.0.0.1:6969/ we get: HTTP/1.0 500 INTERNAL SERVER ERROR Content-Type: text/html Content-Length: 291 Server: Werkzeug/0.8.3 Python/2.7.1 Date: Tue, 08 Jan 2013 07:45:46 GMT <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>500 Internal Server Error</title> <h1>Internal Server Error</h1> <p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p> I would love to reduce it to the bare minimum. And use the 500 Internal Server Error as a catch all. Ideally the Response from the server should be 500 for any HTTP requests and just that, because the server doesn't know anything about the requests HTTP/1.0 500 INTERNAL SERVER ERROR Then in a second stage I will probably add HTTP/1.0 500 INTERNAL SERVER ERROR Content-Type: text/plain Internal Server Error Then start to handle requests by understanding them. The goal is to be educative in the process. Any suggestions for taking over the default answers is welcome. **Update 001** with: #!/usr/bin/env python2.7 # encoding: utf-8 from werkzeug.wrappers import BaseResponse as Response def application(environ, start_response): response = Response('Internal Server Error', status=500) return response(environ, start_response) if __name__ == '__main__': from werkzeug.serving import run_simple run_simple('127.0.0.1', 6969, application) It will return HTTP/1.0 500 INTERNAL SERVER ERROR Content-Type: text/plain; charset=utf-8 Content-Length: 21 Server: Werkzeug/0.8.3 Python/2.7.1 Date: Tue, 08 Jan 2013 07:55:10 GMT Internal Server Error I want to remove at least the server and the date which are optional. Answer: As basic example, I wouldn't use a third-party library. You can use the BaseHTTPServer-module that comes with Python. import BaseHTTPServer PORT = 8000 class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler): def send_response(self, code, message=None): """Send the response header and log the response code. In contrast to base class, do not send two standard headers with the server software version and the current date. """ self.log_request(code) if message is None: if code in self.responses: message = self.responses[code][0] else: message = '' if self.request_version != 'HTTP/0.9': self.wfile.write("%s %d %s\r\n" % (self.protocol_version, code, message)) def do_GET(self): self.send_response(500) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write("Internal Server Error\n") httpd = BaseHTTPServer.HTTPServer(("", PORT), MyHandler) print "serving at port", PORT httpd.serve_forever() This will give us the following response: HTTP/1.0 500 Internal Server Error Content-type: text/html Internal Server Error The place where you can do all your changes now is in the do_GET-method. I think it is quite obvious what each line does. **Alternative 1:** Even more basic is import SocketServer response = """HTTP/1.0 500 Internal Server Error Content-type: text/html Invalid Server Error""" class MyTCPHandler(SocketServer.BaseRequestHandler): """ The RequestHandler class for our server. It is instantiated once per connection to the server, and must override the handle() method to implement communication to the client. """ def handle(self): # self.request is the TCP socket connected to the client self.data = self.request.recv(1024).strip() self.request.sendall(response) if __name__ == "__main__": HOST, PORT = "localhost", 8000 server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) server.serve_forever()
Automatically cropping an image with python/PIL Question: Can anyone help me figure out what's happening in my image auto-cropping script? I have a png image with a large transparent area/space. I would like to be able to automatically crop that space out and leave the essentials. Original image has a squared canvas, optimally it would be rectangular, encapsulating just the molecule. here's the original image: ![Original Image](http://i.stack.imgur.com/AsypD.png) Doing some googling i came across PIL/python code that was reported to work, however in my hands, running the code below over-crops the image. import Image import sys image=Image.open('L_2d.png') image.load() imageSize = image.size imageBox = image.getbbox() imageComponents = image.split() rgbImage = Image.new("RGB", imageSize, (0,0,0)) rgbImage.paste(image, mask=imageComponents[3]) croppedBox = rgbImage.getbbox() print imageBox print croppedBox if imageBox != croppedBox: cropped=image.crop(croppedBox) print 'L_2d.png:', "Size:", imageSize, "New Size:",croppedBox cropped.save('L_2d_cropped.png') the output is this:![script's output](http://i.stack.imgur.com/6Y5r6.png) Can anyone more familiar with image-processing/PLI can help me figure out the issue? Answer: For me it works as: import Image import sys image=Image.open('L_2d.png') image.load() imageSize = image.size imageBox = image.getbbox() cropped=image.crop(imageBox) cropped.save('L_2d_cropped.png') When you search for boundaries by `mask=imageComponents[3]`, you search only by blue channel.
Prevent OS X from going to sleep with Python? Question: Is there a way to prevent a computer running OS X from going to sleep from within a Python script? Answer: You can call the **caffeinate** command. subprocess.Popen('caffeinate') This is how I use it: import sys import subprocess if 'darwin' in sys.platform: print('Running \'caffeinate\' on MacOSX to prevent the system from sleeping') subprocess.Popen('caffeinate')
Force importing module from current directory Question: I have package `p` that has modules `a` and `b`. `a` relies on `b`: `b.py` contents: import a However I want to _ensure_ that `b` imports my `a` module from the same `p` package directory and not just any `a` module from `PYTHONPATH`. So I'm trying to change `b.py` like the following: from . import a This works as long as I import `b` when I'm outside of `p` package directory. Given the following files: /tmp /p a.py b.py __init__.py The following works: $ cd /tmp $ echo 'import p.b' | python **The following does NOT work:** $ cd /tmp/p $ echo 'import b' | python Traceback (most recent call last): File "<stdin>", line 1, in <module> File "b.py", line 1, in <module> from . import a ValueError: Attempted relative import in non-package **Why?** P.S. I'm using Python 2.7.3 Answer: After rereading the Python [import documentation](http://docs.python.org/2/tutorial/modules.html#intra-package- references), the correct answer to my original problem is: _To ensure that`b` imports `a` from its own package its just enough to write the following in the `b`:_ import a Here is the quote from the docs: > The submodules often need to refer to each other. For example, the surround > module might use the echo module. In fact, **such references are so common > that the import statement first looks in the containing package before > looking in the standard module search path.** **Note:** As J.F. Sebastian suggest in the comment below, use of implicit imports is not advised, and they are, in fact, gone in Python 3.
python network file writing in a robust manner Question: I am looking for a robust way to write out to a network drive. I am stuck with WinXP writing to a share on a Win2003 server. I want to pause writing if the network share goes down... then reconnect and continue writing once the network resource is available. With my initial code below, what happens is the 'except' catches the IOError when the drive goes away, but then when the drive becomes available again, the outf operations continue to IOError. import serial with serial.Serial('COM8',9600,timeout=5) as port, open('m:\\file.txt','ab') as outf: while True: x = port.readline() # read one line from serial port if x: # if the there was some data print x[0:-1] # display the line without extra CR try: outf.write(x) # write the line to the output file outf.flush() # actually write the file except IOError: # catch an io error print 'there was an io error' Answer: I suspect that once an open file goes into an error state because of the IOError that you will need to reopen it. You could try something like this: with serial.Serial('COM8',9600,timeout=5) as port: while True: try: with open('m:\\file.txt','ab') as outf: while True: x = port.readline() # read one line from serial port if x: # if the there was some data print x[0:-1] # display the line without extra CR try: outf.write(x) # write the line to the output file outf.flush() # actually write the file break except IOError: print 'there was an io error' This puts the exception handling inside an outer loop that will reopen the file (and continue reading from the port) in the event of an exception. In practice you would probably want to add a `time.sleep()` or something to the `except` block in order to prevent the code from spinning.
Why is 'import simplejson' failing in Python 2.7.3 code, but not in the interpreter? Question: There are two instances running uwgsi and nginx servers. Each hosts a Flask application. Both are running on a Python 2.7.3 path. One of the servers throws an ImportError for the "import simplejson" statement. The interpreter on both servers will accept this import statement without complaint. Here's the source of application A: 1 from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, views 2 import sys 3 print sys.version 4 print sys.path 5 6 import os 7 import functools 8 import urllib,urllib2 9 import simplejson 10 from datetime import datetime, timedelta And the source of application B: 1 from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, views 2 3 import sys 4 print sys.version 5 print sys.path 6 7 import simplejson 8 9 import functools Here's the sys.version and sys.path log output of server A: 2.7.3 (default, Aug 1 2012, 05:25:23) [GCC 4.6.3] ['/srv/www/A/env/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/srv/www/A/env/local/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg', '/srv/www/A/env/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/srv/www/A/env/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg', '/srv/www/A/env/lib/python2.7', '/srv/www/A/20120910/src', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/srv/www/A/env/local/lib/python2.7/site-packages', '/srv/www/A/env/lib/python2.7/site-packages'] WSGI app 0 (mountpoint='notimportant.com|') ready in 1 seconds on interpreter 0x1b20420 pid: 11069 Here's the sys.version and sys.path log output of server B: 2.7.3 (default, Aug 1 2012, 05:25:23) [GCC 4.6.3] ['/srv/www/B/env/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/srv/www/B/env/local/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg', '/srv/www/B/env/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/srv/www/B/env/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg', '/srv/www/B/env/lib/python2.7', '/srv/www/B/20130105/src', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/srv/www/B/env/local/lib/python2.7/site-packages', '/srv/www/B/env/lib/python2.7/site-packages'] Traceback (most recent call last): File "/srv/www/B/20130105/src/B.py", line 7, in <module> import simplejson ImportError: No module named simplejson unable to load app 0 (mountpoint='notimportant.com|') (callable not found or import error) Any constructive ideas will be appreciated. Answer: `simplejson` is an external library; it is bundled with Python 2.6 and up as the [`json` module](http://docs.python.org/2/library/json.html). Just use `import json` instead of `import simplejson`, _or_ install `simplejson` on server B too. If you replace your `simplejson` import with `json`, remember to fix any references in the file. Alternatively, import it like this: try: import simplejson except ImportError: import json as simplejson and it'll use the stdlib `json` module, renamed, and all your references to `simplejson` will continue to work.
can python be useful to open multiple tabs in a browser in one shot? Question: I am looking for a faster way to do my task. i have 40000 file downloadable urls. I would like to download them in local desktop is.now the thought is currently what I am doing is placing the link on the browser and then download them via a script.now what I am looking for is to place 10 urls in a chunk to the address bar and get the 10 files to be downloaded at the same time.If it possible hope overall time will be decreased. Sorry I was late to give the code,here it is : def _download_file(url, filename): """ Given a URL and a filename, this method will save a file locally to the» destination_directory path. """ if not os.path.exists(destination_directory): print 'Directory [%s] does not exist, Creating directory...' % destination_directory os.makedirs(destination_directory) try: urllib.urlretrieve(url, os.path.join(destination_directory, filename)) print 'Downloading File [%s]' % (filename) except: print 'Error Downloading File [%s]' % (filename) def _download_all(main_url): """ Given a URL list, this method will download each file in the destination directory. """ url_list = _create_url_list(main_url) for url in url_list: _download_file(url, _get_file_name(url)) Thanks, Answer: Why use a browser? This seems like an [XY problem](http://meta.stackexchange.com/a/66378). To download files, I'd use a library like [requests](http://docs.python- requests.org/) (or make a system call to `wget`). Something like this: import requests def download_file_from_url(url, file_save_path): r = requests.get(url) if r.ok: # checks if the download succeeded with file(file_save_path, 'w') as f: f.write(r.content) return True else: return r.status_code download_file_from_url('http://imgs.xkcd.com/comics/tech_support_cheat_sheet.png', 'new_image.png') # will download image and save to current directory as 'new_image.png' You first have to install requests using whatever python package manager you prefer e.g., `pip install requests`. You can also get fancier; e.g.,
Expose a C++ global variable in Python Question: I'm trying to access to a C++ global variable in my Python code, using Cython. Let's say I have the following array in my C++ code: // Project.cpp int myArr[2] = { 0, 1 }; So, in Cython to define a pointer to _myArr_ : cdef extern int * myArr_ptr Does **myArr_ptr** really points to the C++ array? Or is just a random value? Answer: OK, the problem is: `Project.cpp` has a global `int *myArr;`, it's not listed in `Project.h`, and you want to access it from Cython without importing `Project.cpp`. In the comments, you say: > I can't include Project.cpp because this file will try to include other > files that were already included and will try to redefine many variables. The way you described it, there might be an elementary error here. You probably know these basic things, so please don't be insulted that I bring them up, but I just want to be thorough: First, if your header files don't have guards against multiple inclusion, fix that, and then you don't need to worry about "I can't include `Project.cpp` because this file will try to include other files that were already included and will try to redefine many variables." (And if you don't have header files, and you're just doing everything in .cpp files with explicit `extern` statements all over the place, don't do that—it's a bad idea in C and C++, well before you get to Cythonizing.) Second, if your module is meant to interface to a .so/.dll/.dylib that `Project.cpp` is part of, you shouldn't be building against the source to that library, but to the installed interface. On the other hand, if your module is meant to directly include the C++ code, then you _have_ to include `Project.cpp`. If you use `extern` declarations to reference things that you aren't going to link in, you're just going to get a linker error—or, if you're unlucky, everything will build but then fail at runtime. Third, if it isn't actually global, you can't access from outside of `Project.cpp`—for reasons of scope, lifetime, or linkage, no other kind of variable is usable in a separate implementation file. Again, I assume you know all those basic things, and I just misread your comment. There _is_ a real problem case where you need to wrap something with a poorly-designed API that requires you to reach into the internals, and that can be tricky sometimes, and you probably did run into such a thing, and I just haven't figured out exactly how. There are three basic solutions. First, obviously, if you can build a proper native API, then wrapping that API in Cython is trivial. And this is useful for other reasons, at the same time. Sometimes, this would be too much time and effort—e.g., if the native library wasn't designed to be driven externally, and is a mass of 10 years of legacy maintenance, and the only reason you're ever going to have to wrap it is the current Cython project, you may not want to clean it up. Or, if it's a rapidly-changing library that you need to keep up to date with and don't have source control over, forking it and trying to keep in sync can be a nightmare. And so on. But if there's no such reason in your case, this is the right answer. If you can just `cdef extern from "project.h"`, everything is easy. You can do a simpler version of that by creating a "shim API" at the native level, creating separate `.h` files with the appropriate extern, function, and type declarations for the various, functions, and types you need to use from the internals. Then, you can just `cdef extern from "project_extras.h"`. Finally, you can always write explicit `cdef extern` statements for anything, without telling Cython where any of it comes from. Cython will turn this into the appropriate native externs in the generated code, and if you get everything right, it will work. There are some downsides here—[the docs](http://docs.cython.org/src/userguide/external_C_code.html#referencing-c- header-files) explain all the advantages of `cdef extern from` that you'll be giving up. The short version is, your Cython declarations have to exactly match the native declarations; otherwise, instead of getting automatically fixed up or raising a nice error at the Cython stage, you'll get an inscrutable error message from the C compiler referring to the unreadable Cython-generated C code instead of your actual code—or, worse, code that compiles but does the wrong thing. For the case of a simple `int *` or `int []` value, all of this scarcely matters, because that doesn't need any interpretation; a plain `cdef extern` should be just fine.
How to pass a parameter list to another function in Python? Question: Using `optparse`, I want to separate the list of option list parameters from the place where I call add_option(). How do I package the stuff up in File A (and then unpack in file B) so that this will work? The parser_options.append() lines will not work as written... File A: import file_b parser_options = [] parser_options.append(('-b', '--bootcount', type='string', dest='bootcount', default='', help='Number of times to repeat booting and testing, if applicable')) parser_options.append(('-d', '--duration', type='string', dest='duration', default='', help='Number of hours to run the test. Decimals OK')) my_object = file_b.B(parser_options) File B recieves parser_options as input: import optparse class B: def __init__(self, parser_options): self.parser = optparse.OptionParser('MyTest Options') if parser_options: for option in parser_options: self.parser.add_option(option) _*_ EDIT: Fixed to use ojbects Answer: Rather than try to shoehorn your options into some data structure, wouldn't it be simpler to define a function in file A that adds options to a parser you give it? File A: def addOptions(parser): parser.add_option('-b', '--bootcount', type='string', dest='bootcount', default='', help='Number of times to repeat booting and testing, if applicable') parser.add_option('-d', '--duration', type='string', dest='duration', default='', help='Number of hours to run the test. Decimals OK') File B: import optparse def build_parser(parser_options): parser = optparse.OptionParser('MyTest Options') if parser_options: parser_options(parser) elsewhere: import file_a import file_b file_b.build_parser(file_a.addOptions)
Python @property in Flask configs? Question: I'm currently learning Flask and I just set up a config file I load into the app with: app.config.from_object('myconfigmodule') The config module has two classes in it, Config and DebugConfig and DebugConfig inherits Config. I'd like to use @property getters to get config variables rather than accessing them with `app.config['myvar']` because it makes for cleaner code. I set this up and app.config does not see the properties but I can still access the config class members with `app.config['myvar']` This is the error I get when I start my app: Traceback (most recent call last): File "runserver.py", line 3, in <module> app.run(host=app.config['_APP_HOST'], debug=app.config.Debug) AttributeError: 'Config' object has no attribute 'Debug' In the config class the Debug property is as follows: class Config (object): _APP_DEBUG = False @property def Debug (self): return self._APP_DEBUG Am I doing something wrong here or does Flask just not like properties in configs for some reason? Thanks for any help! Answer: Flask has it's own `Config` class (a dict subclass) and it will pick out the attributes of the object given to `from_object`, rather that using the given object as is, as can be seen in the [source code](https://github.com/mitsuhiko/flask/blob/master/flask/config.py#L163): # class Config(dict): # ... for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key) As you can see, it will only use _uppercase_ attributes. Here's an example _by hand_ : >>> from flask import config >>> class X(object): ... REGULAR = True ... ignored = "not uppercase" ... def __init__(self): ... self.not_used = "because lowercase" ... self.OK = True ... ... @property ... def UPPER_PROP(self): ... return True ... ... @property ... def MIXED_case(self): ... return "wont work" ... >>> x = X() >>> c = config.Config(None) >>> c.from_object(x) >>> c <Config {'REGULAR': True, 'OK': True, 'UPPER_PROP': True}> That said, nothing will hold you back, if you want to implement something like a [dot-dict'd](http://parand.com/say/index.php/2008/10/24/python-dot-notation- dictionary-access/) subclass of flasks' `Config`. Whether the potential confusion caused by a non-standard approach outweighs the gains in code readability is something you can decide based on the scope of your project.