content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Parameters not getting passed properly Here's an excerpt of my code: def listFrom(here): print "[DBG] here: " + here def book(here, there, amount): print "[DBG] here: " + here + "; there: " + there + "; amount: " + str(amount) # Code that takes input and stores it into the string input # Yes, I know this is dangerous, but it's part of a # school assignment where we HAVE to use eval. eval(input, {"__builtins__": {}, "listAll": listAll, "listFrom": listFrom, "listFromTo": listFromTo, "book": book, "about": about, "commands": commands, "book": book}) If I enter listFrom('LON'), the program returns [DBG] here: LON as expected. However, when I do book('LON', 'MAN', 8) I get an inexplicable [DBG] here: ☺; there: ☻; amount: ♥. What could be the cause of this? A: This code works without problems in Python 2.6 on Linux/x86-32: >>> def listFrom(here): ... print "[DBG] here: " + here ... >>> def book(here, there, amount): ... print "[DBG] here: " + here + "; there: " + there + "; amount: " + str(amount) ... >>> book('LON', 'MAN', 8) [DBG] here: LON; there: MAN; amount: 8 >>> input = """book('LON', 'MAN', 8)""" >>> eval(input, {"__builtins__": {}, "listFrom": listFrom, "book": book}) [DBG] here: LON; there: MAN; amount: 8 >>> eval("""listFrom('LON')""", {"__builtins__": {}, "listFrom": listFrom, "book": book}) [DBG] here: LON What Python version are you using? On which OS/architecture?
Parameters not getting passed properly
Here's an excerpt of my code: def listFrom(here): print "[DBG] here: " + here def book(here, there, amount): print "[DBG] here: " + here + "; there: " + there + "; amount: " + str(amount) # Code that takes input and stores it into the string input # Yes, I know this is dangerous, but it's part of a # school assignment where we HAVE to use eval. eval(input, {"__builtins__": {}, "listAll": listAll, "listFrom": listFrom, "listFromTo": listFromTo, "book": book, "about": about, "commands": commands, "book": book}) If I enter listFrom('LON'), the program returns [DBG] here: LON as expected. However, when I do book('LON', 'MAN', 8) I get an inexplicable [DBG] here: ☺; there: ☻; amount: ♥. What could be the cause of this?
[ "This code works without problems in Python 2.6 on Linux/x86-32:\n>>> def listFrom(here):\n... print \"[DBG] here: \" + here\n... \n>>> def book(here, there, amount):\n... print \"[DBG] here: \" + here + \"; there: \" + there + \"; amount: \" + str(amount)\n... \n>>> book('LON', 'MAN', 8)\n[DBG] here: LON; there: MAN; amount: 8\n>>> input = \"\"\"book('LON', 'MAN', 8)\"\"\"\n>>> eval(input, {\"__builtins__\": {}, \"listFrom\": listFrom, \"book\": book})\n[DBG] here: LON; there: MAN; amount: 8\n>>> eval(\"\"\"listFrom('LON')\"\"\", {\"__builtins__\": {}, \"listFrom\": listFrom, \"book\": book})\n[DBG] here: LON\n\nWhat Python version are you using? On which OS/architecture?\n" ]
[ 0 ]
[]
[]
[ "eval", "python" ]
stackoverflow_0002347266_eval_python.txt
Q: Python: passing a function with parameters as parameter def lite(a,b,c): #... def big(func): # func = callable() #... #main big(lite(1,2,3)) how to do this? in what way to pass function with parameters to another function? A: Why not do: big(lite, (1, 2, 3)) ? Then you can do: def big(func, args): func(*args) A: import functools #main big(functools.partial(lite, 1,2,3)) A: Similar problem is usually solved in two ways: With lambda… but then the passed function will expect one argument, so big() needs to be changed With named functions calling the original functions with arguments. Please note, that such function can be declared inside other function and the arguments can be variables. See the example: #!/usr/bin/python def lite(a,b,c): return "%r,%r,%r" % (a,b,c) def big(func): # func = callable() print func() def big2(func): # func = callable with one argument print func("anything") def main(): param1 = 1 param2 = 2 param3 = 3 big2(lambda x: lite(param1, param2, param3)) def lite_with_params(): return lite(param1,param2,param3) big(lite_with_params) main() A: Not this way, you're passing to big the return value of lite() function. You should do something like: def lite(a, b, c): return a + b + c def big(func, arg): print func(arg[0], arg[1], arg[2]) big(lite, (1, 2, 3))
Python: passing a function with parameters as parameter
def lite(a,b,c): #... def big(func): # func = callable() #... #main big(lite(1,2,3)) how to do this? in what way to pass function with parameters to another function?
[ "Why not do:\nbig(lite, (1, 2, 3))\n\n?\nThen you can do:\ndef big(func, args):\n func(*args)\n\n", "import functools\n\n#main\nbig(functools.partial(lite, 1,2,3))\n\n", "Similar problem is usually solved in two ways:\n\nWith lambda… but then the passed function will expect one argument, so big() needs to be changed\nWith named functions calling the original functions with arguments. Please note, that such function can be declared inside other function and the arguments can be variables.\n\nSee the example:\n#!/usr/bin/python\n\ndef lite(a,b,c):\n return \"%r,%r,%r\" % (a,b,c)\n\ndef big(func): # func = callable()\n print func()\n\ndef big2(func): # func = callable with one argument\n print func(\"anything\")\n\n\ndef main():\n param1 = 1\n param2 = 2\n param3 = 3\n\n big2(lambda x: lite(param1, param2, param3))\n\n def lite_with_params():\n return lite(param1,param2,param3)\n\n big(lite_with_params)\n\nmain()\n\n", "Not this way, you're passing to big the return value of lite() function.\nYou should do something like:\ndef lite(a, b, c):\n return a + b + c\n\ndef big(func, arg):\n print func(arg[0], arg[1], arg[2])\n\n\n\nbig(lite, (1, 2, 3))\n\n" ]
[ 43, 11, 3, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0002347388_function_python.txt
Q: How to consume XML from RESTful web services using Django / Python? Should I use PyXML or what's in the standard library? A: ElementTree is provided as part of the standard Python libs. ElementTree is pure python, and cElementTree is the faster C implementation: # Try to use the C implementation first, falling back to python try: from xml.etree import cElementTree as ElementTree except ImportError, e: from xml.etree import ElementTree Here's an example usage, where I'm consuming xml from a RESTful web service: def find(*args, **kwargs): """Find a book in the collection specified""" search_args = [('access_key', api_key),] if not is_valid_collection(kwargs['collection']): return None kwargs.pop('collection') for key in kwargs: # Only the first keword is honored if kwargs[key]: search_args.append(('index1', key)) search_args.append(('value1', kwargs[key])) break url = urllib.basejoin(api_url, '%s.xml' % 'books') data = urllib.urlencode(search_args) req = urllib2.urlopen(url, data) rdata = [] chunk = 'xx' while chunk: chunk = req.read() if chunk: rdata.append(chunk) tree = ElementTree.fromstring(''.join(rdata)) results = [] for i, elem in enumerate(tree.getiterator('BookData')): results.append( {'isbn': elem.get('isbn'), 'isbn13': elem.get('isbn13'), 'title': elem.find('Title').text, 'author': elem.find('AuthorsText').text, 'publisher': elem.find('PublisherText').text,} ) return results A: I always prefer to use the standard library when possible. ElementTree is well known amongst pythonistas, so you should be able to find plenty of examples. Parts of it have also been optimized in C, so it's quite fast. http://docs.python.org/library/xml.etree.elementtree.html A: There's also BeautifulSoup, which has an API some might prefer. Here's an example on how you can extract all tweets that have been favorited from Twitter's Public Timeline: from BeautifulSoup import BeautifulStoneSoup import urllib url = urllib.urlopen('http://twitter.com/statuses/public_timeline.xml').read() favorited = [] soup = BeautifulStoneSoup(url) statuses = soup.findAll('status') for status in statuses: if status.find('favorited').contents != [u'false']: favorited.append(status)
How to consume XML from RESTful web services using Django / Python?
Should I use PyXML or what's in the standard library?
[ "ElementTree is provided as part of the standard Python libs. ElementTree is pure python, and cElementTree is the faster C implementation:\n# Try to use the C implementation first, falling back to python\ntry:\n from xml.etree import cElementTree as ElementTree\nexcept ImportError, e:\n from xml.etree import ElementTree\n\nHere's an example usage, where I'm consuming xml from a RESTful web service:\ndef find(*args, **kwargs):\n \"\"\"Find a book in the collection specified\"\"\"\n\n search_args = [('access_key', api_key),]\n if not is_valid_collection(kwargs['collection']):\n return None\n kwargs.pop('collection')\n for key in kwargs:\n # Only the first keword is honored\n if kwargs[key]:\n search_args.append(('index1', key))\n search_args.append(('value1', kwargs[key]))\n break\n\n url = urllib.basejoin(api_url, '%s.xml' % 'books')\n data = urllib.urlencode(search_args)\n req = urllib2.urlopen(url, data)\n rdata = []\n chunk = 'xx'\n while chunk:\n chunk = req.read()\n if chunk:\n rdata.append(chunk)\n tree = ElementTree.fromstring(''.join(rdata))\n results = []\n for i, elem in enumerate(tree.getiterator('BookData')):\n results.append(\n {'isbn': elem.get('isbn'),\n 'isbn13': elem.get('isbn13'),\n 'title': elem.find('Title').text,\n 'author': elem.find('AuthorsText').text,\n 'publisher': elem.find('PublisherText').text,}\n )\n return results\n\n", "I always prefer to use the standard library when possible. ElementTree is well known amongst pythonistas, so you should be able to find plenty of examples. Parts of it have also been optimized in C, so it's quite fast.\nhttp://docs.python.org/library/xml.etree.elementtree.html\n", "There's also BeautifulSoup, which has an API some might prefer. Here's an example on how you can extract all tweets that have been favorited from Twitter's Public Timeline:\nfrom BeautifulSoup import BeautifulStoneSoup\nimport urllib\n\nurl = urllib.urlopen('http://twitter.com/statuses/public_timeline.xml').read()\nfavorited = []\n\nsoup = BeautifulStoneSoup(url)\nstatuses = soup.findAll('status')\n\nfor status in statuses:\n if status.find('favorited').contents != [u'false']:\n favorited.append(status)\n\n" ]
[ 10, 3, 0 ]
[]
[]
[ "django", "python", "rest", "xml" ]
stackoverflow_0000804992_django_python_rest_xml.txt
Q: Baby steps to a solution with django and mod-wsgi on os x I'm running apache / os x and serving up localhost pages to test django on my laptop. I've already verified all the following • python is working fine and up to date (2.5.1) • django available to python and up to date (1,1,0, 'final', 0) • mod_wsgi module is loaded among apache modules in my apache config - Check! • path to django application is in vhost.conf with proper permissions - OK! • mod_wsgi vhost.conf tested and working fine in the intended django application directory - test application through localhost pulls up 200 OK, 'hello world!' • django default application has been created using 'django-admin.py startproject mysite' • django application works fine on port 8000 using development server - OK! • path to the new django application (called mysite) is on python path - verified! All this is verified and when I run the wsgi script with DJANGO_SETTINGS_MODULE settings.py and load the django app, I still get 'could not import settings 'mysite.settings' etc. Since this seems to cover the basic troubleshooting, are there any further steps I could take to find out the problem? ================ Python path is valid, verified. The django development server runs fine with the command line on port 8000. The apache config has the typical module loaded: LoadModule wsgi_module libexec/apache2/mod_wsgi.so vhost.conf is included from apache config as follows NameVirtualHost: *.80 <Directory /users/useracct/scripts/python> Order allow,deny Allow from all </Directory> <Directory /Library/WebServer/Documents> Order allow,deny Allow from all </Directory> WSGIDaemonProcess localhost user=username group=staff threads=25 WSGIProcessGroup localhost WSGIScriptAlias /mysite /users/useracct/Sites/mysite/mysite.wsgi <Directory /users/useracct/Sites/mysite/> Allow from all </Directory> DocumentRoot /Users/useracct/Sites/ Virtualenv is not set up with this account, so that is one less possible cause. ======================= and the wsgi script file (trying to keep it minimal): import os, sys path = '/users/usracct/sites/mysite' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() A: Try adding /users/useracct/Sites/ a to your pythonpath in your wsgi file: import os import sys ..... sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') ....
Baby steps to a solution with django and mod-wsgi on os x
I'm running apache / os x and serving up localhost pages to test django on my laptop. I've already verified all the following • python is working fine and up to date (2.5.1) • django available to python and up to date (1,1,0, 'final', 0) • mod_wsgi module is loaded among apache modules in my apache config - Check! • path to django application is in vhost.conf with proper permissions - OK! • mod_wsgi vhost.conf tested and working fine in the intended django application directory - test application through localhost pulls up 200 OK, 'hello world!' • django default application has been created using 'django-admin.py startproject mysite' • django application works fine on port 8000 using development server - OK! • path to the new django application (called mysite) is on python path - verified! All this is verified and when I run the wsgi script with DJANGO_SETTINGS_MODULE settings.py and load the django app, I still get 'could not import settings 'mysite.settings' etc. Since this seems to cover the basic troubleshooting, are there any further steps I could take to find out the problem? ================ Python path is valid, verified. The django development server runs fine with the command line on port 8000. The apache config has the typical module loaded: LoadModule wsgi_module libexec/apache2/mod_wsgi.so vhost.conf is included from apache config as follows NameVirtualHost: *.80 <Directory /users/useracct/scripts/python> Order allow,deny Allow from all </Directory> <Directory /Library/WebServer/Documents> Order allow,deny Allow from all </Directory> WSGIDaemonProcess localhost user=username group=staff threads=25 WSGIProcessGroup localhost WSGIScriptAlias /mysite /users/useracct/Sites/mysite/mysite.wsgi <Directory /users/useracct/Sites/mysite/> Allow from all </Directory> DocumentRoot /Users/useracct/Sites/ Virtualenv is not set up with this account, so that is one less possible cause. ======================= and the wsgi script file (trying to keep it minimal): import os, sys path = '/users/usracct/sites/mysite' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()
[ "Try adding /users/useracct/Sites/ a to your pythonpath in your wsgi file:\nimport os\nimport sys\n.....\nsys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')\n....\n\n" ]
[ 2 ]
[]
[]
[ "apache", "django", "macos", "mod_wsgi", "python" ]
stackoverflow_0002336253_apache_django_macos_mod_wsgi_python.txt
Q: Coping dictionary within a dictionary(Nested dictionary) I am having a dictionary like as dict1 = { 0 : 0, 1 : 1, 2 : { 0: 0, 1 : 1}} (which is also having a dictionary as value). I want to keep store these value same for some modification checking purpose. So now I am copy this dictionary content into another dictionary as dict2 = dict1.copy(). Now I am changing the values of dict2 like as { 0 : -1, 1 : -2, 2: { 0 : -1, i : -2}}. Now the problem is that my dict1's dictionary value also changing as { 0 : 0, 1 : 1, 2:{ 0 : -1, 1 : -2}}. Here you can see this easily dict1's key 2 values also changing as dict2's key 2 values. How should I copy the dict2 from dict1 so if change dict2's key 2 value this should not put a impact on the dict1's key = 2 values? A: Use copy.deepcopy to perform a deep copy.
Coping dictionary within a dictionary(Nested dictionary)
I am having a dictionary like as dict1 = { 0 : 0, 1 : 1, 2 : { 0: 0, 1 : 1}} (which is also having a dictionary as value). I want to keep store these value same for some modification checking purpose. So now I am copy this dictionary content into another dictionary as dict2 = dict1.copy(). Now I am changing the values of dict2 like as { 0 : -1, 1 : -2, 2: { 0 : -1, i : -2}}. Now the problem is that my dict1's dictionary value also changing as { 0 : 0, 1 : 1, 2:{ 0 : -1, 1 : -2}}. Here you can see this easily dict1's key 2 values also changing as dict2's key 2 values. How should I copy the dict2 from dict1 so if change dict2's key 2 value this should not put a impact on the dict1's key = 2 values?
[ "Use copy.deepcopy to perform a deep copy.\n" ]
[ 11 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002347854_dictionary_python.txt
Q: Dynamic Event Conditions Consider that we've a class named Foo that fires "ready" event when it's ready. from observer import SubjectSet class Foo: def __init__(self): self.events = SubjectSet() self.events.create('ready') def do_sth(self): self.events.fire('ready') As you see, do_sth method makes ready instances of the Foo class. But subclasses will want to add new tasks/conditions that have to be done before emit ready event. To solve this problem, I've coded a set of new classes named TaskPool, Task, ObserverTask. They are being used by the Foo class like this: from observer import SubjectSet from taskpool import TaskPool, ObserverTask class Foo: def __init__(self): self.events = SubjectSet() self.events.create('task1') self.events.create('task2') self.events.create('ready') task1 = ObserverTask( self.events.get('task1') ) task1 = ObserverTask( self.events.get('task2') ) self.tasks = TaskPool() self.tasks.append( task1, task2 ) self.tasks.events.add_listener('success',self.events.subjects.ready.emit) def complete_task1(self): self.events.fire('task1') def complete_task2(self): self.events.fire('task2') Now, it fires "ready" event when it's taskpool fires "success" event. As you expect, the classes which will extend Foo can define new tasks that have to be completed before fire the ready event. By the way, almost all of the tasks are asynchronous. Do you think that it's a good solution to the problem? I've been looking for better solutions but I guess I don't know the right search phrase. Thanks. A: I think you do not actually define very exactly what is the problem you try to solve. However, there's nothing wrong with the solution. It's clearly asynchronous and event-driven. But I think in general the solution should also arrow for error conditions, i.e. what happens if task1 or task2 fails due to any reason---they should be maybe allowed to also send a 'failed' event, and then this should be also propagated out of Foo with some logic---i.e. if task1 fails, will task2 still run to completion or will it be aborted; and if task1 succeeds and task2 fails, will the main object report 'success' or 'failed' out or what? Just things to consider.
Dynamic Event Conditions
Consider that we've a class named Foo that fires "ready" event when it's ready. from observer import SubjectSet class Foo: def __init__(self): self.events = SubjectSet() self.events.create('ready') def do_sth(self): self.events.fire('ready') As you see, do_sth method makes ready instances of the Foo class. But subclasses will want to add new tasks/conditions that have to be done before emit ready event. To solve this problem, I've coded a set of new classes named TaskPool, Task, ObserverTask. They are being used by the Foo class like this: from observer import SubjectSet from taskpool import TaskPool, ObserverTask class Foo: def __init__(self): self.events = SubjectSet() self.events.create('task1') self.events.create('task2') self.events.create('ready') task1 = ObserverTask( self.events.get('task1') ) task1 = ObserverTask( self.events.get('task2') ) self.tasks = TaskPool() self.tasks.append( task1, task2 ) self.tasks.events.add_listener('success',self.events.subjects.ready.emit) def complete_task1(self): self.events.fire('task1') def complete_task2(self): self.events.fire('task2') Now, it fires "ready" event when it's taskpool fires "success" event. As you expect, the classes which will extend Foo can define new tasks that have to be completed before fire the ready event. By the way, almost all of the tasks are asynchronous. Do you think that it's a good solution to the problem? I've been looking for better solutions but I guess I don't know the right search phrase. Thanks.
[ "I think you do not actually define very exactly what is the problem you try to solve. However, there's nothing wrong with the solution. It's clearly asynchronous and event-driven. But I think in general the solution should also arrow for error conditions, i.e. what happens if task1 or task2 fails due to any reason---they should be maybe allowed to also send a 'failed' event, and then this should be also propagated out of Foo with some logic---i.e. if task1 fails, will task2 still run to completion or will it be aborted; and if task1 succeeds and task2 fails, will the main object report 'success' or 'failed' out or what? Just things to consider.\n" ]
[ 1 ]
[]
[]
[ "algorithm", "asynchronous", "events", "python" ]
stackoverflow_0002347958_algorithm_asynchronous_events_python.txt
Q: Google Books API - Getting Book Ratings? I cannot find a way to get a Book's Ratings through the Books API provided by Google. All I figured out is how to obtain search listings, which do not include ratings and description. Help would be very much appreciated. A: I've never used Google Book API, but its documentation claims you can only retrieve an annotation (incl. review) for a specific user. Another proof is some post by Google employee who claims it's not supported (yet).
Google Books API - Getting Book Ratings?
I cannot find a way to get a Book's Ratings through the Books API provided by Google. All I figured out is how to obtain search listings, which do not include ratings and description. Help would be very much appreciated.
[ "I've never used Google Book API, but its documentation claims you can only retrieve an annotation (incl. review) for a specific user.\nAnother proof is some post by Google employee who claims it's not supported (yet).\n" ]
[ 2 ]
[]
[]
[ "ajax", "google_books", "python" ]
stackoverflow_0002284595_ajax_google_books_python.txt
Q: webcam motion tracking with Python Is there a simple way to track the motions of a single entity in a webcam feed? For example, I imagine a "hello world" app with an index finger used as mouse pointer. I realize there's still a lot of basic research in this area, so it might be too early to expect an easy to use, generic abstraction. For the sake of completeness, I've seen some related but lower-level (and non-Python) projects being mentioned, including AForge, WiimoteLib and an article on motion detection algorithms. A: You might want to take a look at http://opencv.willowgarage.com/wiki/PythonInterface. I'm not sure how hard it would be to do arbitrary motion tracking, but it was fairly simple to implement face tracking.
webcam motion tracking with Python
Is there a simple way to track the motions of a single entity in a webcam feed? For example, I imagine a "hello world" app with an index finger used as mouse pointer. I realize there's still a lot of basic research in this area, so it might be too early to expect an easy to use, generic abstraction. For the sake of completeness, I've seen some related but lower-level (and non-Python) projects being mentioned, including AForge, WiimoteLib and an article on motion detection algorithms.
[ "You might want to take a look at http://opencv.willowgarage.com/wiki/PythonInterface. I'm not sure how hard it would be to do arbitrary motion tracking, but it was fairly simple to implement face tracking.\n" ]
[ 4 ]
[]
[]
[ "motion_detection", "python" ]
stackoverflow_0002348151_motion_detection_python.txt
Q: Share data between mod_python processes I'm running mod_python under Apache. If I've understood correctly, each Apache process runs its own Python interpreter. What would be the best way to share a tiny amount of data across all the processes? I'm talking about just a few hundred bytes here, making something database based completely overkill. A: Put it in shared memory. A: The quickest way is to use file IO. One process writes the file and the other reads it. You can use the mmap module to make this a little more seamless. One interesting alternative that I haven't tried (yet) is to use some derivative of multiprocessing.Manager to communicate between the processes. I haven't tried the latter, I was looking for some way to create a process-shared semaphore.
Share data between mod_python processes
I'm running mod_python under Apache. If I've understood correctly, each Apache process runs its own Python interpreter. What would be the best way to share a tiny amount of data across all the processes? I'm talking about just a few hundred bytes here, making something database based completely overkill.
[ "Put it in shared memory.\n", "The quickest way is to use file IO. One process writes the file and the other reads it. You can use the mmap module to make this a little more seamless. One interesting alternative that I haven't tried (yet) is to use some derivative of multiprocessing.Manager to communicate between the processes. I haven't tried the latter, I was looking for some way to create a process-shared semaphore.\n" ]
[ 1, 1 ]
[]
[]
[ "apache", "mod_python", "python", "share" ]
stackoverflow_0002348202_apache_mod_python_python_share.txt
Q: Python PIL and StringIO I'm trying to download images from URLs and pass them to PIL. I would like to use as few resources as possible, especially RAM. What would the best way of dealing with this? I've had suggestions to use cStringIO. A: Unfortunately file-likes from network functions such as urllib2.urlopen() don't support all the necessary methods, so you'll need to read the data into a StringIO or cStringIO in order to be able to pass them to Image.open().
Python PIL and StringIO
I'm trying to download images from URLs and pass them to PIL. I would like to use as few resources as possible, especially RAM. What would the best way of dealing with this? I've had suggestions to use cStringIO.
[ "Unfortunately file-likes from network functions such as urllib2.urlopen() don't support all the necessary methods, so you'll need to read the data into a StringIO or cStringIO in order to be able to pass them to Image.open().\n" ]
[ 4 ]
[]
[]
[ "django", "python", "python_imaging_library" ]
stackoverflow_0002348443_django_python_python_imaging_library.txt
Q: Scraping for a "preview" of a webpage - Python I'm indexing a list of links, these links update quite often so I'm automating thumbnails for the sites. For most sites it's easy, as I just grab the biggest image on the page hoping it describes the content. But other times there are videos as main content of the page. Does somebody have tips with dealing with this? That would be great! Regarding the usage of Webkit to create screenshots I found this A: wkhtmltopdf uses an embedded copy of the WebKit render engine (used in Safari, Chrome etc.) to save a webpage to PDF, including all images (no Flash video though I guess). That could be a starting point for a much more accurate thumbnail. A: There exists (free and paid) services that do exactly what you need. I use shrink the web:
Scraping for a "preview" of a webpage - Python
I'm indexing a list of links, these links update quite often so I'm automating thumbnails for the sites. For most sites it's easy, as I just grab the biggest image on the page hoping it describes the content. But other times there are videos as main content of the page. Does somebody have tips with dealing with this? That would be great! Regarding the usage of Webkit to create screenshots I found this
[ "wkhtmltopdf uses an embedded copy of the WebKit render engine (used in Safari, Chrome etc.) to save a webpage to PDF, including all images (no Flash video though I guess). That could be a starting point for a much more accurate thumbnail.\n", "There exists (free and paid) services that do exactly what you need. I use shrink the web: \n" ]
[ 3, 3 ]
[]
[]
[ "django", "html", "python", "screen_scraping" ]
stackoverflow_0002348401_django_html_python_screen_scraping.txt
Q: What's wrong with this string normilizer Python snippet? It seems that every time I think I mastered encoding, I find something new to puzzle me :-) I'm trying to get rid of French accents from an UTF-8 string: >>> import unicodedata >>> s = u"éèêàùçÇ" >>> print(unicodedata.normalize('NFKD', s).encode('ascii','ignore')) I expected eeeaucC as an output and got instead AA AaA A1AA using Python 2.6.4 in Ubuntu 9.10 and iPython 0.10, all the stuff set to unicode. A: Afters further tests, it works if you use Python 3 or Python 2.6 interpreters instead of iPython. Maybe a wrong user setting or a bug. A: python works as it should: $ python Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> s = u"éèêàùçÇ" >>> s u'\xe9\xe8\xea\xe0\xf9\xe7\xc7' >>> ord(s[0]) 233 There is some bug in ipython: $ ipython Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) Type "copyright", "credits" or "license" for more information. IPython 0.10 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: s = u"éèêàùçÇ" In [2]: ord(s[0]) Out[2]: 195 In [3]: s Out[3]: u'\xc3\xa9\xc3\xa8\xc3\xaa\xc3\xa0\xc3\xb9\xc3\xa7\xc3\x87' If you read it from file then ipython works: $ ipython ... In [1]: import codecs In [2]: s = codecs.open('s.txt', 'r', 'utf-8').read() In [3]: s Out[3]: u'\xe9\xe8\xea\xe0\xf9\xe7\xc7' In [4]: ord(s[0]) Out[4]: 233
What's wrong with this string normilizer Python snippet?
It seems that every time I think I mastered encoding, I find something new to puzzle me :-) I'm trying to get rid of French accents from an UTF-8 string: >>> import unicodedata >>> s = u"éèêàùçÇ" >>> print(unicodedata.normalize('NFKD', s).encode('ascii','ignore')) I expected eeeaucC as an output and got instead AA AaA A1AA using Python 2.6.4 in Ubuntu 9.10 and iPython 0.10, all the stuff set to unicode.
[ "Afters further tests, it works if you use Python 3 or Python 2.6 interpreters instead of iPython.\nMaybe a wrong user setting or a bug.\n", "python works as it should:\n$ python\nPython 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) \n[GCC 4.4.1] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> s = u\"éèêàùçÇ\"\n>>> s\nu'\\xe9\\xe8\\xea\\xe0\\xf9\\xe7\\xc7'\n>>> ord(s[0])\n233\n\nThere is some bug in ipython:\n$ ipython\nPython 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) \nType \"copyright\", \"credits\" or \"license\" for more information.\n\nIPython 0.10 -- An enhanced Interactive Python.\n? -> Introduction and overview of IPython's features.\n%quickref -> Quick reference.\nhelp -> Python's own help system.\nobject? -> Details about 'object'. ?object also works, ?? prints more.\n\nIn [1]: s = u\"éèêàùçÇ\"\n\nIn [2]: ord(s[0])\nOut[2]: 195\n\nIn [3]: s\nOut[3]: u'\\xc3\\xa9\\xc3\\xa8\\xc3\\xaa\\xc3\\xa0\\xc3\\xb9\\xc3\\xa7\\xc3\\x87'\n\nIf you read it from file then ipython works:\n$ ipython\n...\nIn [1]: import codecs\n\nIn [2]: s = codecs.open('s.txt', 'r', 'utf-8').read()\n\nIn [3]: s\nOut[3]: u'\\xe9\\xe8\\xea\\xe0\\xf9\\xe7\\xc7'\n\nIn [4]: ord(s[0])\nOut[4]: 233\n\n" ]
[ 1, 0 ]
[]
[]
[ "encoding", "normalize", "python", "string" ]
stackoverflow_0002347953_encoding_normalize_python_string.txt
Q: Why do I need the DJANGO_SETTINGS_MODULE set? Every time I log on to my server through SSH I need to type the following: export DJANGO_SETTINGS_MODULE=settings if I do not any usage of the manage.py module fails My manage.py has the following added code: if "notification" in settings.INSTALLED_APPS: from notification import models as notification def create_notice_types(app, created_models, verbosity, **kwargs): notification.create_notice_type("friends_invite", _("Invitation Received"), _("you have received an invitation")) notification.create_notice_type("friends_accept", _("Acceptance Received"), _("an invitation you sent has been accepted")) signals.post_syncdb.connect(create_notice_types, sender=notification) else: print "Skipping creation of NoticeTypes as notification app not found" Any ideas? A: Yourmanage.py is referencing an application (notifications). This forces Django to complain about DJANGO_SETTINGS_MODULE being set because the Django environment hasn't been set up yet. Incidentally, you can force the enviroment setup manually, but honestly I wouldn't do this in manage.py. That's not really a good practice in my opinion. Here is how you can manually setup the Django environment from within any app (or program for that matter): # set up the environment using the settings module from django.core.management import setup_environ from myapp import settings setup_environ(settings) A: You need to set the DJANGO_SETTINGS_MODULE environment variable because it's how Django knows what your settings module is called (so you can have different ones per project or for testing and development.) You can set it in the scripts themselves before you import django (directly or indirectly) but that won't do much good when you run the Django-provided scripts. The easiest solution is probably to just set DJANGO_SETTINGS_MODULE in your shell's startup scripts, so you won't have to set it manually anymore. The usual files to add it to are .bash_profile and .bashrc (if you do indeed use bash.) A: By default, manage.py looks for a settings module in the same directory as itself. If it doesn't find one, it bombs out with a message to use django-admin.py instead. It doesn't actually set up the environemnt until it runs execute_manager. If you need to run your hooks before calling your management functions, the practice I've seen suggested is to put them in the relevant app's models.py.
Why do I need the DJANGO_SETTINGS_MODULE set?
Every time I log on to my server through SSH I need to type the following: export DJANGO_SETTINGS_MODULE=settings if I do not any usage of the manage.py module fails My manage.py has the following added code: if "notification" in settings.INSTALLED_APPS: from notification import models as notification def create_notice_types(app, created_models, verbosity, **kwargs): notification.create_notice_type("friends_invite", _("Invitation Received"), _("you have received an invitation")) notification.create_notice_type("friends_accept", _("Acceptance Received"), _("an invitation you sent has been accepted")) signals.post_syncdb.connect(create_notice_types, sender=notification) else: print "Skipping creation of NoticeTypes as notification app not found" Any ideas?
[ "Yourmanage.py is referencing an application (notifications). This forces Django to complain about DJANGO_SETTINGS_MODULE being set because the Django environment hasn't been set up yet.\nIncidentally, you can force the enviroment setup manually, but honestly I wouldn't do this in manage.py. That's not really a good practice in my opinion.\nHere is how you can manually setup the Django environment from within any app (or program for that matter):\n# set up the environment using the settings module\nfrom django.core.management import setup_environ\nfrom myapp import settings\nsetup_environ(settings)\n\n", "You need to set the DJANGO_SETTINGS_MODULE environment variable because it's how Django knows what your settings module is called (so you can have different ones per project or for testing and development.) You can set it in the scripts themselves before you import django (directly or indirectly) but that won't do much good when you run the Django-provided scripts.\nThe easiest solution is probably to just set DJANGO_SETTINGS_MODULE in your shell's startup scripts, so you won't have to set it manually anymore. The usual files to add it to are .bash_profile and .bashrc (if you do indeed use bash.)\n", "By default, manage.py looks for a settings module in the same directory as itself. If it doesn't find one, it bombs out with a message to use django-admin.py instead. It doesn't actually set up the environemnt until it runs execute_manager. If you need to run your hooks before calling your management functions, the practice I've seen suggested is to put them in the relevant app's models.py. \n" ]
[ 11, 6, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002102330_django_python.txt
Q: Is there any Python wrapper around cron? I'm looking for a wrapper around cron. I've stumbled upon PyCron but it's a Python implementation, not a wrapper. Do you know any good cron Python wrapper ? If not, did you test PyCron, and what can you tell about it ? //EDIT (As an answer to comment asking for more details): I am looking for something to set a cron job in a pythonic way such as: >>> job = CronJob(call_back) >>> job.schedule(datetime, repeat) >>> job.schedule(datetime2, repeat2) And I could edit the currents job this way: >>> jobs = loadFromCron() >>> jobs[0].shedule().schedule(datetime, repeat) >>> print(jobs[0]) <CronJob object - "call_back" at 2009-11-01> Ideally, that would write and read from "crontab" under linux and use "planified tasks" under windows. I may used the wrong terminology, is it more accurate to talk about a cron Python API ? A: python-crontab allows you to read and write user crontabs via python programs. from crontab import CronTab tab = CronTab() cron = tab.new(command='/foo/bar') cron.every_reboot() tab.write()
Is there any Python wrapper around cron?
I'm looking for a wrapper around cron. I've stumbled upon PyCron but it's a Python implementation, not a wrapper. Do you know any good cron Python wrapper ? If not, did you test PyCron, and what can you tell about it ? //EDIT (As an answer to comment asking for more details): I am looking for something to set a cron job in a pythonic way such as: >>> job = CronJob(call_back) >>> job.schedule(datetime, repeat) >>> job.schedule(datetime2, repeat2) And I could edit the currents job this way: >>> jobs = loadFromCron() >>> jobs[0].shedule().schedule(datetime, repeat) >>> print(jobs[0]) <CronJob object - "call_back" at 2009-11-01> Ideally, that would write and read from "crontab" under linux and use "planified tasks" under windows. I may used the wrong terminology, is it more accurate to talk about a cron Python API ?
[ "python-crontab allows you to read and write user crontabs via python programs.\nfrom crontab import CronTab\n\ntab = CronTab()\ncron = tab.new(command='/foo/bar')\ncron.every_reboot()\ntab.write()\n\n" ]
[ 11 ]
[]
[]
[ "cron", "python", "wrapper" ]
stackoverflow_0002343403_cron_python_wrapper.txt
Q: Creating a Persistent Data Object In Django I have a Python-based maximum entropy classifier. It's large, stored as a Pickle, and takes about a minute to unserialize. It's also not thread safe. However, it runs fast and can classify a sample (a simple Python dictionary) in a few milliseconds. I'd like to create a basic Django web app, so users can submit samples to classify in realtime. How would I load the classifier into persistent memory once, and then regulate it so that each request can access the object without conflicting with other requests? A: you could use djangos cache-framework and set the timeout to a extreme value A: Consider running it in another process. You could have your Django application submit samples via a socket that the classifier process listens on, or you could run a queue and have Django submit requests to the queue.
Creating a Persistent Data Object In Django
I have a Python-based maximum entropy classifier. It's large, stored as a Pickle, and takes about a minute to unserialize. It's also not thread safe. However, it runs fast and can classify a sample (a simple Python dictionary) in a few milliseconds. I'd like to create a basic Django web app, so users can submit samples to classify in realtime. How would I load the classifier into persistent memory once, and then regulate it so that each request can access the object without conflicting with other requests?
[ "you could use djangos cache-framework and set the timeout to a extreme value\n", "Consider running it in another process. You could have your Django application submit samples via a socket that the classifier process listens on, or you could run a queue and have Django submit requests to the queue.\n" ]
[ 4, 2 ]
[]
[]
[ "django", "persistence", "python" ]
stackoverflow_0002345257_django_persistence_python.txt
Q: Display value in Charfield for foreign key in django on error Let's say I've got a model and it has a foreign key to another one. class ModelA(models.Model): field = models.CharField(max_length=100) class ModelB(models.Model): model_a = models.ForeignKey(ModelA) Than I've got this form: class FormB(models.ModelForm): model_a = forms.CharField(required=True) def clean(self): model_a = self.cleaned_data["model_a"] try: v = ModelA.objects.get(model_a=model_a) self.cleaned_data["model_a"] = v except Exception: self._errors['model_a'] = ErrorList(["ModelA not found"]) return self.cleaned_data Now, whenever I enter a char value in FormB, it'll search for it in the ModelA and return the cleaned data. When I use the form to list the pre-existing instance it shows the ID and not the value. def my_view(request): instance = ModelB.objects.get()[0] form = FormB(instance=instance) return render_to_response("bla.html", {"form" : form}) Does anybody knows how I could show the value in this CharField when I pass the instance? Thanks, Nico A: I can think of two options: Make model_a field on ModelB hidden with editable=false, and add a CharField to ModelB to store the text the user entered. Then show this field in the form, but use its value to populate model_a. Use an autocomplete field, for example using django-autocomplete. This allows the user to type the name of the object instead of using a select widget. (But falls back to a select with no JavaScript).
Display value in Charfield for foreign key in django on error
Let's say I've got a model and it has a foreign key to another one. class ModelA(models.Model): field = models.CharField(max_length=100) class ModelB(models.Model): model_a = models.ForeignKey(ModelA) Than I've got this form: class FormB(models.ModelForm): model_a = forms.CharField(required=True) def clean(self): model_a = self.cleaned_data["model_a"] try: v = ModelA.objects.get(model_a=model_a) self.cleaned_data["model_a"] = v except Exception: self._errors['model_a'] = ErrorList(["ModelA not found"]) return self.cleaned_data Now, whenever I enter a char value in FormB, it'll search for it in the ModelA and return the cleaned data. When I use the form to list the pre-existing instance it shows the ID and not the value. def my_view(request): instance = ModelB.objects.get()[0] form = FormB(instance=instance) return render_to_response("bla.html", {"form" : form}) Does anybody knows how I could show the value in this CharField when I pass the instance? Thanks, Nico
[ "I can think of two options:\n\nMake model_a field on ModelB hidden with editable=false, and add a CharField to ModelB to store the text the user entered. Then show this field in the form, but use its value to populate model_a.\nUse an autocomplete field, for example using django-autocomplete. This allows the user to type the name of the object instead of using a select widget. (But falls back to a select with no JavaScript).\n\n" ]
[ 0 ]
[]
[]
[ "django", "foreign_keys", "forms", "python" ]
stackoverflow_0002348829_django_foreign_keys_forms_python.txt
Q: what is the pysvn command equvilent to "svn info file:///path/to/svn/repo"? I'm looking for a good python library to manipulate subversion repositories. I'm trying out PySvn, but finding that it can't handle something like pysvn.Client().info("/path/to/svn/repo") because it's not a working copy. Anyone know of any good libraries that can handle this kind of thing? Update - I'll try to simplify it - I want to get info about the repository. The same kind of info I get when I run svn info file:///path/to/svn/repo A: Do you try info2 instead of info? Documentation says it can access URL of repository.
what is the pysvn command equvilent to "svn info file:///path/to/svn/repo"?
I'm looking for a good python library to manipulate subversion repositories. I'm trying out PySvn, but finding that it can't handle something like pysvn.Client().info("/path/to/svn/repo") because it's not a working copy. Anyone know of any good libraries that can handle this kind of thing? Update - I'll try to simplify it - I want to get info about the repository. The same kind of info I get when I run svn info file:///path/to/svn/repo
[ "Do you try info2 instead of info? Documentation says it can access URL of repository.\n" ]
[ 5 ]
[]
[]
[ "python", "svn" ]
stackoverflow_0002348282_python_svn.txt
Q: pysqlite, query for duplicate entries with swapped columns Currently I have a pysqlite db that I am using to store a list of road conditions. The source this list is generated from however is buggy and sometimes generates duplicates. Some of these duplicates will have the start and end points swapped but everything else the same. The method i currently have looks like this: def getDupes(self): '''This method is used to return a list of dupilicate entries ''' self.__curs.execute('SELECT * FROM roadCond GROUP BY road, start, end, cond, reason, updated, county, timestmp HAVING count(*)>1') result = self.__curs.fetchall() def getSwaps(): '''This method is used to grab the duplicates with swapped columns ''' self.__curs.execute('SELECT * FROM roadCond WHERE ') extra = self.__curs.fetchall() return extrac result.extend(getSwaps()) return result The the initial query works but I am suspicious of it (I think there is a better way, I just don't know) but I am not all to sure how to make the inner method work. Thank you ahead of time. :-D A: Instead of the first query, you could use SELECT DISTINCT * FROM roadCond which will retrieve all the records from the table, removing any duplicates. As for the inner method, this query will return all the records which have "duplicates" with start and end swapped. Note that, for each record with "duplicates", this query will return both the "original" and the "copy". SELECT DISTINCT * FROM roadCond WHERE EXISTS ( SELECT * FROM roadCond rc2 WHERE roadCond.road = rc2.road AND roadCond.end = rc2.start AND roadCond.start = rc2.end AND roadCond.cond = rc2.cond AND ... AND roadCond.timestamp = rc2.timestamp) Edit: To detect and remove "duplicates" with start and end swapped, you could make sure that your data always contains these values laid out in the same order: UPDATE roadCond SET start = end, end = start WHERE end < start; But this approach only works if it doesn't matter which is which.
pysqlite, query for duplicate entries with swapped columns
Currently I have a pysqlite db that I am using to store a list of road conditions. The source this list is generated from however is buggy and sometimes generates duplicates. Some of these duplicates will have the start and end points swapped but everything else the same. The method i currently have looks like this: def getDupes(self): '''This method is used to return a list of dupilicate entries ''' self.__curs.execute('SELECT * FROM roadCond GROUP BY road, start, end, cond, reason, updated, county, timestmp HAVING count(*)>1') result = self.__curs.fetchall() def getSwaps(): '''This method is used to grab the duplicates with swapped columns ''' self.__curs.execute('SELECT * FROM roadCond WHERE ') extra = self.__curs.fetchall() return extrac result.extend(getSwaps()) return result The the initial query works but I am suspicious of it (I think there is a better way, I just don't know) but I am not all to sure how to make the inner method work. Thank you ahead of time. :-D
[ "Instead of the first query, you could use\nSELECT DISTINCT * FROM roadCond\n\nwhich will retrieve all the records from the table, removing any duplicates.\nAs for the inner method, this query will return all the records which have \"duplicates\" with start and end swapped. Note that, for each record with \"duplicates\", this query will return both the \"original\" and the \"copy\".\nSELECT DISTINCT * FROM roadCond WHERE EXISTS (\n SELECT * FROM roadCond rc2 WHERE\n roadCond.road = rc2.road AND\n roadCond.end = rc2.start AND roadCond.start = rc2.end AND\n roadCond.cond = rc2.cond AND\n ... AND\n roadCond.timestamp = rc2.timestamp)\n\nEdit: To detect and remove \"duplicates\" with start and end swapped, you could make sure that your data always contains these values laid out in the same order:\nUPDATE roadCond SET start = end, end = start WHERE end < start;\n\nBut this approach only works if it doesn't matter which is which.\n" ]
[ 0 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0002344610_python_sql_sqlite.txt
Q: Unable to get custom context processor to be invoked I am trying to create a custom context processor which will render a list of menu items for a logged in user. I have done the following: Within my settings.py I have TEMPLATE_CONTEXT_PROCESSOR = ( 'django.contrib.auth.context_processors.auth', 'mysite.accounts.context_processors.user_menu', ) Under the accounts submodule I have context_processors.py with the following, for now: def user_menu(request): return {'user_menu':'Hello World'} On my template page I have the following: {% if user.is_authenticated %} Menu {{user_menu}} {% endif %} The invoking view is as follows: def profile(request): return render_to_response('accounts/profile.html',context_instance=RequestContext(request)) However I am unable to get the {{user_menu}} to render anything on the page, I know the user is authenticated as other sections of the template with similar checks render correctly. Am I missing something here. Please help Thank you Edit: Thanks Ben, Daniel, I have fixed the (S) in TEMPLATE_CONTEXT_PROCESSOR, however Django now has trouble resolving the module and I get the following message Error importing request processor module django.contrib.auth.context_processors: "No module named context_processors" UPDATE: I fixed it by changing the path to django.core.context_processors.auth Seems like the modules have been moved around A: The setting name should be TEMPLATE_CONTEXT_PROCESSORS, with an S.
Unable to get custom context processor to be invoked
I am trying to create a custom context processor which will render a list of menu items for a logged in user. I have done the following: Within my settings.py I have TEMPLATE_CONTEXT_PROCESSOR = ( 'django.contrib.auth.context_processors.auth', 'mysite.accounts.context_processors.user_menu', ) Under the accounts submodule I have context_processors.py with the following, for now: def user_menu(request): return {'user_menu':'Hello World'} On my template page I have the following: {% if user.is_authenticated %} Menu {{user_menu}} {% endif %} The invoking view is as follows: def profile(request): return render_to_response('accounts/profile.html',context_instance=RequestContext(request)) However I am unable to get the {{user_menu}} to render anything on the page, I know the user is authenticated as other sections of the template with similar checks render correctly. Am I missing something here. Please help Thank you Edit: Thanks Ben, Daniel, I have fixed the (S) in TEMPLATE_CONTEXT_PROCESSOR, however Django now has trouble resolving the module and I get the following message Error importing request processor module django.contrib.auth.context_processors: "No module named context_processors" UPDATE: I fixed it by changing the path to django.core.context_processors.auth Seems like the modules have been moved around
[ "The setting name should be TEMPLATE_CONTEXT_PROCESSORS, with an S.\n" ]
[ 5 ]
[]
[]
[ "django", "django_context", "django_templates", "python" ]
stackoverflow_0002348943_django_django_context_django_templates_python.txt
Q: python single configuration file I am developing a project that requires a single configuration file whose data is used by multiple modules. My question is: what is the common approach to that? should i read the configuration file from each of my modules (files) or is there any other way to do it? I was thinking to have a module named config.py that reads the configuration files and whenever I need a config I do import config and then do something like config.data['teamsdir'] get the 'teamsdir' property (for example). response: opted for the conf.py approach then since it it is modular, flexible and simple I can just put the configuration data directly in the file, latter if i want to read from a json file a xml file or multiple sources i just change the conf.py and make sure the data is accessed the same way. accepted answer: chose "Alex Martelli" response because it was the most complete. voted up other answers because they where good and useful too. A: I like the approach of a single config.py module whose body (when first imported) parses one or more configuration-data files and sets its own "global variables" appropriately -- though I'd favor config.teamdata over the round-about config.data['teamdata'] approach. This assumes configuration settings are read-only once loaded (except maybe in unit-testing scenarios, where the test-code will be doing its own artificial setting of config variables to properly exercise the code-under-test) -- it basically exploits the nature of a module as the simplest Pythonic form of "singleton" (when you don't need subclassing or other features supported only by classes and not by modules, of course). "One or more" configuration files (e.g. first one somewhere in /etc for general default settings, then one under /usr/local for site-specific overrides thereof, then again possibly one in the user's home directory for user specific settings) is a common and useful pattern. A: The approach you describe is ok. If you want to add support for user config files, you can use execfile(os.path.expanduser("~/.yourprogram/config.py")). A: One nice approach is to parse the config file(s) into a Python object when the application starts and pass this object around to all classes and modules requiring access to the configuration. This may save a lot of time parsing the config. A: If you want to share your config across different machines, you could perhaps put it on a web server and do import like this: import urllib2 confstr = urllib2.urlopen("http://yourhost/config.py").read() exec(confstr) And if you want to share it across different languages, perhaps you can use JSON to encode and parse the configuration: import urllib2 import simplejson confstr = urllib2.urlopen("http://yourhost/config.py").read() config = simplejson.loads(confstr)
python single configuration file
I am developing a project that requires a single configuration file whose data is used by multiple modules. My question is: what is the common approach to that? should i read the configuration file from each of my modules (files) or is there any other way to do it? I was thinking to have a module named config.py that reads the configuration files and whenever I need a config I do import config and then do something like config.data['teamsdir'] get the 'teamsdir' property (for example). response: opted for the conf.py approach then since it it is modular, flexible and simple I can just put the configuration data directly in the file, latter if i want to read from a json file a xml file or multiple sources i just change the conf.py and make sure the data is accessed the same way. accepted answer: chose "Alex Martelli" response because it was the most complete. voted up other answers because they where good and useful too.
[ "I like the approach of a single config.py module whose body (when first imported) parses one or more configuration-data files and sets its own \"global variables\" appropriately -- though I'd favor config.teamdata over the round-about config.data['teamdata'] approach.\nThis assumes configuration settings are read-only once loaded (except maybe in unit-testing scenarios, where the test-code will be doing its own artificial setting of config variables to properly exercise the code-under-test) -- it basically exploits the nature of a module as the simplest Pythonic form of \"singleton\" (when you don't need subclassing or other features supported only by classes and not by modules, of course).\n\"One or more\" configuration files (e.g. first one somewhere in /etc for general default settings, then one under /usr/local for site-specific overrides thereof, then again possibly one in the user's home directory for user specific settings) is a common and useful pattern.\n", "The approach you describe is ok. If you want to add support for user config files, you can use execfile(os.path.expanduser(\"~/.yourprogram/config.py\")).\n", "One nice approach is to parse the config file(s) into a Python object when the application starts and pass this object around to all classes and modules requiring access to the configuration. \nThis may save a lot of time parsing the config.\n", "If you want to share your config across different machines, you could perhaps put it on a web server and do import like this:\nimport urllib2\nconfstr = urllib2.urlopen(\"http://yourhost/config.py\").read()\nexec(confstr)\n\nAnd if you want to share it across different languages, perhaps you can use JSON to encode and parse the configuration:\nimport urllib2\nimport simplejson\nconfstr = urllib2.urlopen(\"http://yourhost/config.py\").read()\nconfig = simplejson.loads(confstr)\n\n" ]
[ 10, 4, 3, 1 ]
[]
[]
[ "configuration_files", "python" ]
stackoverflow_0002348927_configuration_files_python.txt
Q: Passing multiple arguments from IronPython to .NET method I have a class in .NET (C#): public class MyHelper { public object exec( string script, params object[] arguments ) { // execute script with passed arguments in some external enviroment } } I'm using IronPython runtime in my code to run python scripts, which should in some cases call the "exec" method. I would like serve the comfortable way to call the "exec" method. Something like: helper.exec( "someExternalFunction( {0}, {1}, {3} )", var01, var02, var03 ) But I don't know how to declare the "exec" method in C# to achieve this. In python I can use a "*args" argument: def exec( script, *args ): ... do something ... I don't want have separate Python method "exec" from "MyHelper" class, because the "MyHelper" class provides complex functionality "in one place". How should I write the "exec" method declaration in C# to achieve that? Or what other solution should I use? Thanks A: The problem here is that "exec" is a keyword in Python so you can't use that as your function name. You could use "exec_" or execute or something like that instead. Alternately you could write: getattr(helper, 'exec')(...) A: According to this FAQ, the MyHelper.exec you've defined should accept both an array as the second argument, or any number of objects following the first string. If your example call to helper does not invoke as expected, that is probably a limitation of the IronPython interpreter, and probably needs to be filed as a bug. Before filing it as a bug, however, please create a minimal runnable C# script that demonstrates what you're trying to do (show how it works as expected in C#), and an IronPython script that attempts to do the same thing but fails. This will be invaluable toward making the problem work. In the meantime, why not just call helper.exec( "someExternalFunction( {0}, {1}, {3} )", [var01, var02, var03] ) ?
Passing multiple arguments from IronPython to .NET method
I have a class in .NET (C#): public class MyHelper { public object exec( string script, params object[] arguments ) { // execute script with passed arguments in some external enviroment } } I'm using IronPython runtime in my code to run python scripts, which should in some cases call the "exec" method. I would like serve the comfortable way to call the "exec" method. Something like: helper.exec( "someExternalFunction( {0}, {1}, {3} )", var01, var02, var03 ) But I don't know how to declare the "exec" method in C# to achieve this. In python I can use a "*args" argument: def exec( script, *args ): ... do something ... I don't want have separate Python method "exec" from "MyHelper" class, because the "MyHelper" class provides complex functionality "in one place". How should I write the "exec" method declaration in C# to achieve that? Or what other solution should I use? Thanks
[ "The problem here is that \"exec\" is a keyword in Python so you can't use that as your function name. You could use \"exec_\" or execute or something like that instead. Alternately you could write:\ngetattr(helper, 'exec')(...)\n", "According to this FAQ, the MyHelper.exec you've defined should accept both an array as the second argument, or any number of objects following the first string.\nIf your example call to helper does not invoke as expected, that is probably a limitation of the IronPython interpreter, and probably needs to be filed as a bug. Before filing it as a bug, however, please create a minimal runnable C# script that demonstrates what you're trying to do (show how it works as expected in C#), and an IronPython script that attempts to do the same thing but fails. This will be invaluable toward making the problem work.\nIn the meantime, why not just call\nhelper.exec( \"someExternalFunction( {0}, {1}, {3} )\", [var01, var02, var03] )\n\n?\n" ]
[ 3, 1 ]
[]
[]
[ "c#", "interop", "ironpython", "python" ]
stackoverflow_0002347003_c#_interop_ironpython_python.txt
Q: What can I do if django runserver seems to be caching my urls.py and settings.py? I detected this problem when updating the patterns in URLConf and seeing that the new pattern wasn't matched anywhere. So, with urls.py I don't get anywhere when writing random lines on it, I mean, invalid code, and django doesn't throw any exception and serves the urls just fine. So I checked ROOT_URLCONF in settings.py, and it points to "projectname.urls" so it's reading the right file. I tried deleting urls.py, and the server keeps running and serving just fine. Then I deleted settings.py, just to see if it wasn't being read, and that gave me the expected exception. I deleted all *.pyc too, restarted runserver many times, and even restarted the whole computer. I also tried deleting the db and running syncdb again. I created a new empty project, and it runs just fine. I'm running the latest development version: Django version 1.2 beta 1 SVN-12617, using settings 'cms.settings' I am asking for any kind of help of how to override this behavior, I mean, there must be something that's misconfigured. A: You're not running what you think you're running. Check your PYTHONPATH.
What can I do if django runserver seems to be caching my urls.py and settings.py?
I detected this problem when updating the patterns in URLConf and seeing that the new pattern wasn't matched anywhere. So, with urls.py I don't get anywhere when writing random lines on it, I mean, invalid code, and django doesn't throw any exception and serves the urls just fine. So I checked ROOT_URLCONF in settings.py, and it points to "projectname.urls" so it's reading the right file. I tried deleting urls.py, and the server keeps running and serving just fine. Then I deleted settings.py, just to see if it wasn't being read, and that gave me the expected exception. I deleted all *.pyc too, restarted runserver many times, and even restarted the whole computer. I also tried deleting the db and running syncdb again. I created a new empty project, and it runs just fine. I'm running the latest development version: Django version 1.2 beta 1 SVN-12617, using settings 'cms.settings' I am asking for any kind of help of how to override this behavior, I mean, there must be something that's misconfigured.
[ "You're not running what you think you're running. Check your PYTHONPATH.\n" ]
[ 2 ]
[]
[]
[ "django", "python", "url" ]
stackoverflow_0002349302_django_python_url.txt
Q: Process for converting python program into threaded application? I have a code-base that I'm looking to split up and add to by using threading, however I'm relatively new on how to handle it. Please before reading further respect my wish of NOT just re-writing this code and tossing it back at me with the problem solved. I would much rather work the problem out by someone pointing me in the right direction, than someone solving it FOR me; I don't learn well that way. The fully functioning code-base is here -- It requires the mechanize and beautifulsoup libraries which can be installed via easy_install. I've separated out all of my functions, and tried to keep the code as clean as possible (I'm sure there are some optimizations in there that I'll get reamed for, but the main problem is how to thread this. My ultimate goal is to pack this into a thread, and then share cookies between other initialized browser objects in order to do other things while my original code is running 'backgrounded'. I've tried thus: class Recon(threading.Thread): def __init__(self): threading.Thread.__init__(self) #Packed the stuff above my original while loop in here, minus functions. def run(self): #Packed my code past the while loop in here. somevar = Recon() somevar.start() Problem I'm having is that, once I run the program it will run the things in init, but afterwards it just sits there and freezes on me. No traceback, no errors, just doesn't do anything, doesn't even return my command prompt back to my control. Could I just get some tips, or a general flow of how to convert this? I got overwhelmed and deleted the code I was trying with so I don't have that example, but do I need to be prepending 'self.' to all of my variables? Do I need to just define my vars as global? Here is a reproduction of what I'm having trouble with after having tried to convert the script to use threading. A: As long as you have a single thread (as in the above snippet, where you instantiate Recon just once), it shouldn't matter much what you do where; but of course I imagine the reason you're introducing threading is to eventually move to having multiple threads active. If that's the case, then the first key issue is to ensure that you never have two or more threads simultaneously trying to use the same shared system/resource -- for example, multiple threads writing at the same time to ReconFile, in the case of the code at the pastebin URL you mention. The classic way to avoid such issues is to use locking, but my favorite way is quite different: make sure any such resource is accessed by only one dedicated thread, and use a Queue.Queue instance (intrinsically threadsafe) to have other threads post work-request to the dedicated thread (so instead of writing to ReconFile directly each other thread would make a list of lines to be written contiguously, then .put the list on the queue where the "recon file writing" worker thread is waiting via .get). When you need to get results back from such actions (not the case here), the requesting thread would place its own personal "queue on which to return results" as part of the "work request packet" it puts to the worker thread's queue. I've presented much more detail about this recommended architecture in the threading chapter of "Python in a Nutshell" 2nd edition (and why, as the book's author, I would of course never recommend you perform an illegal download of a free pirate copy of my book, I can however mention there's plenty of sites offering such pirate copies for download -- the legal way to read my book for free is to sign up for a trial offer to O'Reilly's "safari" online books website). This does not address the specific problem you're observing, since it's happening when you only have one thread around. I notice that thread is trying to perform lots of I/O on standard input and standard output, which is possibly problematic from a thread -- consider doing the input for a thread before you start it (in the main thread) and for needed output use Python's standard logging module, which is guaranteed to be thread-safe. Do you still observe problems then? If that's the case, then the next step is to pepper your code with logging.info calls so that you can pinpoint exactly where it's stalling -- and tell us about that, so we can try to help from there!
Process for converting python program into threaded application?
I have a code-base that I'm looking to split up and add to by using threading, however I'm relatively new on how to handle it. Please before reading further respect my wish of NOT just re-writing this code and tossing it back at me with the problem solved. I would much rather work the problem out by someone pointing me in the right direction, than someone solving it FOR me; I don't learn well that way. The fully functioning code-base is here -- It requires the mechanize and beautifulsoup libraries which can be installed via easy_install. I've separated out all of my functions, and tried to keep the code as clean as possible (I'm sure there are some optimizations in there that I'll get reamed for, but the main problem is how to thread this. My ultimate goal is to pack this into a thread, and then share cookies between other initialized browser objects in order to do other things while my original code is running 'backgrounded'. I've tried thus: class Recon(threading.Thread): def __init__(self): threading.Thread.__init__(self) #Packed the stuff above my original while loop in here, minus functions. def run(self): #Packed my code past the while loop in here. somevar = Recon() somevar.start() Problem I'm having is that, once I run the program it will run the things in init, but afterwards it just sits there and freezes on me. No traceback, no errors, just doesn't do anything, doesn't even return my command prompt back to my control. Could I just get some tips, or a general flow of how to convert this? I got overwhelmed and deleted the code I was trying with so I don't have that example, but do I need to be prepending 'self.' to all of my variables? Do I need to just define my vars as global? Here is a reproduction of what I'm having trouble with after having tried to convert the script to use threading.
[ "As long as you have a single thread (as in the above snippet, where you instantiate Recon just once), it shouldn't matter much what you do where; but of course I imagine the reason you're introducing threading is to eventually move to having multiple threads active.\nIf that's the case, then the first key issue is to ensure that you never have two or more threads simultaneously trying to use the same shared system/resource -- for example, multiple threads writing at the same time to ReconFile, in the case of the code at the pastebin URL you mention.\nThe classic way to avoid such issues is to use locking, but my favorite way is quite different: make sure any such resource is accessed by only one dedicated thread, and use a Queue.Queue instance (intrinsically threadsafe) to have other threads post work-request to the dedicated thread (so instead of writing to ReconFile directly each other thread would make a list of lines to be written contiguously, then .put the list on the queue where the \"recon file writing\" worker thread is waiting via .get).\nWhen you need to get results back from such actions (not the case here), the requesting thread would place its own personal \"queue on which to return results\" as part of the \"work request packet\" it puts to the worker thread's queue. I've presented much more detail about this recommended architecture in the threading chapter of \"Python in a Nutshell\" 2nd edition (and why, as the book's author, I would of course never recommend you perform an illegal download of a free pirate copy of my book, I can however mention there's plenty of sites offering such pirate copies for download -- the legal way to read my book for free is to sign up for a trial offer to O'Reilly's \"safari\" online books website).\nThis does not address the specific problem you're observing, since it's happening when you only have one thread around. I notice that thread is trying to perform lots of I/O on standard input and standard output, which is possibly problematic from a thread -- consider doing the input for a thread before you start it (in the main thread) and for needed output use Python's standard logging module, which is guaranteed to be thread-safe. Do you still observe problems then? If that's the case, then the next step is to pepper your code with logging.info calls so that you can pinpoint exactly where it's stalling -- and tell us about that, so we can try to help from there!\n" ]
[ 3 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0002349876_multithreading_python.txt
Q: How many private variables are too many? Capsulizing classes? Class Practices? Okay so i am currently working on an inhouse statistics package for python, its mainly geared towards a combination of working with arcgis geoprocessor, for modeling comparasion and tools. Anyways, so i have a single class, that calculates statistics. Lets just call it Stats. Now my Stats class, is getting to the point of being very large. It uses statistics calculated by other statistics, to calculate other statistics sets, etc etc. This leads to alot of private variables, that are kept simply to prevent recalculation. however there is certain ones, while used quite frequintly they are often only used by one or two key subsections of functionality. (e.g. summation of matrix diagonals, and probabilities). However its starting to become a major eyeesore, and i feel as if i am doing this terribly wrong. So is this bad? I was recommended by a coworker, to simply start putting core and common functionality togther, in the main class, then simply having capsules, that take a reference to the main class, and simply do what ever functionality they need to within themselves. E.g. for calculating accuracy of model predictions, i would create a capsule, who simply takes a reference to the parent, and it will offload all of the calculations needed, for model predictions. Is something like this really a good idea? Is there a better way? Right now i have over a dozen different sub statistics that are dumped to a text file to make a smallish report. The code base is growing, and i would just love it if i could start splitting up more and more of my python classes. I am just not sure really what the best way about doing stuff like this is. A: I can think of a couple of solutions. One would be to simply store values in an array with an enum like so: StatisticType = enum('AveragePerDay','MedianPerDay'...) Another would be to use a inheritance like so: class StatisticBase .... class AveragePerDay ( StatisticBase ) ... class MedianPerDay ( StatisticBase ) ... There is no hard and fast rule on "too many", however a guideline is that if the list of fields, properties, and methods when collapsed, is longer than a single screen full, it's probably too big. A: Why not create a class for each statistic you need to compute and when of the statistics requires other, just pass an instance of the latter to the computing method? However, there is little known about your code and required functionalities. Maybe you could describe in a broader fashion, what kind of statistics you need calculate and how they depend on each other? Anyway, if I had to count certain statistics, I would instantly turn to creating separate class for each of them. I did once, when I was writing code statistics library for python. Every statistic, like how many times class is inherited or how often function was called, was a separate class. This way each of them was simple, however I didn't need to use any of them in the other. A: It's a common anti-pattern for a class to become "too fat" (have too much functionality and related state), and while this is commonly observed about "base classes" (whence the "fat base class" monicker for the anti-pattern), it can really happen without any inheritance involved. Many design patterns (DPs for short_ can help you re-factor your code to whittle down the large, untestable, unmaintainable "fat class" to a nice package of cooperating classes (which can be used through "Facade" DPs for simplicity): consider, for example, State, Strategy, Memento, Proxy. You could attack this problem directly, but I think, especially since you mention in a comment that you're looking at it as a general class design topic, it may offer you a good opportunity to dig into the very useful field of design patterns, and especially "refactoring to patterns" (Fowler's book by that title is excellent, though it doesn't touch on Python-specific issues). Specifically, I believe you'll be focusing mostly on a few Structural and Behavioral patterns (since I don't think you have much need for Creational ones for this use case, except maybe "lazy initialization" of some of your expensive-to-compute state that's only needed in certain cases -- see this wikipedia entry for a pretty exhaustive listing of DPs, with classification and links for further explanations of each). A: Since you are asking about best practices you might want to check out pylint (http://www.logilab.org/857). It has many good suggestions about code style including ones relating to how many private variables in a class.
How many private variables are too many? Capsulizing classes? Class Practices?
Okay so i am currently working on an inhouse statistics package for python, its mainly geared towards a combination of working with arcgis geoprocessor, for modeling comparasion and tools. Anyways, so i have a single class, that calculates statistics. Lets just call it Stats. Now my Stats class, is getting to the point of being very large. It uses statistics calculated by other statistics, to calculate other statistics sets, etc etc. This leads to alot of private variables, that are kept simply to prevent recalculation. however there is certain ones, while used quite frequintly they are often only used by one or two key subsections of functionality. (e.g. summation of matrix diagonals, and probabilities). However its starting to become a major eyeesore, and i feel as if i am doing this terribly wrong. So is this bad? I was recommended by a coworker, to simply start putting core and common functionality togther, in the main class, then simply having capsules, that take a reference to the main class, and simply do what ever functionality they need to within themselves. E.g. for calculating accuracy of model predictions, i would create a capsule, who simply takes a reference to the parent, and it will offload all of the calculations needed, for model predictions. Is something like this really a good idea? Is there a better way? Right now i have over a dozen different sub statistics that are dumped to a text file to make a smallish report. The code base is growing, and i would just love it if i could start splitting up more and more of my python classes. I am just not sure really what the best way about doing stuff like this is.
[ "I can think of a couple of solutions. One would be to simply store values in an array with an enum like so:\nStatisticType = enum('AveragePerDay','MedianPerDay'...)\n\nAnother would be to use a inheritance like so:\nclass StatisticBase\n....\nclass AveragePerDay ( StatisticBase )\n...\nclass MedianPerDay ( StatisticBase )\n... \n\nThere is no hard and fast rule on \"too many\", however a guideline is that if the list of fields, properties, and methods when collapsed, is longer than a single screen full, it's probably too big.\n", "Why not create a class for each statistic you need to compute and when of the statistics requires other, just pass an instance of the latter to the computing method? However, there is little known about your code and required functionalities. Maybe you could describe in a broader fashion, what kind of statistics you need calculate and how they depend on each other?\nAnyway, if I had to count certain statistics, I would instantly turn to creating separate class for each of them. I did once, when I was writing code statistics library for python. Every statistic, like how many times class is inherited or how often function was called, was a separate class. This way each of them was simple, however I didn't need to use any of them in the other.\n", "It's a common anti-pattern for a class to become \"too fat\" (have too much functionality and related state), and while this is commonly observed about \"base classes\" (whence the \"fat base class\" monicker for the anti-pattern), it can really happen without any inheritance involved.\nMany design patterns (DPs for short_ can help you re-factor your code to whittle down the large, untestable, unmaintainable \"fat class\" to a nice package of cooperating classes (which can be used through \"Facade\" DPs for simplicity): consider, for example, State, Strategy, Memento, Proxy.\nYou could attack this problem directly, but I think, especially since you mention in a comment that you're looking at it as a general class design topic, it may offer you a good opportunity to dig into the very useful field of design patterns, and especially \"refactoring to patterns\" (Fowler's book by that title is excellent, though it doesn't touch on Python-specific issues).\nSpecifically, I believe you'll be focusing mostly on a few Structural and Behavioral patterns (since I don't think you have much need for Creational ones for this use case, except maybe \"lazy initialization\" of some of your expensive-to-compute state that's only needed in certain cases -- see this wikipedia entry for a pretty exhaustive listing of DPs, with classification and links for further explanations of each).\n", "Since you are asking about best practices you might want to check out pylint (http://www.logilab.org/857). It has many good suggestions about code style including ones relating to how many private variables in a class.\n" ]
[ 1, 1, 0, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0002349529_class_python.txt
Q: Why am I getting an AttributeError when I have the attribute? I keep getting the following error: AttributeError: Caribou instance has no attribute 'on_key_up' The problem is, I'm pretty sure I do have that attribute... Here are some excerpts from my code (from caribou.py): def on_key_up(self, event): if event.event_string == "Shift_R": _r_shift_down = False elif event.event_string == "Shift_L": _l_shift_down = False And this is the line that is causing the error: pyatspi.Registry.registerKeystrokeListener(caribou.on_key_up, mask=None, kind=(pyatspi.KEY_RELEASED_EVENT,)) Anybody see what I'm doing wrong? Thanks! edit: Whoops--here's how I create the caribou instance: caribou = Caribou() A: The OP mentions in a comment that dir(caribou) gives him: ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__'] so it definitely looks at that point that caribou is a module -- nothing else would normally have __builtins__ etc. The error message however clearly mentions a Caribou instance -- so I imagine that something else must be happening between that dir call and the following attempt to access caribou.on_key_up. Clearly the OP is having some multiple use of that beloved caribou identifier (at some point it's bound to a Caribou instance, but at other times it's clearly a module, and indeed the OP does mention a caribou.py which is clearly going to become a module named caribou when imported). So my recommendation is to clarify naming. For example, use caribou_instance = Caribou() instead of binding one more value to the caribou name, and replace all uses of caribou which are supposed to be the instance (not the module) with caribou_instance. That may give you a different error, which could be more informative. A: What happens if you print dir(caribou)? Do you see your method? A: You aren't showing your import statements or how "caribou" the instance is being created. My guess is you are trying to pass caribou.on_key_up as in caribou the module, not the instance.
Why am I getting an AttributeError when I have the attribute?
I keep getting the following error: AttributeError: Caribou instance has no attribute 'on_key_up' The problem is, I'm pretty sure I do have that attribute... Here are some excerpts from my code (from caribou.py): def on_key_up(self, event): if event.event_string == "Shift_R": _r_shift_down = False elif event.event_string == "Shift_L": _l_shift_down = False And this is the line that is causing the error: pyatspi.Registry.registerKeystrokeListener(caribou.on_key_up, mask=None, kind=(pyatspi.KEY_RELEASED_EVENT,)) Anybody see what I'm doing wrong? Thanks! edit: Whoops--here's how I create the caribou instance: caribou = Caribou()
[ "The OP mentions in a comment that dir(caribou) gives him:\n['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']\n\nso it definitely looks at that point that caribou is a module -- nothing else would normally have __builtins__ etc. The error message however clearly mentions a Caribou instance -- so I imagine that something else must be happening between that dir call and the following attempt to access caribou.on_key_up.\nClearly the OP is having some multiple use of that beloved caribou identifier (at some point it's bound to a Caribou instance, but at other times it's clearly a module, and indeed the OP does mention a caribou.py which is clearly going to become a module named caribou when imported).\nSo my recommendation is to clarify naming. For example, use\ncaribou_instance = Caribou()\n\ninstead of binding one more value to the caribou name, and replace all uses of caribou which are supposed to be the instance (not the module) with caribou_instance. That may give you a different error, which could be more informative.\n", "What happens if you print dir(caribou)? Do you see your method?\n", "You aren't showing your import statements or how \"caribou\" the instance is being created. My guess is you are trying to pass caribou.on_key_up as in caribou the module, not the instance.\n" ]
[ 4, 2, 1 ]
[]
[]
[ "attributeerror", "python" ]
stackoverflow_0002349365_attributeerror_python.txt
Q: Emacs: Set/Reset python debug breakpoint I use python debugger pdb. I use emacs for python programming. I use python-mode.el. My idea is to make emacs intuitive. So I need the following help for python programs (.py) Whenever I press 'F9' key, the emacs should put "import pdb; pdb.set_trace();" statements in the current line and move the current line to one line below. Sentence to be in same line. smart indentation may help very much. Wherever "import pdb; pdb.set_trace();" statement presents in the python code, emacs should display left indicator and highlight that line. When I press 'Alt-F9' keys at the current line and emacs found the "import pdb; pdb.set_trace();" statement then, emacs should remove the "import pdb; pdb.set_trace();" line and move the current line to one up. Whenever I press "F8" key, emacs to jump to "import pdb; pdb.set_trace();" in the same buffer. I am trying to learn elisp and catch up lisp soon to customize emacs myself. I will appreciate your answers. The answer shall be great enough for me and others who find this solution is very useful. A: to do 1) (defun add-py-debug () "add debug code and move line down" (interactive) (move-beginning-of-line 1) (insert "import pdb; pdb.set_trace();\n")) (local-set-key (kbd "<f9>") 'add-py-debug) to do 2) you probably have to change the syntax highlighting of the python mode, or write you own minor mode. You'd have to look into font-lock to get more. Sorry. to do 3) though I've set this to be C-c F9 instead of Alt-F9 (defun remove-py-debug () "remove py debug code, if found" (interactive) (let ((x (line-number-at-pos)) (cur (point))) (search-forward-regexp "^[ ]*import pdb; pdb.set_trace();") (if (= x (line-number-at-pos)) (let () (move-beginning-of-line 1) (kill-line 1) (move-beginning-of-line 1)) (goto-char cur)))) (local-set-key (kbd "C c <f9>") 'remove-py-debug) and to do 4) (local-set-key (kbd "<f3>") '(lambda () (interactive) (search-forward-regexp "^[ ]*import pdb; pdb.set_trace();") (move-beginning-of-line 1))) Note, this is not the best elisp code in the world, but I've tried to make it clear to you what's going on rather than make it totally idiomatic. The GNU Elsip book is a great place to start if you want to do more with elisp. HTH A: I've found that Xah's Elisp Tutorial is an excellent starting point in figuring out the basics of Emacs Lisp programming. There are also some SteveY articles from a while ago that go through techniques you might find useful for learning the basics. If you're serious about making an amended Python mode, you'll do well to take a look at Writing GNU Emacs Extensions, which is available as a PDF. Finally, the most useful resource for me is actually Emacs itself. I make frequent use of M-x apropos and M-x describe-key to figure out how built-in functions work, and whether there's something already in place to do what I want. The specific things you want to look like they can be done through some simple use of insert, and a few search/replace functions, so that'll be a good starting point.
Emacs: Set/Reset python debug breakpoint
I use python debugger pdb. I use emacs for python programming. I use python-mode.el. My idea is to make emacs intuitive. So I need the following help for python programs (.py) Whenever I press 'F9' key, the emacs should put "import pdb; pdb.set_trace();" statements in the current line and move the current line to one line below. Sentence to be in same line. smart indentation may help very much. Wherever "import pdb; pdb.set_trace();" statement presents in the python code, emacs should display left indicator and highlight that line. When I press 'Alt-F9' keys at the current line and emacs found the "import pdb; pdb.set_trace();" statement then, emacs should remove the "import pdb; pdb.set_trace();" line and move the current line to one up. Whenever I press "F8" key, emacs to jump to "import pdb; pdb.set_trace();" in the same buffer. I am trying to learn elisp and catch up lisp soon to customize emacs myself. I will appreciate your answers. The answer shall be great enough for me and others who find this solution is very useful.
[ "to do 1) \n(defun add-py-debug () \n \"add debug code and move line down\" \n (interactive) \n (move-beginning-of-line 1) \n (insert \"import pdb; pdb.set_trace();\\n\")) \n\n(local-set-key (kbd \"<f9>\") 'add-py-debug)\n\nto do 2) you probably have to change the syntax highlighting of the python mode, or write you own minor mode. You'd have to look into font-lock to get more. Sorry.\nto do 3) though I've set this to be C-c F9 instead of Alt-F9\n(defun remove-py-debug () \n \"remove py debug code, if found\" \n (interactive) \n (let ((x (line-number-at-pos)) \n (cur (point))) \n (search-forward-regexp \"^[ ]*import pdb; pdb.set_trace();\") \n (if (= x (line-number-at-pos)) \n (let () \n (move-beginning-of-line 1) \n (kill-line 1) \n (move-beginning-of-line 1)) \n (goto-char cur)))) \n\n(local-set-key (kbd \"C c <f9>\") 'remove-py-debug)\n\nand to do 4)\n(local-set-key (kbd \"<f3>\") '(lambda () \n (interactive) \n (search-forward-regexp \"^[ ]*import pdb; pdb.set_trace();\") \n (move-beginning-of-line 1)))\n\nNote, this is not the best elisp code in the world, but I've tried to make it clear to you what's going on rather than make it totally idiomatic. The GNU Elsip book is a great place to start if you want to do more with elisp.\nHTH\n", "I've found that Xah's Elisp Tutorial is an excellent starting point in figuring out the basics of Emacs Lisp programming. There are also some SteveY articles from a while ago that go through techniques you might find useful for learning the basics.\nIf you're serious about making an amended Python mode, you'll do well to take a look at Writing GNU Emacs Extensions, which is available as a PDF.\nFinally, the most useful resource for me is actually Emacs itself. I make frequent use of M-x apropos and M-x describe-key to figure out how built-in functions work, and whether there's something already in place to do what I want.\nThe specific things you want to look like they can be done through some simple use of insert, and a few search/replace functions, so that'll be a good starting point.\n" ]
[ 8, 0 ]
[]
[]
[ "customization", "debugging", "elisp", "emacs", "python" ]
stackoverflow_0002332164_customization_debugging_elisp_emacs_python.txt
Q: python csv header error Trying to read headers for a csv file with: reader = csv.DictReader(open(PATH_FILE),skipinitialspace=True) headers = reader.fieldnames for header in sorted(set(headers)): It worked on development server, throws this error on production 'NoneType' object is not iterable Debug shows headers has None value while the csv file has headers in it. headers:None A: From csvreader.fieldnames documentation: If not passed as a parameter when creating the object, this attribute is initialized upon first access or when the first record is read from the file. So try reading the first row from the file, then reader.fieldnames should contain the data you need. Maybe something like adding reader.next(): reader = csv.DictReader(open(PATH_FILE),skipinitialspace=True) reader.next() headers = reader.fieldnames The documentation also says: Changed in version 2.6. So this difference in behaviour could be due to a difference in Python version between your two systems. A: Maybe you're using different Python versions in your development server vs production? In Python 2.5, the fieldnames attribute of a DictReader instance is None until the instance has been used to fetch at least one row.
python csv header error
Trying to read headers for a csv file with: reader = csv.DictReader(open(PATH_FILE),skipinitialspace=True) headers = reader.fieldnames for header in sorted(set(headers)): It worked on development server, throws this error on production 'NoneType' object is not iterable Debug shows headers has None value while the csv file has headers in it. headers:None
[ "From csvreader.fieldnames documentation:\n\nIf not passed as a parameter when creating the object, this attribute is initialized upon first access or when the first record is read from the file.\n\nSo try reading the first row from the file, then reader.fieldnames should contain the data you need. Maybe something like adding reader.next():\nreader = csv.DictReader(open(PATH_FILE),skipinitialspace=True)\nreader.next()\nheaders = reader.fieldnames\n\nThe documentation also says:\n\nChanged in version 2.6.\n\nSo this difference in behaviour could be due to a difference in Python version between your two systems.\n", "Maybe you're using different Python versions in your development server vs production? In Python 2.5, the fieldnames attribute of a DictReader instance is None until the instance has been used to fetch at least one row.\n" ]
[ 2, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0002350018_csv_python.txt
Q: Python: does the set class "leak" when items are removed, like a dict? I know that Python dicts will "leak" when items are removed (because the item's slot will be overwritten with the magic "removed" value)… But will the set class behave the same way? Is it safe to keep a set around, adding and removing stuff from it over time? Edit: Alright, I've tried it out, and here's what I found: >>> import gc >>> gc.collect() 0 >>> nums = range(1000000) >>> gc.collect() 0 ### rsize: 20 megs ### A baseline measurement >>> s = set(nums) >>> gc.collect() 0 ### rsize: 36 megs >>> for n in nums: s.remove(n) >>> gc.collect() 0 ### rsize: 36 megs ### Memory usage doesn't drop after removing every item from the set… >>> s = None >>> gc.collect() 0 ### rsize: 20 megs ### … but nulling the reference to the set *does* free the memory. >>> s = set(nums) >>> for n in nums: s.remove(n) >>> for n in nums: s.add(n) >>> gc.collect() 0 ### rsize: 36 megs ### Removing then re-adding keys uses a constant amount of memory… >>> for n in nums: s.remove(n) >>> for n in nums: s.add(n+1000000) >>> gc.collect() 0 ### rsize: 47 megs ### … but adding new keys uses more memory. A: Yes, set is basically a hash table just like dict -- the differences at the interface don't imply many differences "below" it. Once in a while, you should copy the set -- myset = set(myset) -- just like you should for a dict on which many additions and removals are regularly made over time.
Python: does the set class "leak" when items are removed, like a dict?
I know that Python dicts will "leak" when items are removed (because the item's slot will be overwritten with the magic "removed" value)… But will the set class behave the same way? Is it safe to keep a set around, adding and removing stuff from it over time? Edit: Alright, I've tried it out, and here's what I found: >>> import gc >>> gc.collect() 0 >>> nums = range(1000000) >>> gc.collect() 0 ### rsize: 20 megs ### A baseline measurement >>> s = set(nums) >>> gc.collect() 0 ### rsize: 36 megs >>> for n in nums: s.remove(n) >>> gc.collect() 0 ### rsize: 36 megs ### Memory usage doesn't drop after removing every item from the set… >>> s = None >>> gc.collect() 0 ### rsize: 20 megs ### … but nulling the reference to the set *does* free the memory. >>> s = set(nums) >>> for n in nums: s.remove(n) >>> for n in nums: s.add(n) >>> gc.collect() 0 ### rsize: 36 megs ### Removing then re-adding keys uses a constant amount of memory… >>> for n in nums: s.remove(n) >>> for n in nums: s.add(n+1000000) >>> gc.collect() 0 ### rsize: 47 megs ### … but adding new keys uses more memory.
[ "Yes, set is basically a hash table just like dict -- the differences at the interface don't imply many differences \"below\" it. Once in a while, you should copy the set -- myset = set(myset) -- just like you should for a dict on which many additions and removals are regularly made over time.\n" ]
[ 7 ]
[ "For questions like these it is often best to run a quick experiment like this one and see what happens:\ns = set()\nfor a in range(1000):\n for b in range(10000000):\n s.add(b)\n for b in range(10000000):\n s.remove(b)\n\nWhat docs and people say and what behaviour actually is are often at odds. If this is important for you, test it. Don't rely on others.\n" ]
[ -1 ]
[ "dictionary", "python", "set" ]
stackoverflow_0002350050_dictionary_python_set.txt
Q: How do I print a line following a line containing certain text in a saved file in Python? I have written a Python program to find the carrier of a cell phone given the number. It downloads the source of http://www.whitepages.com/carrier_lookup?carrier=other&number_0=1112223333&response=1 (where 1112223333 is the phone number to lookup) and saves this as carrier.html. In the source, the carrier is in the line after the [div class="carrier_result"] tag. (switch in < and > for [ and ], as stackoverflow thought I was trying to format using the html and would not display it.) My program currently searches the file and finds the line containing the div tag, but now I need a way to store the next line after that as a string. My current code is: http://pastebin.com/MSDN0vbC A: What you really want to be doing is parsing the HTML properly. Use the BeautifulSoup library - it's wonderful at doing so. Sample code: import urllib2, BeautifulSoup opener = urllib2.build_opener() opener.addheaders[0] = ('User-agent', 'Mozilla/5.1') response = opener.open('http://www.whitepages.com/carrier_lookup?carrier=other&number_0=1112223333&response=1').read() bs = BeautifulSoup.BeautifulSoup(response) print bs.findAll('div', attrs={'class': 'carrier_result'})[0].next.strip() A: You should be using a HTML parser such as BeautifulSoup or lxml instead. A: to get the next line, you can use htmlsource = open('carrier.html', 'r') for line in htmlsource: if '<div class="carrier_result">' in line: nextline = htmlsource.next() print nextline A "better" way is to split on </div>, then get the things you want, as sometimes the stuff you want can occur all in one line. So using next() if give wrong result.eg data=open("carrier.html").read().split("</div>") for item in data: if '<div class="carrier_result">' in item: print item.split('<div class="carrier_result">')[-1].strip() by the way, if its possible, try to use Python's own web module, like urllib, urllib2 instead of calling external wget.
How do I print a line following a line containing certain text in a saved file in Python?
I have written a Python program to find the carrier of a cell phone given the number. It downloads the source of http://www.whitepages.com/carrier_lookup?carrier=other&number_0=1112223333&response=1 (where 1112223333 is the phone number to lookup) and saves this as carrier.html. In the source, the carrier is in the line after the [div class="carrier_result"] tag. (switch in < and > for [ and ], as stackoverflow thought I was trying to format using the html and would not display it.) My program currently searches the file and finds the line containing the div tag, but now I need a way to store the next line after that as a string. My current code is: http://pastebin.com/MSDN0vbC
[ "What you really want to be doing is parsing the HTML properly. Use the BeautifulSoup library - it's wonderful at doing so.\nSample code:\nimport urllib2, BeautifulSoup\n\nopener = urllib2.build_opener()\nopener.addheaders[0] = ('User-agent', 'Mozilla/5.1')\n\nresponse = opener.open('http://www.whitepages.com/carrier_lookup?carrier=other&number_0=1112223333&response=1').read()\n\nbs = BeautifulSoup.BeautifulSoup(response)\nprint bs.findAll('div', attrs={'class': 'carrier_result'})[0].next.strip()\n\n", "You should be using a HTML parser such as BeautifulSoup or lxml instead.\n", "to get the next line, you can use \nhtmlsource = open('carrier.html', 'r')\nfor line in htmlsource:\n if '<div class=\"carrier_result\">' in line:\n nextline = htmlsource.next()\n print nextline\n\nA \"better\" way is to split on </div>, then get the things you want, as sometimes the stuff you want can occur all in one line. So using next() if give wrong result.eg\ndata=open(\"carrier.html\").read().split(\"</div>\")\nfor item in data:\n if '<div class=\"carrier_result\">' in item:\n print item.split('<div class=\"carrier_result\">')[-1].strip()\n\nby the way, if its possible, try to use Python's own web module, like urllib, urllib2 instead of calling external wget.\n" ]
[ 4, 2, 2 ]
[]
[]
[ "html", "parsing", "python", "string" ]
stackoverflow_0002350190_html_parsing_python_string.txt
Q: Callback, observers, and asynch sockets in Python I'm still a neophyte Python programmer and I'm trying to do something that is a bit over my head. What I've done is create a simple IRC bot using asyncore (and asynchronous sockets module). The client runs in a continuous loop, listening to the conversation in the channel. What I would like to do (I think?) is implement an observer pattern so I can respond to events. I imagine it would look somthing like this: class MyBot(object): def __init__(self): bot = MyIRCClient(server='whatever', channel='#whatever') bot.observe(event='join', handler='log_join') bot.connect() # Bot is now listening continously in a loop def log_join(self, e): print e + ' joined the channel.' I'm basing this design around what I know of observers used in the various Javascript frameworks. I don't know if the same technique can or should be applied here. Any suggestions? A: While Observer is not a particularly popular DP (design pattern) in Python, it's not a totally "alien" one either, so if you're familiar with it, go right ahead. However, the normal way to call observe would be with handler=self.log_join, a callback that's actually a callable, not with a string value forcing the bot to perform introspection to find out what it actually has to call when the event occurs (and not even giving it a self to refer to the object it's supposed to perform introspection on -- shudder!). Callback is a perfectly reasonable and popular DP in Python, but that's because passing around first-class callables (functions, bound methods, classes, instances of classes with a __call__ method, etc, etc) is so wonderfully easy (pretty trivial, actually;-).
Callback, observers, and asynch sockets in Python
I'm still a neophyte Python programmer and I'm trying to do something that is a bit over my head. What I've done is create a simple IRC bot using asyncore (and asynchronous sockets module). The client runs in a continuous loop, listening to the conversation in the channel. What I would like to do (I think?) is implement an observer pattern so I can respond to events. I imagine it would look somthing like this: class MyBot(object): def __init__(self): bot = MyIRCClient(server='whatever', channel='#whatever') bot.observe(event='join', handler='log_join') bot.connect() # Bot is now listening continously in a loop def log_join(self, e): print e + ' joined the channel.' I'm basing this design around what I know of observers used in the various Javascript frameworks. I don't know if the same technique can or should be applied here. Any suggestions?
[ "While Observer is not a particularly popular DP (design pattern) in Python, it's not a totally \"alien\" one either, so if you're familiar with it, go right ahead. However, the normal way to call observe would be with handler=self.log_join, a callback that's actually a callable, not with a string value forcing the bot to perform introspection to find out what it actually has to call when the event occurs (and not even giving it a self to refer to the object it's supposed to perform introspection on -- shudder!).\nCallback is a perfectly reasonable and popular DP in Python, but that's because passing around first-class callables (functions, bound methods, classes, instances of classes with a __call__ method, etc, etc) is so wonderfully easy (pretty trivial, actually;-).\n" ]
[ 2 ]
[]
[]
[ "design_patterns", "network_programming", "python", "sockets" ]
stackoverflow_0002350249_design_patterns_network_programming_python_sockets.txt
Q: Python Eval executing environment I do not understand what environment a eval or exec statement executes in. You can pass both global and local scopes to them but I don't quite understand what this means. Does python create an anonymous module for them, and if that is the case how do the global and local scope differ? Does it run it like it was an anonymous function? If that was the case the global and local scopes would make more sense to me, although would you still need to call global var to prevent python from making a local variable on assignment? And here is some code to show what I am actually trying to do. # module level vars result = '' allowed_builtins = {"__builtins__":{'int':int, 'str':str, 'range':range, 'dir':dir, 'zip':zip }, "result":result} In class def _exec(self, answer, function_name, input): global result exec_string = answer + '\n' exec_string += 'global result; result = %s(%s)' % (function_name, input) exec exec_string in allowed_builtins, {} return result I would like the var result in my scope to be able to be set from within the eval/exec's scope. A: The "local" dictionary is where all names are being set during an exec or eval; the "global" one is used for lookup of names not found in the "local" one, but names aren't set there unless you're execing code that includes a global statement. No module object is created intrinsically by either eval or exec, nor is any function object, anonymous or otherwise (again, of course: unless you exec statements such as def, etc). Edit: for example, given the OP's code, and assuming _exec is a free-standing function since the OP's giving no class where it could live, add at the end: print 'one: %r' % _exec(None, '"foo"', 'range', 7) print 'two: %r' % allowed_builtins['result'] and you'll see this output: one: '' two: [0, 1, 2, 3, 4, 5, 6] the result in the __dict__ of the current module is of course not affected (how could it conceivably be, since that dict is never passed to the exec in question?!) -- the allowed_builtins dictionary is of course the one affected, since it's the dict passed as the "global dictionary" and there is a global statement in the string being executed!
Python Eval executing environment
I do not understand what environment a eval or exec statement executes in. You can pass both global and local scopes to them but I don't quite understand what this means. Does python create an anonymous module for them, and if that is the case how do the global and local scope differ? Does it run it like it was an anonymous function? If that was the case the global and local scopes would make more sense to me, although would you still need to call global var to prevent python from making a local variable on assignment? And here is some code to show what I am actually trying to do. # module level vars result = '' allowed_builtins = {"__builtins__":{'int':int, 'str':str, 'range':range, 'dir':dir, 'zip':zip }, "result":result} In class def _exec(self, answer, function_name, input): global result exec_string = answer + '\n' exec_string += 'global result; result = %s(%s)' % (function_name, input) exec exec_string in allowed_builtins, {} return result I would like the var result in my scope to be able to be set from within the eval/exec's scope.
[ "The \"local\" dictionary is where all names are being set during an exec or eval; the \"global\" one is used for lookup of names not found in the \"local\" one, but names aren't set there unless you're execing code that includes a global statement.\nNo module object is created intrinsically by either eval or exec, nor is any function object, anonymous or otherwise (again, of course: unless you exec statements such as def, etc).\nEdit: for example, given the OP's code, and assuming _exec is a free-standing function since the OP's giving no class where it could live, add at the end:\nprint 'one: %r' % _exec(None, '\"foo\"', 'range', 7)\nprint 'two: %r' % allowed_builtins['result']\n\nand you'll see this output:\none: ''\ntwo: [0, 1, 2, 3, 4, 5, 6]\n\nthe result in the __dict__ of the current module is of course not affected (how could it conceivably be, since that dict is never passed to the exec in question?!) -- the allowed_builtins dictionary is of course the one affected, since it's the dict passed as the \"global dictionary\" and there is a global statement in the string being executed!\n" ]
[ 2 ]
[]
[]
[ "eval", "exec", "python" ]
stackoverflow_0002350390_eval_exec_python.txt
Q: Parsing XML in Python using Expat Background: I'm coming from C#-land, so I'm looking for something like being able to handle nodes and values by selecting via Xpath. Here's my code, so far: import urllib import sys from xml.parsers import expat url = 'http://SomeWebService.SomeDomain.com' u = urllib.urlopen(url) Parser = expat.ParserCreate() data = u.read() try: Parser.Parse(data) except: print "ERROR: Can't parse the XML" sys.exit(0) What standard lib should I be using to deal with DOM elements as objects along with their attributes as one could in C#? I'm looking for something like NodeList nodes = Parser.SelectNodes("Xpath") A: I think you would have more luck if you tried using one of the xml.dom packages, or xml.etree.ElementTree. ElementTree has some limited xpath support, so if that's what you're used to, it might be the best choice.
Parsing XML in Python using Expat
Background: I'm coming from C#-land, so I'm looking for something like being able to handle nodes and values by selecting via Xpath. Here's my code, so far: import urllib import sys from xml.parsers import expat url = 'http://SomeWebService.SomeDomain.com' u = urllib.urlopen(url) Parser = expat.ParserCreate() data = u.read() try: Parser.Parse(data) except: print "ERROR: Can't parse the XML" sys.exit(0) What standard lib should I be using to deal with DOM elements as objects along with their attributes as one could in C#? I'm looking for something like NodeList nodes = Parser.SelectNodes("Xpath")
[ "I think you would have more luck if you tried using one of the xml.dom packages, or xml.etree.ElementTree. ElementTree has some limited xpath support, so if that's what you're used to, it might be the best choice.\n" ]
[ 1 ]
[]
[]
[ "expat_parser", "python", "xml", "xmlnode", "xpath" ]
stackoverflow_0002350494_expat_parser_python_xml_xmlnode_xpath.txt
Q: GraphicsPath doesn't always refresh itself The simple curve in this application only appears when it's dragged off the screen, or the window is resized. When the application just starts up it doesn't appear, and when the window is maximized or minimized it also disappears. However, all of these times, "Path Drawn" is printed, so all of the painting functions are called. Is there something I'm doing wrong with regards to creating and drawing on the graphicscontext? If not, how can I make the window totally refresh in these special cases? import wx class Path(object): def paint(self,gc): print "Path Drawn" gc.SetPen(wx.Pen("#000000",1)) path=gc.CreatePath() path.MoveToPoint(wx.Point2D(10,10)) path.AddCurveToPoint(wx.Point2D(10,50), wx.Point2D(10,150), wx.Point2D(100,100)) gc.DrawPath(path) class TestPane(wx.Panel): def __init__(self,parent=None,id=-1): wx.Panel.__init__(self,parent,id,style=wx.TAB_TRAVERSAL) self.SetBackgroundColour("#FFFFFF") self.Bind(wx.EVT_PAINT,self.onPaint) self.SetDoubleBuffered(True) self.path=Path() def onPaint(self, event): event.Skip() dc=wx.PaintDC(self) dc.BeginDrawing() gc = wx.GraphicsContext.Create(dc) gc.PushState() self.path.paint(gc) gc.PopState() dc.EndDrawing() def drawTestRects(self,dc): dc.SetBrush(wx.Brush("#000000",style=wx.SOLID)) dc.DrawRectangle(50,50,50,50) dc.DrawRectangle(100,100,100,100) class TestFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(640,480)) self.mainPanel=TestPane(self,-1) self.Show(True) app = wx.App(False) frame = TestFrame(None,"Test App") app.MainLoop() A: Comment out the self.SetDoubleBuffered(True) part and it will work, because due to bug http://trac.wxwidgets.org/ticket/11138 window isn't refreshed correctly if SetDoubleBuffered and GraphicsContext are used together. If you MUST need double buffering implement it yourselves e.g. first draw to a MeomryDC and then blit or paint bitmap to paint dc.
GraphicsPath doesn't always refresh itself
The simple curve in this application only appears when it's dragged off the screen, or the window is resized. When the application just starts up it doesn't appear, and when the window is maximized or minimized it also disappears. However, all of these times, "Path Drawn" is printed, so all of the painting functions are called. Is there something I'm doing wrong with regards to creating and drawing on the graphicscontext? If not, how can I make the window totally refresh in these special cases? import wx class Path(object): def paint(self,gc): print "Path Drawn" gc.SetPen(wx.Pen("#000000",1)) path=gc.CreatePath() path.MoveToPoint(wx.Point2D(10,10)) path.AddCurveToPoint(wx.Point2D(10,50), wx.Point2D(10,150), wx.Point2D(100,100)) gc.DrawPath(path) class TestPane(wx.Panel): def __init__(self,parent=None,id=-1): wx.Panel.__init__(self,parent,id,style=wx.TAB_TRAVERSAL) self.SetBackgroundColour("#FFFFFF") self.Bind(wx.EVT_PAINT,self.onPaint) self.SetDoubleBuffered(True) self.path=Path() def onPaint(self, event): event.Skip() dc=wx.PaintDC(self) dc.BeginDrawing() gc = wx.GraphicsContext.Create(dc) gc.PushState() self.path.paint(gc) gc.PopState() dc.EndDrawing() def drawTestRects(self,dc): dc.SetBrush(wx.Brush("#000000",style=wx.SOLID)) dc.DrawRectangle(50,50,50,50) dc.DrawRectangle(100,100,100,100) class TestFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(640,480)) self.mainPanel=TestPane(self,-1) self.Show(True) app = wx.App(False) frame = TestFrame(None,"Test App") app.MainLoop()
[ "Comment out the self.SetDoubleBuffered(True) part and it will work, because due to bug http://trac.wxwidgets.org/ticket/11138 window isn't refreshed correctly if SetDoubleBuffered and GraphicsContext are used together.\nIf you MUST need double buffering implement it yourselves e.g. first draw to a MeomryDC and then blit or paint bitmap to paint dc.\n" ]
[ 2 ]
[]
[]
[ "graphicscontext", "graphicspath", "python", "wxpython" ]
stackoverflow_0002348183_graphicscontext_graphicspath_python_wxpython.txt
Q: memory location of dictionary in python 2.6.4 only? Is it possible to see a memory location/address of data dictionary in python 2.6.4 only?? A: In CPython use id function.
memory location of dictionary in python 2.6.4 only?
Is it possible to see a memory location/address of data dictionary in python 2.6.4 only??
[ "In CPython use id function.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0002350719_python.txt
Q: literal usage of % in batch I have a batch file containing a python script using the Output template> %(NAME)s when I ran it, cmd thinks its a var and igoners the % so youtube-dl.py -b -o %(uploader)s-%(title)s-%(id)s.%(ext)s turns into youtube-dl.py -b -o (uploader)s-(title)s-(id)s.(ext)s how do i convince cmd to not process it and pass it as is to python? A: Replace the % with %%: youtube-dl.py -b -o %%(uploader)s-%%(title)s-%%(id)s.%%(ext)s (Note that, unlike on Unix, double quotes don't do a lot on Windows command lines.) A: If you don't want your % characters interpreted by cmd.exe, you should prefix them with the escape character: c:\> set qwert=55 c:\> echo %qwert% 55 c:\> echo ^%qwert^% %qwert% A: here's an alternative suggestion you don't have to meddle with cmd "quirks" like that you encountered. Pass to your script normal text arguments, then in your script, do the templating.
literal usage of % in batch
I have a batch file containing a python script using the Output template> %(NAME)s when I ran it, cmd thinks its a var and igoners the % so youtube-dl.py -b -o %(uploader)s-%(title)s-%(id)s.%(ext)s turns into youtube-dl.py -b -o (uploader)s-(title)s-(id)s.(ext)s how do i convince cmd to not process it and pass it as is to python?
[ "Replace the % with %%:\nyoutube-dl.py -b -o %%(uploader)s-%%(title)s-%%(id)s.%%(ext)s\n\n(Note that, unlike on Unix, double quotes don't do a lot on Windows command lines.)\n", "If you don't want your % characters interpreted by cmd.exe, you should prefix them with the escape character:\nc:\\> set qwert=55\nc:\\> echo %qwert%\n55\nc:\\> echo ^%qwert^%\n%qwert%\n\n", "here's an alternative suggestion you don't have to meddle with cmd \"quirks\" like that you encountered. Pass to your script normal text arguments, then in your script, do the templating.\n" ]
[ 3, 3, 1 ]
[]
[]
[ "cmd", "python" ]
stackoverflow_0002350954_cmd_python.txt
Q: Putting a pyCurl XML server response into a variable (Python) I'm a Python novice, trying to use pyCurl. The project I am working on is creating a Python wrapper for the twitpic.com API (http://twitpic.com/api.do). For reference purposes, check out the code (http://pastebin.com/f4c498b6e) and the error I'm getting (http://pastebin.com/mff11d31). Pay special attention to line 27 of the code, which contains "xml = server.perform()". After researching my problem, I discovered that unlike I had previously thought, .perform() does not return the xml response from twitpic.com, but None, when the upload succeeds (duh!). After looking at the error output further, it seems to me like the xml input that I want stuffed into the "xml" variable is instead being printed to ether standard output or standard error (not sure which). I'm sure there is an easy way to do this, but I cannot seem to think of it at the moment. If you have any tips that could point me in the right direction, I'd be very appreciative. Thanks in advance. A: Using a StringIO would be much cleaner, no point in using a dummy class like that if all you want is the response data... Something like this would suffice: import pycurl import cStringIO response = cStringIO.StringIO() c = pycurl.Curl() c.setopt(c.URL, 'http://www.turnkeylinux.org') c.setopt(c.WRITEFUNCTION, response.write) c.perform() c.close() print response.getvalue() A: The pycurl doc explicitly says: perform() -> None So the expected result is what you observe. looking at an example from the pycurl site: import sys import pycurl class Test: def __init__(self): self.contents = '' def body_callback(self, buf): self.contents = self.contents + buf print >>sys.stderr, 'Testing', pycurl.version t = Test() c = pycurl.Curl() c.setopt(c.URL, 'http://curl.haxx.se/dev/') c.setopt(c.WRITEFUNCTION, t.body_callback) c.perform() c.close() print t.contents The interface requires a class instance - Test() - with a specific callback to save the content. Note the call c.setopt(c.WRITEFUNCTION, t.body_callback) - something like this is missing in your code, so you do not receive any data (buf in the example). The example shows how to access the content: print t.contents
Putting a pyCurl XML server response into a variable (Python)
I'm a Python novice, trying to use pyCurl. The project I am working on is creating a Python wrapper for the twitpic.com API (http://twitpic.com/api.do). For reference purposes, check out the code (http://pastebin.com/f4c498b6e) and the error I'm getting (http://pastebin.com/mff11d31). Pay special attention to line 27 of the code, which contains "xml = server.perform()". After researching my problem, I discovered that unlike I had previously thought, .perform() does not return the xml response from twitpic.com, but None, when the upload succeeds (duh!). After looking at the error output further, it seems to me like the xml input that I want stuffed into the "xml" variable is instead being printed to ether standard output or standard error (not sure which). I'm sure there is an easy way to do this, but I cannot seem to think of it at the moment. If you have any tips that could point me in the right direction, I'd be very appreciative. Thanks in advance.
[ "Using a StringIO would be much cleaner, no point in using a dummy class like that if all you want is the response data...\nSomething like this would suffice:\nimport pycurl\nimport cStringIO\n\nresponse = cStringIO.StringIO()\n\nc = pycurl.Curl()\nc.setopt(c.URL, 'http://www.turnkeylinux.org')\nc.setopt(c.WRITEFUNCTION, response.write)\nc.perform()\nc.close()\n\nprint response.getvalue()\n\n", "The pycurl doc explicitly says:\n\nperform() -> None\n\nSo the expected result is what you observe.\nlooking at an example from the pycurl site:\nimport sys\nimport pycurl\n\nclass Test:\n def __init__(self):\n self.contents = ''\n\n def body_callback(self, buf):\n self.contents = self.contents + buf\n\nprint >>sys.stderr, 'Testing', pycurl.version\n\nt = Test()\nc = pycurl.Curl()\nc.setopt(c.URL, 'http://curl.haxx.se/dev/')\nc.setopt(c.WRITEFUNCTION, t.body_callback)\nc.perform()\nc.close()\n\nprint t.contents\n\nThe interface requires a class instance - Test() - with a specific callback to save the content. Note the call c.setopt(c.WRITEFUNCTION, t.body_callback) - something like this is missing in your code, so you do not receive any data (buf in the example). The example shows how to access the content:\nprint t.contents\n\n" ]
[ 12, 4 ]
[]
[]
[ "pycurl", "python", "xml" ]
stackoverflow_0000256564_pycurl_python_xml.txt
Q: Can I use wxPython wx.ItemContainer in a derived class? I'm trying to make a new wx.Choice-like control (actually a replacement for wx.Choice) which uses the wx.ItemContainer to manage the list of items. Here is a minimal example showing the error: import wx class c(wx.ItemContainer): def __init__(my): pass x = c() x.Clear() This fails with: Traceback (most recent call last): File "", line 1, in File "c:\python25\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 1178 7, in Clear return _core_.ItemContainer_Clear(*args, **kwargs) TypeError: in method 'ItemContainer_Clear', expected argument 1 of type 'wxItemContainer *' The other controls using ItemContainer seem to be internal to wxWindows, so it may not be possible for me to use it this way. However, it would certainly be convenient. Any ideas on what I'm doing wrong? A: wx.ItemContainer can't be instantiated directly e.g. try x = wx.ItemContainer() it throws error Traceback (most recent call last): File "C:\<string>", line 1, in <module> File "D:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 11812, in __init__ def __init__(self): raise AttributeError, "No constructor defined" AttributeError: No constructor defined Reason being it is a type of interface(if we can call that in python) and you can not call __init__ on it, instead use it as second base and override the methods you use e.g. class C(wx.PyControl, wx.ItemContainer): def __init__(self, *args, **kwargs): wx.PyControl.__init__(self, *args, **kwargs) def Clear(self): pass app = wx.PySimpleApp() frame = wx.Frame(None,title="ItemContainer Test") x = C(frame) x.Clear() frame.Show() app.SetTopWindow(frame) app.MainLoop() A: Your suspicions are on the right track. You can't subclass any of the wxWidgets types, because they're in the C++ domain and only nominally wrapped in Python. Instead, you need a Py* class, which you can subclass. The explanation is given in this Wiki entry on writing custom controls. For ItemContainer, there doesn't appear to be such a wrapper - and the fact that ItemContainer is used as a parent in a multiple inheritance pattern may even complicate matters. I suspect that from within wxPython, it may not be possible to replace ItemContainer--and if you do need it, it will have to be integrated at the C++ level.
Can I use wxPython wx.ItemContainer in a derived class?
I'm trying to make a new wx.Choice-like control (actually a replacement for wx.Choice) which uses the wx.ItemContainer to manage the list of items. Here is a minimal example showing the error: import wx class c(wx.ItemContainer): def __init__(my): pass x = c() x.Clear() This fails with: Traceback (most recent call last): File "", line 1, in File "c:\python25\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 1178 7, in Clear return _core_.ItemContainer_Clear(*args, **kwargs) TypeError: in method 'ItemContainer_Clear', expected argument 1 of type 'wxItemContainer *' The other controls using ItemContainer seem to be internal to wxWindows, so it may not be possible for me to use it this way. However, it would certainly be convenient. Any ideas on what I'm doing wrong?
[ "wx.ItemContainer can't be instantiated directly e.g. try\nx = wx.ItemContainer()\n\nit throws error\nTraceback (most recent call last):\n File \"C:\\<string>\", line 1, in <module>\n File \"D:\\Python25\\Lib\\site-packages\\wx-2.8-msw-unicode\\wx\\_core.py\", line 11812, in __init__\n def __init__(self): raise AttributeError, \"No constructor defined\"\nAttributeError: No constructor defined\n\nReason being it is a type of interface(if we can call that in python) and you can not call __init__ on it, instead use it as second base and override the methods you use e.g.\nclass C(wx.PyControl, wx.ItemContainer): \n def __init__(self, *args, **kwargs):\n wx.PyControl.__init__(self, *args, **kwargs)\n\n def Clear(self):\n pass\n\napp = wx.PySimpleApp()\n\nframe = wx.Frame(None,title=\"ItemContainer Test\")\nx = C(frame)\nx.Clear()\n\nframe.Show()\napp.SetTopWindow(frame)\napp.MainLoop()\n\n", "Your suspicions are on the right track. You can't subclass any of the wxWidgets types, because they're in the C++ domain and only nominally wrapped in Python. Instead, you need a Py* class, which you can subclass. The explanation is given in this Wiki entry on writing custom controls.\nFor ItemContainer, there doesn't appear to be such a wrapper - and the fact that ItemContainer is used as a parent in a multiple inheritance pattern may even complicate matters.\nI suspect that from within wxPython, it may not be possible to replace ItemContainer--and if you do need it, it will have to be integrated at the C++ level.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002335585_python_wxpython.txt
Q: Socket shutdown and rebind - How to avoid long wait? I'm working with socket in python, and being in development stage I need to kill and restart my program frequently. The issue is that once killed my python script, I've to wait long time to be able to rebind the listen socket. Here's a snippet to reproduce the problem: #!/usr/bin/env python3 import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((socket.gethostname(), 4321)) try: s.listen(5) while True: (a, b) = s.accept() print(a.recv(1000)) except KeyboardInterrupt: print("Closing") s.shutdown(socket.SHUT_RDWR) s.close() Hitting C-z runs the except code, calling shutdown and close functions, but I'm not able to restart my program until the socket timeout (GNU/Linux environment). How can I avoid this? A: I'm not sure how to do it in Python, but you want to set the SO_REUSEADDR socket option.
Socket shutdown and rebind - How to avoid long wait?
I'm working with socket in python, and being in development stage I need to kill and restart my program frequently. The issue is that once killed my python script, I've to wait long time to be able to rebind the listen socket. Here's a snippet to reproduce the problem: #!/usr/bin/env python3 import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((socket.gethostname(), 4321)) try: s.listen(5) while True: (a, b) = s.accept() print(a.recv(1000)) except KeyboardInterrupt: print("Closing") s.shutdown(socket.SHUT_RDWR) s.close() Hitting C-z runs the except code, calling shutdown and close functions, but I'm not able to restart my program until the socket timeout (GNU/Linux environment). How can I avoid this?
[ "I'm not sure how to do it in Python, but you want to set the SO_REUSEADDR socket option.\n" ]
[ 4 ]
[]
[]
[ "linux", "python", "python_3.x", "sockets" ]
stackoverflow_0002351465_linux_python_python_3.x_sockets.txt
Q: python switch by class name? I am currently doing this, to do different things based on an object's type: actions = { SomeClass: lambda: obj.name AnotherClass: lambda: self.normalize(obj.identifier) ...[5 more of these]... } for a in actions.keys(): if isinstance(obj, a): return actions[a]() Is it possible to cut out the for loop, and do something like this? actions[something to do with obj]() A: class SomeClass( object ): .... def action( self ): return self.name class AnotherClass( object ): .... def action( self ): return self.normalize( self.identifier ) [5 more classes like the above two] a.action() Simpler. Clearer. More extensible. Less Magic. No dictionary. No loop. A: actions[obj.__class__]() works if obj is really an instance of (say) SomeClass and not of a subclass -- so if that can be the case, the result will be different from your current way of handling it. Also note that this might raise a KeyError if the class has no corresponding action. To handle this case the same way you do now (i.e. do nothing), you could use actions.get(obj.__class__, lambda: None) to have a default value returned. Oh, and listen to S.Lott's comment on your question. In many cases, there are better ways to achieve something like this. You could, for example, have all your classes define a do_whatever(self) and just call obj.do_whatever(). A: I assume you have a parent class for all of those, or at least a mixin. Put a default return function in the parent or mixin, and then override it in those that are different... It's the only proper way of doing it. Sure, it makes extra code, but at least it's encapsulated, and scalable. Say you wanna add support for five more classes. Instead of altering that code up there, just add the correct code to the new classes. By the looks of it, it's two lines per class (function definition and return line). That's not bad, is it? If obj isn't a class which contains a return function, then an exception is raised, which you could catch and ignore with a clean conscience. class MyMixin: def my_return(self, *args): return self.name ... possibly other things... class SomeClass(MyMixin): ... no alteration to the default ... class AnotherClass(MyParent, MyMixin): def my_return(self, *args): return args[0].normalize(self.identifier) ... blabla # now, this is in the caller object... try: rval = obj.my_return(self) # this is the caller object 'self', not the 'self' in the 'obj' #dosomething with rval except Exception: pass #no rval for this object type, skipping it... A: What about actions[obj.__class__]() A: actions[type(obj)]() A: results = [func() for cls, func in actions.iteritems() if isinstance(obj, cls)] There will be zero or more results, if your object isinstance of zero or more of the class-keys. Using type(obj) as key will only work if your object is of that type. If it's further down the inheritance tree, you'll miss it.
python switch by class name?
I am currently doing this, to do different things based on an object's type: actions = { SomeClass: lambda: obj.name AnotherClass: lambda: self.normalize(obj.identifier) ...[5 more of these]... } for a in actions.keys(): if isinstance(obj, a): return actions[a]() Is it possible to cut out the for loop, and do something like this? actions[something to do with obj]()
[ "class SomeClass( object ):\n....\n def action( self ):\n return self.name\n\nclass AnotherClass( object ):\n....\n def action( self ):\n return self.normalize( self.identifier )\n\n[5 more classes like the above two]\n\na.action()\n\nSimpler. Clearer. More extensible. Less Magic. No dictionary. No loop.\n", "actions[obj.__class__]()\n\nworks if obj is really an instance of (say) SomeClass and not of a subclass -- so if that can be the case, the result will be different from your current way of handling it. Also note that this might raise a KeyError if the class has no corresponding action. To handle this case the same way you do now (i.e. do nothing), you could use\nactions.get(obj.__class__, lambda: None)\n\nto have a default value returned.\nOh, and listen to S.Lott's comment on your question. In many cases, there are better ways to achieve something like this. You could, for example, have all your classes define a do_whatever(self) and just call obj.do_whatever().\n", "I assume you have a parent class for all of those, or at least a mixin. Put a default return function in the parent or mixin, and then override it in those that are different... It's the only proper way of doing it. \nSure, it makes extra code, but at least it's encapsulated, and scalable. Say you wanna add support for five more classes. Instead of altering that code up there, just add the correct code to the new classes. By the looks of it, it's two lines per class (function definition and return line). That's not bad, is it?\nIf obj isn't a class which contains a return function, then an exception is raised, which you could catch and ignore with a clean conscience.\nclass MyMixin:\n def my_return(self, *args):\n return self.name\n ... possibly other things...\n\nclass SomeClass(MyMixin):\n ... no alteration to the default ...\n\nclass AnotherClass(MyParent, MyMixin):\n def my_return(self, *args):\n return args[0].normalize(self.identifier)\n ... blabla\n\n\n# now, this is in the caller object...\ntry:\n rval = obj.my_return(self) # this is the caller object 'self', not the 'self' in the 'obj'\n #dosomething with rval\nexcept Exception:\n pass #no rval for this object type, skipping it...\n\n", "What about\nactions[obj.__class__]()\n\n", "actions[type(obj)]()\n\n", "results = [func() for cls, func in actions.iteritems() if isinstance(obj, cls)]\n\nThere will be zero or more results, if your object isinstance of zero or more of the class-keys. \nUsing type(obj) as key will only work if your object is of that type. If it's further down the inheritance tree, you'll miss it.\n" ]
[ 7, 2, 2, 0, 0, 0 ]
[]
[]
[ "python", "switch_statement", "syntax" ]
stackoverflow_0002351525_python_switch_statement_syntax.txt
Q: Why doesn't import prevent NameError in a python script run with execfile()? I looked at a number of existing questions about NameError exceptions when scripts are run with exec statements or execfile() in Python, but haven't found a good explanation yet of the following behavior. I want to make a simple game that creates script objects at runtime with execfile(). Below are 4 modules that demonstrate the problem (please bear with me, this is as simple as I could make it!). The main program just loads a script using execfile() and then calls a script manager to run the script objects: # game.py import script_mgr import gamelib # must be imported here to prevent NameError, any place else has no effect def main(): execfile("script.py") script_mgr.run() main() The script file just creates an object that plays a sound and then adds the object to a list in the script manager: script.py import script_mgr #import gamelib # (has no effect here) class ScriptObject: def action(self): print("ScriptObject.action(): calling gamelib.play_sound()") gamelib.play_sound() obj = ScriptObject() script_mgr.add_script_object(obj) The script manager just calls the action() function of each script: # script_mgr.py #import gamelib # (has no effect here) script_objects = [] def add_script_object(obj): script_objects.append(obj) def run(): for obj in script_objects: obj.action() The gamelib function is defined in a fourth module, which is the troublesome one to be accessed: # gamelib.py def play_sound(): print("boom!") The above code works with the following output: mhack:exec $ python game.py ScriptObject.action(): calling gamelib.play_sound() boom! mhack:exec $ However, if I comment-out the 'import gamelib' statement in game.py and uncomment the 'import gamelib' in script.py, I get the following error: mhack:exec $ python game.py ScriptObject.action(): calling gamelib.play_sound() Traceback (most recent call last): File "game.py", line 10, in main() File "game.py", line 8, in main script_mgr.run() File "/Users/williamknight/proj/test/python/exec/script_mgr.py", line 12, in run obj.action() File "script.py", line 9, in action gamelib.play_sound() NameError: global name 'gamelib' is not defined My question is: 1) Why is the import needed in the 'game.py' module, the one that execs the script? 2) Why doesn't it work to import 'gamelib' from the module where it is referenced (script.py) or the module where it is called (script_mgr.py)? This happens on Python 2.5.1 A: From the Python documentation for execfile: execfile(filename[, globals[, locals]]) If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where execfile() is called. There are two optional arguments for execfile. Since you omit them both, your script is being executed in the environment where execfile is called. Hence the reason the import in game.py changes the behaviour. In addition, I concluded the following behaviour of import in game.py and script.py: In game.py import gamelib imports the gamelib module into both globals and locals. This is the environment passed to script.py which is why gamelib is accessible in the ScriptObject action method (accessed from globals). In script.py import gamelib imports the gamelib module into locals only (not sure of the reason). So when trying to access gamelib from the ScriptObject action method from globals you have the NameError. It will work if you move the import into the scope of the action method as follows (gamelib will be accessed from locals): class ScriptObject: def action(self): import gamelib print("ScriptObject.action(): calling gamelib.play_sound()") gamelib.play_sound() A: The reason the 'import gamelib' in script.py has no effect is because it imports into the local scope of game.py main(), because this is the scope in which the import is executed. This scope is not a visible scope for ScriptObject.action() when it executes. Adding debug code to print out the changes in the globals() and locals() reveals what is going on in the following modified version of the program: # game.py import script_mgr import gamelib # puts gamelib into globals() of game.py # a debug global variable _game_global = "BEF main()" def report_dict(d): s = "" keys = d.keys() keys.sort() for i, k in enumerate(keys): ln = "%04d %s: %s\n" % (i, k, d[k]) s += ln return s def main(): print("--- game(): BEF exec: globals:\n%s" % (report_dict(globals()))) print("--- game(): BEF exec: locals:\n%s" % (report_dict(locals()))) global _game_global _game_global = "in main(), BEF execfile()" execfile("script.py") _game_global = "in main(), AFT execfile()" print("--- game(): AFT exec: globals:\n%s" % (report_dict(globals()))) print("--- game(): AFT exec: locals:\n%s" % (report_dict(locals()))) script_mgr.run() main() # script.py import script_mgr import gamelib # puts gamelib into the local scope of game.py main() import pdb # a test import that only shows up in the local scope of game.py main(). It will _not_ show up in any visible scope of ScriptObject.action()! class ScriptObject: def action(self): def report_dict(d): s = "" keys = d.keys() keys.sort() for i, k in enumerate(keys): ln = "%04d %s: %s\n" % (i, k, d[k]) s += ln return s print("--- ScriptObject.action(): globals:\n%s" % (report_dict(globals()))) print("--- ScriptObject.action(): locals:\n%s" % (report_dict(locals()))) gamelib.play_sound() obj = ScriptObject() script_mgr.add_script_object(obj) Here is the debug output of the program: --- game(): BEF exec: globals: 0000 __builtins__: 0001 __doc__: None 0002 __file__: game.py 0003 __name__: __main__ 0004 _game_global: BEF main() 0005 gamelib: 0006 main: 0007 report_dict: 0008 script_mgr: --- game(): BEF exec: locals: --- game(): AFT exec: globals: 0000 __builtins__: 0001 __doc__: None 0002 __file__: game.py 0003 __name__: __main__ 0004 _game_global: in main(), AFT execfile() 0005 gamelib: 0006 main: 0007 report_dict: 0008 script_mgr: --- game(): AFT exec: locals: 0000 ScriptObject: __main__.ScriptObject 0001 gamelib: 0002 obj: 0003 pdb: 0004 script_mgr: --- ScriptObject.action(): globals: 0000 __builtins__: 0001 __doc__: None 0002 __file__: game.py 0003 __name__: __main__ 0004 _game_global: in main(), AFT execfile() 0005 gamelib: 0006 main: 0007 report_dict: 0008 script_mgr: --- ScriptObject.action(): locals: 0000 report_dict: 0001 self: boom! Instead of trying to put imports in game.py or the module level of script.py, I will follow Yukiko's suggestion to put import statements at the local scope of the script object member functions. This seems a little awkward to me, and there may be some better way to specify such imports for exec'd scripts, but at least I now understand what is happening.
Why doesn't import prevent NameError in a python script run with execfile()?
I looked at a number of existing questions about NameError exceptions when scripts are run with exec statements or execfile() in Python, but haven't found a good explanation yet of the following behavior. I want to make a simple game that creates script objects at runtime with execfile(). Below are 4 modules that demonstrate the problem (please bear with me, this is as simple as I could make it!). The main program just loads a script using execfile() and then calls a script manager to run the script objects: # game.py import script_mgr import gamelib # must be imported here to prevent NameError, any place else has no effect def main(): execfile("script.py") script_mgr.run() main() The script file just creates an object that plays a sound and then adds the object to a list in the script manager: script.py import script_mgr #import gamelib # (has no effect here) class ScriptObject: def action(self): print("ScriptObject.action(): calling gamelib.play_sound()") gamelib.play_sound() obj = ScriptObject() script_mgr.add_script_object(obj) The script manager just calls the action() function of each script: # script_mgr.py #import gamelib # (has no effect here) script_objects = [] def add_script_object(obj): script_objects.append(obj) def run(): for obj in script_objects: obj.action() The gamelib function is defined in a fourth module, which is the troublesome one to be accessed: # gamelib.py def play_sound(): print("boom!") The above code works with the following output: mhack:exec $ python game.py ScriptObject.action(): calling gamelib.play_sound() boom! mhack:exec $ However, if I comment-out the 'import gamelib' statement in game.py and uncomment the 'import gamelib' in script.py, I get the following error: mhack:exec $ python game.py ScriptObject.action(): calling gamelib.play_sound() Traceback (most recent call last): File "game.py", line 10, in main() File "game.py", line 8, in main script_mgr.run() File "/Users/williamknight/proj/test/python/exec/script_mgr.py", line 12, in run obj.action() File "script.py", line 9, in action gamelib.play_sound() NameError: global name 'gamelib' is not defined My question is: 1) Why is the import needed in the 'game.py' module, the one that execs the script? 2) Why doesn't it work to import 'gamelib' from the module where it is referenced (script.py) or the module where it is called (script_mgr.py)? This happens on Python 2.5.1
[ "From the Python documentation for execfile:\nexecfile(filename[, globals[, locals]])\nIf the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where execfile() is called.\nThere are two optional arguments for execfile. Since you omit them both, your script is being executed in the environment where execfile is called. Hence the reason the import in game.py changes the behaviour.\nIn addition, I concluded the following behaviour of import in game.py and script.py:\n\nIn game.py import gamelib imports the gamelib module into both globals and locals. This is the environment passed to script.py which is why gamelib is accessible in the ScriptObject action method (accessed from globals).\nIn script.py import gamelib imports the gamelib module into locals only (not sure of the reason). So when trying to access gamelib from the ScriptObject action method from globals you have the NameError. It will work if you move the import into the scope of the action method as follows (gamelib will be accessed from locals):\nclass ScriptObject:\n def action(self):\n import gamelib\n print(\"ScriptObject.action(): calling gamelib.play_sound()\")\n gamelib.play_sound()\n\n\n", "The reason the 'import gamelib' in script.py has no effect is because it imports into the local scope of game.py main(), because this is the scope in which the import is executed. This scope is not a visible scope for ScriptObject.action() when it executes. \nAdding debug code to print out the changes in the globals() and locals() reveals what is going on in the following modified version of the program:\n# game.py\n\nimport script_mgr\nimport gamelib # puts gamelib into globals() of game.py\n\n# a debug global variable \n_game_global = \"BEF main()\" \n\ndef report_dict(d):\n s = \"\"\n keys = d.keys()\n keys.sort() \n for i, k in enumerate(keys):\n ln = \"%04d %s: %s\\n\" % (i, k, d[k])\n s += ln\n return s\n\ndef main():\n print(\"--- game(): BEF exec: globals:\\n%s\" % (report_dict(globals())))\n print(\"--- game(): BEF exec: locals:\\n%s\" % (report_dict(locals())))\n global _game_global \n _game_global = \"in main(), BEF execfile()\"\n execfile(\"script.py\")\n _game_global = \"in main(), AFT execfile()\"\n print(\"--- game(): AFT exec: globals:\\n%s\" % (report_dict(globals())))\n print(\"--- game(): AFT exec: locals:\\n%s\" % (report_dict(locals())))\n script_mgr.run()\n\nmain()\n# script.py \n\nimport script_mgr\nimport gamelib # puts gamelib into the local scope of game.py main()\nimport pdb # a test import that only shows up in the local scope of game.py main(). It will _not_ show up in any visible scope of ScriptObject.action()!\n\nclass ScriptObject:\n def action(self):\n def report_dict(d):\n s = \"\"\n keys = d.keys()\n keys.sort()\n for i, k in enumerate(keys):\n ln = \"%04d %s: %s\\n\" % (i, k, d[k])\n s += ln\n return s\n print(\"--- ScriptObject.action(): globals:\\n%s\" % (report_dict(globals())))\n print(\"--- ScriptObject.action(): locals:\\n%s\" % (report_dict(locals())))\n gamelib.play_sound()\n\nobj = ScriptObject()\nscript_mgr.add_script_object(obj)\nHere is the debug output of the program:\n--- game(): BEF exec: globals:\n0000 __builtins__: \n0001 __doc__: None\n0002 __file__: game.py\n0003 __name__: __main__\n0004 _game_global: BEF main()\n0005 gamelib: \n0006 main: \n0007 report_dict: \n0008 script_mgr: \n\n--- game(): BEF exec: locals:\n\n--- game(): AFT exec: globals:\n0000 __builtins__: \n0001 __doc__: None\n0002 __file__: game.py\n0003 __name__: __main__\n0004 _game_global: in main(), AFT execfile()\n0005 gamelib: \n0006 main: \n0007 report_dict: \n0008 script_mgr: \n\n--- game(): AFT exec: locals:\n0000 ScriptObject: __main__.ScriptObject\n0001 gamelib: \n0002 obj: \n0003 pdb: \n0004 script_mgr: \n\n--- ScriptObject.action(): globals:\n0000 __builtins__: \n0001 __doc__: None\n0002 __file__: game.py\n0003 __name__: __main__\n0004 _game_global: in main(), AFT execfile()\n0005 gamelib: \n0006 main: \n0007 report_dict: \n0008 script_mgr: \n\n--- ScriptObject.action(): locals:\n0000 report_dict: \n0001 self: \n\n\nboom!\nInstead of trying to put imports in game.py or the module level of script.py, I will follow Yukiko's suggestion to put import statements at the local scope of the script object member functions. This seems a little awkward to me, and there may be some better way to specify such imports for exec'd scripts, but at least I now understand what is happening.\n" ]
[ 3, 0 ]
[]
[]
[ "exec", "execfile", "import", "nameerror", "python" ]
stackoverflow_0002348630_exec_execfile_import_nameerror_python.txt
Q: numpy.matrix manipulations I have a question about numpy.matrix class. How can I perform such basic manipulations with matrices as adding, deleting and replacing rows and columns? p.s. I apologize for the lame question.. A: Perfectly fine question! Try examining this code: import scipy X = scipy.rand(3,3) Y = scipy.rand(3,3) print X+Y print scipy.delete(X, 1, 0) print scipy.delete(X, 1, 1) X[1,:] = [1,2,3] print X For more, see the numpy/scipy docs here: NumPy/SciPy docs If you are fluent in Matlab, this page is useful: NumPy for Matlab Users
numpy.matrix manipulations
I have a question about numpy.matrix class. How can I perform such basic manipulations with matrices as adding, deleting and replacing rows and columns? p.s. I apologize for the lame question..
[ "Perfectly fine question! Try examining this code:\nimport scipy\nX = scipy.rand(3,3)\nY = scipy.rand(3,3)\nprint X+Y\nprint scipy.delete(X, 1, 0)\nprint scipy.delete(X, 1, 1)\nX[1,:] = [1,2,3]\nprint X\n\nFor more, see the numpy/scipy docs here: NumPy/SciPy docs\nIf you are fluent in Matlab, this page is useful: NumPy for Matlab Users\n" ]
[ 3 ]
[]
[]
[ "matrix", "numpy", "python" ]
stackoverflow_0002351844_matrix_numpy_python.txt
Q: How can I prevent a name error error in python? When I run my program core.py (http://pastebin.com/kbzbBUYd) it returns: File "core.py", line 47, in texto core.mail(numbersendlist, messagetext) NameError: global name 'core' is not defined Can anyone tell me what is going on and how I can stop this error? If it helps, the "import carrier" line in core.py refers to carrier.py (http://pastebin.com/zP2RHbnr) A: You're getting NameError Because there's no such name core defined in your code in either local or global scope. Create a Core object first before calling it's methods. Also the indentation of texto() is probably wrong. You won't be able to use this function from rest of the module. If you want to use it from other parts of current module or from other modules, declare the function at module level or use the @staticmethod decorator to if you want to make it a static method of the class. This should work. import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText import carrier class Core: def __init__(self, username, password): # code could be added here to auto load these from a file self.gmail_user = username self.gmail_pwd = password # Send one text to one number # TODO: send to multiple addresses def mail(self, to, text): msg = MIMEMultipart() msg['From'] = self.gmail_user msg['To'] = to msg.attach(MIMEText(text)) mailServer = smtplib.SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(self.gmail_user, self.gmail_pwd) mailServer.sendmail(self.gmail_user, to, msg.as_string()) # Should be mailServer.quit(), but that crashes... mailServer.close() def texto(sendtoaddress, messagetext): numbersendlist = [] for number in sendtoaddress: numbersendlist.append(carrier.carriercheck(number)) core = Core('username', 'password') for number in numbersendlist: core.mail(number, messagetext) texto(['1112223333'], 'hi. this better work.') A: core is not a name that you've defined, yet. I expect that you intended to write something like core = Core('username', 'password') before calling texto?
How can I prevent a name error error in python?
When I run my program core.py (http://pastebin.com/kbzbBUYd) it returns: File "core.py", line 47, in texto core.mail(numbersendlist, messagetext) NameError: global name 'core' is not defined Can anyone tell me what is going on and how I can stop this error? If it helps, the "import carrier" line in core.py refers to carrier.py (http://pastebin.com/zP2RHbnr)
[ "You're getting NameError Because there's no such name core defined in your code in either local or global scope. Create a Core object first before calling it's methods.\nAlso the indentation of texto() is probably wrong. You won't be able to use this function from rest of the module. If you want to use it from other parts of current module or from other modules, declare the function at module level or use the @staticmethod decorator to if you want to make it a static method of the class.\nThis should work.\nimport smtplib\nfrom email.MIMEMultipart import MIMEMultipart\nfrom email.MIMEText import MIMEText\nimport carrier\n\nclass Core: \n def __init__(self, username, password):\n # code could be added here to auto load these from a file\n self.gmail_user = username\n self.gmail_pwd = password\n\n# Send one text to one number\n# TODO: send to multiple addresses\n\n def mail(self, to, text):\n msg = MIMEMultipart()\n msg['From'] = self.gmail_user\n msg['To'] = to\n msg.attach(MIMEText(text))\n\n mailServer = smtplib.SMTP(\"smtp.gmail.com\", 587)\n mailServer.ehlo()\n mailServer.starttls()\n mailServer.ehlo()\n mailServer.login(self.gmail_user, self.gmail_pwd)\n mailServer.sendmail(self.gmail_user, to, msg.as_string())\n # Should be mailServer.quit(), but that crashes...\n mailServer.close()\n\n\ndef texto(sendtoaddress, messagetext):\n numbersendlist = []\n for number in sendtoaddress:\n numbersendlist.append(carrier.carriercheck(number))\n\n core = Core('username', 'password')\n for number in numbersendlist:\n core.mail(number, messagetext)\n\ntexto(['1112223333'], 'hi. this better work.')\n\n", "core is not a name that you've defined, yet. I expect that you intended to write something like\ncore = Core('username', 'password')\n\nbefore calling texto?\n" ]
[ 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002351904_python.txt
Q: What's the proper way to describe an associative object by SQLalchemy the declarative way I'm looking for a way to describe an associative object the declarative way. Beyond storing the foreign keys in the association table, I need to store information like the creation date of the association. Today, my model looks like that : # Define the User class class User(Base): __tablename__ = 'users' # Define User fields id = schema.Column(types.Integer(unsigned=True), schema.Sequence('users_seq_id', optional=True), primary_key=True) password = schema.Column(types.Unicode(64), nullable=False) # Define the UserSubset class class UserSubset(Base): __tablename__ = 'subsets' # Define UserSubset fields id = schema.Column(types.Integer(unsigned=True), schema.Sequence('subsets_seq_id', optional=True), primary_key=True) some_short_description = schema.Column(types.Unicode(50), nullable=False) # Define the subset memberships table subset_memberships = schema.Table('group_memberships', Base.metadata, schema.Column('user_id', types.Integer(unsigned=True), ForeignKey('users.id')), schema.Column('subset_id', types.Integer(unsigned=True), ForeignKey('subsets.id')), schema.Column('created', types.DateTime(), default=now, nullable=False), ) Can I connect everything in an associative object ? Or should I change stop using the declarative way ? A: What you are using at the moment is just a Many-to-Many-relation. How to work with association objects is described in the docs. There is also an extension called associationproxy which simplifies the relation. A: As you can see in the manual, configuring a one to many relation is really simple: class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(50)) addresses = relation("Address", backref="user") class Address(Base): __tablename__ = 'addresses' id = Column(Integer, primary_key=True) email = Column(String(50)) user_id = Column(Integer, ForeignKey('users.id')) Many to many relations isn't much harder: There’s nothing special about many-to-many with declarative. The secondary argument to relation() still requires a Table object, not a declarative class. The Table should share the same MetaData object used by the declarative base: keywords = Table('keywords', Base.metadata, Column('author_id', Integer, ForeignKey('authors.id')), Column('keyword_id', Integer, ForeignKey('keywords.id')) ) class Author(Base): __tablename__ = 'authors' id = Column(Integer, primary_key=True) keywords = relation("Keyword", secondary=keywords) You should generally not map a class and also specify its table in a many-to-many relation, since the ORM may issue duplicate INSERT and DELETE statements. Anyway, what you seem to be doing might be better served with inheritance. Of course, there can be complex table relations that will be a pathological case for the declarative way, but this doesn't seem to be one of them. One more thing, code comments should state what the following code does ans why, not how it does it. Having a # Define the User class comment is almost like having a line of code saying a = 1 # assing value 1 to variable "a".
What's the proper way to describe an associative object by SQLalchemy the declarative way
I'm looking for a way to describe an associative object the declarative way. Beyond storing the foreign keys in the association table, I need to store information like the creation date of the association. Today, my model looks like that : # Define the User class class User(Base): __tablename__ = 'users' # Define User fields id = schema.Column(types.Integer(unsigned=True), schema.Sequence('users_seq_id', optional=True), primary_key=True) password = schema.Column(types.Unicode(64), nullable=False) # Define the UserSubset class class UserSubset(Base): __tablename__ = 'subsets' # Define UserSubset fields id = schema.Column(types.Integer(unsigned=True), schema.Sequence('subsets_seq_id', optional=True), primary_key=True) some_short_description = schema.Column(types.Unicode(50), nullable=False) # Define the subset memberships table subset_memberships = schema.Table('group_memberships', Base.metadata, schema.Column('user_id', types.Integer(unsigned=True), ForeignKey('users.id')), schema.Column('subset_id', types.Integer(unsigned=True), ForeignKey('subsets.id')), schema.Column('created', types.DateTime(), default=now, nullable=False), ) Can I connect everything in an associative object ? Or should I change stop using the declarative way ?
[ "What you are using at the moment is just a Many-to-Many-relation. How to work with association objects is described in the docs.\nThere is also an extension called associationproxy which simplifies the relation.\n", "As you can see in the manual, configuring a one to many relation is really simple:\nclass User(Base):\n __tablename__ = 'users'\n\n id = Column(Integer, primary_key=True)\n name = Column(String(50))\n addresses = relation(\"Address\", backref=\"user\")\n\nclass Address(Base):\n __tablename__ = 'addresses'\n\n id = Column(Integer, primary_key=True)\n email = Column(String(50))\n user_id = Column(Integer, ForeignKey('users.id'))\n\nMany to many relations isn't much harder:\n\nThere’s nothing special about many-to-many with declarative. The secondary argument to relation() still requires a Table object, not a declarative class. The Table should share the same MetaData object used by the declarative base:\n keywords = Table('keywords', Base.metadata,\n Column('author_id', Integer, ForeignKey('authors.id')),\n Column('keyword_id', Integer, ForeignKey('keywords.id'))\n )\n \n class Author(Base):\n __tablename__ = 'authors'\n id = Column(Integer, primary_key=True)\n keywords = relation(\"Keyword\", secondary=keywords)\n\nYou should generally not map a class and also specify its table in a many-to-many relation, since the ORM may issue duplicate INSERT and DELETE statements.\n\nAnyway, what you seem to be doing might be better served with inheritance. Of course, there can be complex table relations that will be a pathological case for the declarative way, but this doesn't seem to be one of them.\nOne more thing, code comments should state what the following code does ans why, not how it does it. Having a # Define the User class comment is almost like having a line of code saying a = 1 # assing value 1 to variable \"a\".\n" ]
[ 1, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002351927_python_sqlalchemy.txt
Q: How can I detect and track people using OpenCV? I have a camera that will be stationary, pointed at an indoors area. People will walk past the camera, within about 5 meters of it. Using OpenCV, I want to detect individuals walking past - my ideal return is an array of detected individuals, with bounding rectangles. I've looked at several of the built-in samples: None of the Python samples really apply The C blob tracking sample looks promising, but doesn't accept live video, which makes testing difficult. It's also the most complicated of the samples, making extracting the relevant knowledge and converting it to the Python API problematic. The C 'motempl' sample also looks promising, in that it calculates a silhouette from subsequent video frames. Presumably I could then use that to find strongly connected components and extract individual blobs and their bounding boxes - but I'm still left trying to figure out a way to identify blobs found in subsequent frames as the same blob. Is anyone able to provide guidance or samples for doing this - preferably in Python? A: The latest SVN version of OpenCV contains an (undocumented) implementation of HOG-based pedestrian detection. It even comes with a pre-trained detector and a python wrapper. The basic usage is as follows: from cv import * storage = CreateMemStorage(0) img = LoadImage(file) # or read from camera found = list(HOGDetectMultiScale(img, storage, win_stride=(8,8), padding=(32,32), scale=1.05, group_threshold=2)) So instead of tracking, you might just run the detector in each frame and use its output directly. See src/cvaux/cvhog.cpp for the implementation and samples/python/peopledetect.py for a more complete python example (both in the OpenCV sources). A: Nick, What you are looking for is not people detection, but motion detection. If you tell us a lot more about what you are trying to solve/do, we can answer better. Anyway, there are many ways to do motion detection depending on what you are going to do with the results. Simplest one would be differencing followed by thresholding while a complex one could be proper background modeling -> foreground subtraction -> morphological ops -> connected component analysis, followed by blob analysis if required. Download the opencv code and look in samples directory. You might see what you are looking for. Also, there is an Oreilly book on OCV. Hope this helps, Nand A: This is clearly a non-trivial task. You'll have to look into scientific publications for inspiration (Google Scholar is your friend here). Here's a paper about human detection and tracking: Human tracking by fast mean shift mode seeking A: This is similar to a project we did as part of a Computer Vision course, and I can tell you right now that it is a hard problem to get right. You could use foreground/background segmentation, find all blobs and then decide that they are a person. The problem is that it will not work very well since people tend to go together, go past each other and so on, so a blob might very well consist of two persons and then you will see that blob splitting and merging as they walk along. You will need some method of discriminating between multiple persons in one blob. This is not a problem I expect anyone being able to answer in a single SO-post. My advice is to dive into the available research and see if you can find anything there. The problem is not unsolvavble considering that there exists products which do this: Autoliv has a product to detect pedestrians using an IR-camera on a car, and I have seen other products which deal with counting customers entering and exiting stores.
How can I detect and track people using OpenCV?
I have a camera that will be stationary, pointed at an indoors area. People will walk past the camera, within about 5 meters of it. Using OpenCV, I want to detect individuals walking past - my ideal return is an array of detected individuals, with bounding rectangles. I've looked at several of the built-in samples: None of the Python samples really apply The C blob tracking sample looks promising, but doesn't accept live video, which makes testing difficult. It's also the most complicated of the samples, making extracting the relevant knowledge and converting it to the Python API problematic. The C 'motempl' sample also looks promising, in that it calculates a silhouette from subsequent video frames. Presumably I could then use that to find strongly connected components and extract individual blobs and their bounding boxes - but I'm still left trying to figure out a way to identify blobs found in subsequent frames as the same blob. Is anyone able to provide guidance or samples for doing this - preferably in Python?
[ "The latest SVN version of OpenCV contains an (undocumented) implementation of HOG-based pedestrian detection. It even comes with a pre-trained detector and a python wrapper. The basic usage is as follows:\nfrom cv import *\n\nstorage = CreateMemStorage(0)\nimg = LoadImage(file) # or read from camera\n\nfound = list(HOGDetectMultiScale(img, storage, win_stride=(8,8),\n padding=(32,32), scale=1.05, group_threshold=2))\n\nSo instead of tracking, you might just run the detector in each frame and use its output directly.\nSee src/cvaux/cvhog.cpp for the implementation and samples/python/peopledetect.py for a more complete python example (both in the OpenCV sources).\n", "Nick,\nWhat you are looking for is not people detection, but motion detection. If you tell us a lot more about what you are trying to solve/do, we can answer better. \nAnyway, there are many ways to do motion detection depending on what you are going to do with the results. Simplest one would be differencing followed by thresholding while a complex one could be proper background modeling -> foreground subtraction -> morphological ops -> connected component analysis, followed by blob analysis if required. Download the opencv code and look in samples directory. You might see what you are looking for. Also, there is an Oreilly book on OCV.\nHope this helps,\nNand \n", "This is clearly a non-trivial task. You'll have to look into scientific publications for inspiration (Google Scholar is your friend here). Here's a paper about human detection and tracking: Human tracking by fast mean shift mode seeking\n", "This is similar to a project we did as part of a Computer Vision course, and I can tell you right now that it is a hard problem to get right.\nYou could use foreground/background segmentation, find all blobs and then decide that they are a person. The problem is that it will not work very well since people tend to go together, go past each other and so on, so a blob might very well consist of two persons and then you will see that blob splitting and merging as they walk along.\nYou will need some method of discriminating between multiple persons in one blob. This is not a problem I expect anyone being able to answer in a single SO-post.\nMy advice is to dive into the available research and see if you can find anything there. The problem is not unsolvavble considering that there exists products which do this: Autoliv has a product to detect pedestrians using an IR-camera on a car, and I have seen other products which deal with counting customers entering and exiting stores.\n" ]
[ 28, 5, 4, 2 ]
[]
[]
[ "computer_vision", "motion_detection", "opencv", "python" ]
stackoverflow_0002188646_computer_vision_motion_detection_opencv_python.txt
Q: Use Mercurial API to Get Changes to a Repository For a Given Changeset How can I use the Mercurial API to determine the changes made to a repository for each changeset? I am able to get a list of files relevant to a particular revision, but I cannot figure out how to tell what happened to that file. How can I answer these questions about each file in a changeset: Was it added? Was it deleted? Was it modified? Is there an attribute in the file context that will tell me this (if so, I cannot find it), or there ways to figure this out by other means? Here is my code: def index(request): u = ui.ui() repo = hg.repository(ui.ui(), '/path/to/repo') changes = repo.changelog changesets = [] for change in changes: ctx = repo.changectx(change) fileCtxs = [] for aFile in ctx.files(): if aFile in ctx: for status in repo.status(None, ctx.node()): # I'm hoping this could return A, M, D, ? etc fileCtxs.append(status) changeset = { 'files':ctx.files(), 'rev':str(ctx.rev()), 'desc':ctx.description(), 'user':ctx.user(), 'filectxs':fileCtxs, } changesets.append(changeset) c = Context({ 'changesets': changesets, }) tmplt = loader.get_template('web/index.html') return HttpResponse(tmplt.render(c)) A: localrepo.status() can take contexts as argument (node1 and node2). See http://hg.intevation.org/mercurial/crew/file/6505773080e4/mercurial/localrepo.py#l973
Use Mercurial API to Get Changes to a Repository For a Given Changeset
How can I use the Mercurial API to determine the changes made to a repository for each changeset? I am able to get a list of files relevant to a particular revision, but I cannot figure out how to tell what happened to that file. How can I answer these questions about each file in a changeset: Was it added? Was it deleted? Was it modified? Is there an attribute in the file context that will tell me this (if so, I cannot find it), or there ways to figure this out by other means? Here is my code: def index(request): u = ui.ui() repo = hg.repository(ui.ui(), '/path/to/repo') changes = repo.changelog changesets = [] for change in changes: ctx = repo.changectx(change) fileCtxs = [] for aFile in ctx.files(): if aFile in ctx: for status in repo.status(None, ctx.node()): # I'm hoping this could return A, M, D, ? etc fileCtxs.append(status) changeset = { 'files':ctx.files(), 'rev':str(ctx.rev()), 'desc':ctx.description(), 'user':ctx.user(), 'filectxs':fileCtxs, } changesets.append(changeset) c = Context({ 'changesets': changesets, }) tmplt = loader.get_template('web/index.html') return HttpResponse(tmplt.render(c))
[ "localrepo.status() can take contexts as argument (node1 and node2).\nSee http://hg.intevation.org/mercurial/crew/file/6505773080e4/mercurial/localrepo.py#l973\n" ]
[ 5 ]
[]
[]
[ "changeset", "dvcs", "mercurial", "mercurial_extension", "python" ]
stackoverflow_0002352129_changeset_dvcs_mercurial_mercurial_extension_python.txt
Q: Detect when threads are running in a python application? How can we detect when threads are running in a python application? Motivation: We were recently debugging a large Python application that had several customer supplied modules that were supplied without source code. Unbeknowst to us (and our customer!), one of these modules would launch threads under very specific (and undocumented) conditions. These threads caused unexpected side effects which changed our environment in unexpected ways. The entire debugging scenario would be funny if it wasn't my team stuck with the task of figuring out where the side effects were coming from :) We finally discovered what was happening when one of the threads raised an un-trapped error. Had this not happened, we would still be pulling our hair out. So, this is why we're looking for a way to detect the presence of threads in our application. Here are some possible techniques we came up with and the corresponding challenges: Grep source code for thread/threading. Challenge: We don't always have access to source code. And even if we can find instances of thread creation in the source code, we still want a real-time technique for detecting when threads are currently active. Look for thread or threading in sys.modules. Challenge: Only insures these modules were loaded - doesn't prove that threads are currently running. Monkey-patch the Python standard thread/threading library to leave us clues as to when threads have been created. Challenge: Only tells us whether threads have been created - does not provide any information about whether threads are currently running. Thanks! Malcolm A: Debugger Usually a debugger can show you all the threads and what each one is executing. If you tell us which debugger you are using, someone can tell you how to see the thread info. If you aren't using a debugger, I highly suggest you start. Debugging multi-threaded programs without a real debugger is quite error-prone and inefficient. Personally, I use WingIDE. Runtime If you're just poking around in the interpreter or trying to detect this situation in your code, perhaps sys._current_frames() might help. It returns the stack frame for each thread.
Detect when threads are running in a python application?
How can we detect when threads are running in a python application? Motivation: We were recently debugging a large Python application that had several customer supplied modules that were supplied without source code. Unbeknowst to us (and our customer!), one of these modules would launch threads under very specific (and undocumented) conditions. These threads caused unexpected side effects which changed our environment in unexpected ways. The entire debugging scenario would be funny if it wasn't my team stuck with the task of figuring out where the side effects were coming from :) We finally discovered what was happening when one of the threads raised an un-trapped error. Had this not happened, we would still be pulling our hair out. So, this is why we're looking for a way to detect the presence of threads in our application. Here are some possible techniques we came up with and the corresponding challenges: Grep source code for thread/threading. Challenge: We don't always have access to source code. And even if we can find instances of thread creation in the source code, we still want a real-time technique for detecting when threads are currently active. Look for thread or threading in sys.modules. Challenge: Only insures these modules were loaded - doesn't prove that threads are currently running. Monkey-patch the Python standard thread/threading library to leave us clues as to when threads have been created. Challenge: Only tells us whether threads have been created - does not provide any information about whether threads are currently running. Thanks! Malcolm
[ "Debugger\nUsually a debugger can show you all the threads and what each one is executing. If you tell us which debugger you are using, someone can tell you how to see the thread info. If you aren't using a debugger, I highly suggest you start. Debugging multi-threaded programs without a real debugger is quite error-prone and inefficient. Personally, I use WingIDE.\nRuntime\nIf you're just poking around in the interpreter or trying to detect this situation in your code, perhaps sys._current_frames() might help. It returns the stack frame for each thread.\n" ]
[ 6 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0002351989_multithreading_python.txt
Q: Attempting to insert an integer from a list into datetime object What I am trying to accomplish is very simple: creating a loop from a range (pretty self explanatory below) that will insert the month into the datetime object. I know %d requires an integer, and I know that 'month' type is int...so I'm kind of stuck as to why I can't substitute my month variable. Here is my code: all_months=range(1,13) for month in all_months: month_start = (datetime.date(2010,'%d',1))%month next_month_begin= datetime.date(2010,'%d',1)%(month+1) month_end=next_month_begin - timedelta(days=1) print month_start print month_end What am I doing wrong? All help appreciated! Thanks A: There are a few things that you need to fix here. EDIT: First, be careful with your range, since you are using month+1 to create next_month_begin, you do not want this to be greater than 12 or you will get an error. Next, when you are trying to create the date object you are passing the month in as a string when you use (datetime.date(2010,'%d',1))%month. Your code probably throwing this error TypeError: an integer is required. You need to give it the integer representing the month, not a string of the integer (there is a difference between 1 and '1'). This is also a simple fix, since you have variable named month that is already an integer, just use that instead of making a string. So you code should be something like: month_start = datetime.date(2010,month,1) I think you can figure out how to apply this to your next_month_begin assignment. The last problem is that you need to use datetime.timedelta to tell Python to look in the datetime module for the timedelta() function -- your program would currently give you an error saying that timedelta is not defined. Let me know if you have any problems applying these fixes. Be sure to include what the error you may be getting as well. A: You've got other answers, but here's a way to get the last day of the month. Adding 31 days will get you into the next month regardless of the number of days in the current month, then moving back to the first and subtracting a day will give the ending date. import datetime for month in range(1,13): month_start = datetime.date(2010,month,1) into_next_month = month_start + datetime.timedelta(days=31) month_end = into_next_month.replace(day=1) - datetime.timedelta(days=1) print month_start,month_end A: month is a variable and you can use it to create the datetime object. I think you want to do the following: month_start = datetime.date(2010, month, 1) next_month_begin = datetime.date(2010, month+1, 1) That will work, because datetime.date() requires 3 integer arguments. '%d' % month would instead format the integer month as string. '%04d' % 3 for example would format the number 3 with 4 digits and leading zeros. But it's important to know, that even the (nearly unformatted) string "3" is different to the number 3 in Python. And you can't write datetime(...) % 3 because the % operator will only work when used on a format string like the previous "%03d" % 3 example and not on a datetime object. But other types might also accept the % operator (not including datetime objects). For example, integers accept the % operator to get the remainder of a division: 3 % 2 # returns 1. But there, the meaning of % is completely different, because the meaning of the operator depends on the types involved. For example, try 3 + 2 and "3" + "2". There, the meaning of + differs (integer addition vs. string concatenation), because the types are different too. A: Check out the calendar module (http://docs.python.org/library/calendar.html). It has batteries included for this sort of thing... You could just do: from calendar import Calendar def start_and_end_days(year, month): cal = Calendar() month_days = [day for day in cal.itermonthdays(year, month) if day.month == month] first_day = month_days[0] last_day = month_days[-1] return (first_day, last_day)
Attempting to insert an integer from a list into datetime object
What I am trying to accomplish is very simple: creating a loop from a range (pretty self explanatory below) that will insert the month into the datetime object. I know %d requires an integer, and I know that 'month' type is int...so I'm kind of stuck as to why I can't substitute my month variable. Here is my code: all_months=range(1,13) for month in all_months: month_start = (datetime.date(2010,'%d',1))%month next_month_begin= datetime.date(2010,'%d',1)%(month+1) month_end=next_month_begin - timedelta(days=1) print month_start print month_end What am I doing wrong? All help appreciated! Thanks
[ "There are a few things that you need to fix here.\nEDIT: First, be careful with your range, since you are using month+1 to create next_month_begin, you do not want this to be greater than 12 or you will get an error.\nNext, when you are trying to create the date object you are passing the month in as a string when you use (datetime.date(2010,'%d',1))%month. Your code probably throwing this error TypeError: an integer is required. \nYou need to give it the integer representing the month, not a string of the integer (there is a difference between 1 and '1'). This is also a simple fix, since you have variable named month that is already an integer, just use that instead of making a string. So you code should be something like:\nmonth_start = datetime.date(2010,month,1)\nI think you can figure out how to apply this to your next_month_begin assignment.\nThe last problem is that you need to use datetime.timedelta to tell Python to look in the datetime module for the timedelta() function -- your program would currently give you an error saying that timedelta is not defined.\nLet me know if you have any problems applying these fixes. Be sure to include what the error you may be getting as well.\n", "You've got other answers, but here's a way to get the last day of the month. Adding 31 days will get you into the next month regardless of the number of days in the current month, then moving back to the first and subtracting a day will give the ending date.\nimport datetime\nfor month in range(1,13):\n month_start = datetime.date(2010,month,1)\n into_next_month = month_start + datetime.timedelta(days=31)\n month_end = into_next_month.replace(day=1) - datetime.timedelta(days=1)\n print month_start,month_end \n\n", "month is a variable and you can use it to create the datetime object. I think you want to do the following:\nmonth_start = datetime.date(2010, month, 1)\nnext_month_begin = datetime.date(2010, month+1, 1)\n\nThat will work, because datetime.date() requires 3 integer arguments. '%d' % month would instead format the integer month as string. '%04d' % 3 for example would format the number 3 with 4 digits and leading zeros. But it's important to know, that even the (nearly unformatted) string \"3\" is different to the number 3 in Python.\nAnd you can't write datetime(...) % 3 because the % operator will only work when used on a format string like the previous \"%03d\" % 3 example and not on a datetime object.\nBut other types might also accept the % operator (not including datetime objects). For example, integers accept the % operator to get the remainder of a division: 3 % 2 # returns 1. But there, the meaning of % is completely different, because the meaning of the operator depends on the types involved. For example, try 3 + 2 and \"3\" + \"2\". There, the meaning of + differs (integer addition vs. string concatenation), because the types are different too.\n", "Check out the calendar module (http://docs.python.org/library/calendar.html).\nIt has batteries included for this sort of thing...\nYou could just do:\nfrom calendar import Calendar\ndef start_and_end_days(year, month):\n cal = Calendar()\n month_days = [day for day in cal.itermonthdays(year, month) if day.month == month]\n first_day = month_days[0]\n last_day = month_days[-1]\n return (first_day, last_day)\n\n" ]
[ 2, 2, 0, 0 ]
[]
[]
[ "datetime", "python", "range" ]
stackoverflow_0002349551_datetime_python_range.txt
Q: The difference between python dict and tr1::unordered_map in C++ I have a question related to understanding of how python dictionaries work. I remember reading somewhere strings in python are immutable to allow hashing, and it is the same reason why one cannot directly use lists as keys, i.e. the lists are mutable (by supporting .append) and hence they cannot be used as dictionary keys. I wanted to know how does implementation of unordered_map in C++ handles these cases. (since strings in C++ are mutable) A: Keys in all C++ map/set containers are const and thus immutable (after added to the container). Notice that C++ containers are not specific to string keys, you can use any objects, but the constness will prevent modifications after the key is copied to the container.
The difference between python dict and tr1::unordered_map in C++
I have a question related to understanding of how python dictionaries work. I remember reading somewhere strings in python are immutable to allow hashing, and it is the same reason why one cannot directly use lists as keys, i.e. the lists are mutable (by supporting .append) and hence they cannot be used as dictionary keys. I wanted to know how does implementation of unordered_map in C++ handles these cases. (since strings in C++ are mutable)
[ "Keys in all C++ map/set containers are const and thus immutable (after added to the container).\nNotice that C++ containers are not specific to string keys, you can use any objects, but the constness will prevent modifications after the key is copied to the container.\n" ]
[ 8 ]
[]
[]
[ "c++", "dictionary", "hashmap", "python", "tr1" ]
stackoverflow_0002352342_c++_dictionary_hashmap_python_tr1.txt
Q: How to use dicts in Mako templates? Whenever I pass a complicated data structure to Mako, it's hard to iterate it. For example, I pass a dict of dict of list, and to access it in Mako, I have to do something like: % for item in dict1['dict2']['list']: ... %endfor I am wondering if Mako has some mechanism that could replace [] usage to access dictionary elements with simple .? Then I could write the line above as: % for item in dict1.dict2.list: ... %endfor Which is much nicer, isn't it? Thanks, Boda Cydo. A: Simplification of Łukasz' example: class Bunch: def __init__(self, d): for k, v in d.items(): if isinstance(v, dict): v = Bunch(v) self.__dict__[k] = v print Bunch({'a':1, 'b':{'foo':2}}).b.foo See also: http://code.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/ A: class Bunch(dict): def __init__(self, d): dict.__init__(self, d) self.__dict__.update(d) def to_bunch(d): r = {} for k, v in d.items(): if isinstance(v, dict): v = to_bunch(v) r[k] = v return Bunch(r) Pass dict1 to to_bunch function before passing it to Mako template. Unfortunately Mako doesn't provide any hooks to do this automatically.
How to use dicts in Mako templates?
Whenever I pass a complicated data structure to Mako, it's hard to iterate it. For example, I pass a dict of dict of list, and to access it in Mako, I have to do something like: % for item in dict1['dict2']['list']: ... %endfor I am wondering if Mako has some mechanism that could replace [] usage to access dictionary elements with simple .? Then I could write the line above as: % for item in dict1.dict2.list: ... %endfor Which is much nicer, isn't it? Thanks, Boda Cydo.
[ "Simplification of Łukasz' example:\nclass Bunch:\n def __init__(self, d):\n for k, v in d.items():\n if isinstance(v, dict):\n v = Bunch(v)\n self.__dict__[k] = v\n\nprint Bunch({'a':1, 'b':{'foo':2}}).b.foo\n\nSee also: http://code.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/\n", "class Bunch(dict):\n def __init__(self, d):\n dict.__init__(self, d)\n self.__dict__.update(d)\n\ndef to_bunch(d):\n r = {}\n for k, v in d.items():\n if isinstance(v, dict):\n v = to_bunch(v)\n r[k] = v\n return Bunch(r)\n\nPass dict1 to to_bunch function before passing it to Mako template. Unfortunately Mako doesn't provide any hooks to do this automatically.\n" ]
[ 8, 3 ]
[]
[]
[ "mako", "python", "templates" ]
stackoverflow_0002352252_mako_python_templates.txt
Q: What is the proper way to pass errors from classes to rendered html in python I'm performing all my form validation in a class, and would like to be able to get the errors from the class to the rendered html. One approach I was thinking about was to create a global variable "c" that would store all the errors and to set them from within the class, as I still want the individual methods to return false when they fail. Here is some sample code: class User(): def add(self): #Check that e-mail has been completed try: #Validate e-mail address if (isAddressValid(self.email)): c.error = 'Invalid e-mail address' return 0 except NameError: c.error = 'No e-mail address specified' return 0 Is there a better or preferred way to do this? Thanks. A: I like to use a dictionary to hold the errors and warnings. Then I can either show all errors at the top of the form or inline. I also define error and warning variables so I can easily tell the two apart. class User(object): def __init__(self): self.messages = {} def add(self): error = False warning = False #Check that name has a space try: if (self.name.find(' ') == -1): warning = True self.messages['email'] = {'type': 'warning', 'msg': 'Your name has no space.'} except NameError: error = True self.messages['email'] = {'type': 'error', 'msg': 'You have no name.'} #Check that e-mail has been completed try: #Validate e-mail address if (isAddressValid(self.email)): error = True self.messages['email'] = {'type': 'error', 'msg': 'Invalid e-mail address'} except NameError: error = True self.messages['email'] = {'type': 'error', 'msg': 'No e-mail address specified'} return error, warning A: Yes, definitely, and my suggestion is to avoid returning status codes at all. Generally speaking, there is a lot of literature against using status codes and global variables to hold details for handling errors in a high level environment like Python. Ned Batchelder has written a very good article on this topic; I strongly suggest you reading that page for a through lists of reasons why exception handling is usually considered a superior method. But, as we are talking about Python, the official way to communicate exceptions, and errors, is through exception handling. Period. Using any other way, will make your code against the common expectations for Python code, meaning it will be harder to read, and maintain. A: In the context of a web application you could just populate tmpl_context. from pylons import tmpl_context as c from yourproject.lib.base import BaseController, render class MyController(BaseController): def index(self): c.error = 'Invalid e-mail address' return render('/mytemplate.mako') Where 'mytemplate.mako' file content is: % if c.error: error: ${c.error} % endif In generic python code you can: Return a tuple You can return a tuple from your function (it is not preferable way): class Error(Exception): pass def isvalid(something): return False, Error("'%s' is invalid" % (something,)) Example: ok, err = isvalid(object()) if not ok: print err Raise an exception If an immediate caller is not supposed to handle an error from your function then an exception can be used to pass information about the error up the stack. def do_stuff(something): if not something.isready(): raise Error("'%s' is not ready to do stuff" % (something,)) Example: class C(object): def isready(self): return False def run(): # no error handling here do_stuff(C()) # do something else try: run() except Error, e: print e Pass callback def do_stuff(something, onerror=lambda err: None): if not something.isready(): onerror(Error("'%s' is not ready to do stuff" % (something,))) Example: do = lambda: do_stuff(C(), onerror=repeat) def repeat(err): """Repeat until success.""" print err time.sleep(5) do() # possible infinite loop do()
What is the proper way to pass errors from classes to rendered html in python
I'm performing all my form validation in a class, and would like to be able to get the errors from the class to the rendered html. One approach I was thinking about was to create a global variable "c" that would store all the errors and to set them from within the class, as I still want the individual methods to return false when they fail. Here is some sample code: class User(): def add(self): #Check that e-mail has been completed try: #Validate e-mail address if (isAddressValid(self.email)): c.error = 'Invalid e-mail address' return 0 except NameError: c.error = 'No e-mail address specified' return 0 Is there a better or preferred way to do this? Thanks.
[ "I like to use a dictionary to hold the errors and warnings. Then I can either show all errors at the top of the form or inline. I also define error and warning variables so I can easily tell the two apart.\nclass User(object):\n def __init__(self):\n self.messages = {}\n\n def add(self):\n error = False\n warning = False\n\n #Check that name has a space\n try:\n if (self.name.find(' ') == -1):\n warning = True\n self.messages['email'] = {'type': 'warning',\n 'msg': 'Your name has no space.'}\n except NameError:\n error = True\n self.messages['email'] = {'type': 'error',\n 'msg': 'You have no name.'}\n\n #Check that e-mail has been completed\n try:\n #Validate e-mail address\n if (isAddressValid(self.email)):\n error = True\n self.messages['email'] = {'type': 'error',\n 'msg': 'Invalid e-mail address'}\n except NameError:\n error = True\n self.messages['email'] = {'type': 'error',\n 'msg': 'No e-mail address specified'}\n\n return error, warning\n\n", "Yes, definitely, and my suggestion is to avoid returning status codes at all.\nGenerally speaking, there is a lot of literature against using status codes and global variables to hold details for handling errors in a high level environment like Python.\nNed Batchelder has written a very good article on this topic; I strongly suggest you reading that page for a through lists of reasons why exception handling is usually considered a superior method.\nBut, as we are talking about Python, the official way to communicate exceptions, and errors, is through exception handling. Period.\nUsing any other way, will make your code against the common expectations for Python code, meaning it will be harder to read, and maintain.\n", "In the context of a web application you could just populate tmpl_context.\nfrom pylons import tmpl_context as c\nfrom yourproject.lib.base import BaseController, render\n\nclass MyController(BaseController):\n def index(self):\n c.error = 'Invalid e-mail address'\n return render('/mytemplate.mako')\n\nWhere 'mytemplate.mako' file content is:\n% if c.error:\n error: ${c.error}\n% endif\n\nIn generic python code you can:\nReturn a tuple\nYou can return a tuple from your function (it is not preferable way):\nclass Error(Exception):\n pass\n\ndef isvalid(something):\n return False, Error(\"'%s' is invalid\" % (something,))\n\nExample:\nok, err = isvalid(object())\nif not ok:\n print err\n\nRaise an exception\nIf an immediate caller is not supposed to handle an error from your function then an exception can be used to pass information about the error up the stack.\ndef do_stuff(something):\n if not something.isready():\n raise Error(\"'%s' is not ready to do stuff\" % (something,))\n\nExample:\nclass C(object):\n def isready(self):\n return False\n\ndef run():\n # no error handling here\n do_stuff(C()) \n # do something else\n\ntry: run()\nexcept Error, e:\n print e\n\nPass callback\ndef do_stuff(something, onerror=lambda err: None):\n if not something.isready():\n onerror(Error(\"'%s' is not ready to do stuff\" % (something,)))\n\nExample:\ndo = lambda: do_stuff(C(), onerror=repeat)\ndef repeat(err):\n \"\"\"Repeat until success.\"\"\"\n print err\n time.sleep(5) \n do() # possible infinite loop \ndo()\n\n" ]
[ 1, 1, 1 ]
[]
[]
[ "mako", "pylons", "python" ]
stackoverflow_0002352201_mako_pylons_python.txt
Q: What special method in Python handles AttributeError? What special method(s?) should I redefine in my class so that it handled AttributeErrors exceptions and returned a special value in those cases? For example, >>> class MySpecialObject(AttributeErrorHandlingClass): a = 5 b = 9 pass >>> >>> obj = MySpecialObject() >>> >>> obj.nonexistent 'special value' >>> obj.a 5 >>> obj.b 9 I googled for the answer but couldn't find it. A: The example of how to use __getattr__ by Otto Allmendinger overcomplicates its use. You would simply define all the other attributes and—if one is missing—Python will fall back on __getattr__. Example: class C(object): def __init__(self): self.foo = "hi" self.bar = "mom" def __getattr__(self, attr): return "hello world" c = C() print c.foo # hi print c.bar # mom print c.baz # hello world print c.qux # hello world A: You have do override __getattr__, it works like this: class Foo(object): def __init__(self): self.bar = 'bar' def __getattr__(self, attr): return 'special value' foo = Foo() foo.bar # calls Foo.__getattribute__() (defined by object), returns bar foo.baz # calls Foo.__getattribute__(), throws AttributeError, # then calls Foo.__getattr__() which returns 'special value'. A: Your question isn't clear to me, but it sounds like you are looking for __getattr__ and possibly for __setattr__, and __delattr__.
What special method in Python handles AttributeError?
What special method(s?) should I redefine in my class so that it handled AttributeErrors exceptions and returned a special value in those cases? For example, >>> class MySpecialObject(AttributeErrorHandlingClass): a = 5 b = 9 pass >>> >>> obj = MySpecialObject() >>> >>> obj.nonexistent 'special value' >>> obj.a 5 >>> obj.b 9 I googled for the answer but couldn't find it.
[ "The example of how to use __getattr__ by Otto Allmendinger overcomplicates its use. You would simply define all the other attributes and—if one is missing—Python will fall back on __getattr__.\nExample:\nclass C(object):\n def __init__(self):\n self.foo = \"hi\"\n self.bar = \"mom\"\n\n def __getattr__(self, attr):\n return \"hello world\"\n\nc = C()\nprint c.foo # hi\nprint c.bar # mom \nprint c.baz # hello world\nprint c.qux # hello world\n\n", "You have do override __getattr__, it works like this:\nclass Foo(object):\n def __init__(self):\n self.bar = 'bar'\n\n def __getattr__(self, attr):\n return 'special value'\n\nfoo = Foo()\nfoo.bar # calls Foo.__getattribute__() (defined by object), returns bar\nfoo.baz # calls Foo.__getattribute__(), throws AttributeError, \n # then calls Foo.__getattr__() which returns 'special value'. \n\n", "Your question isn't clear to me, but it sounds like you are looking for __getattr__ and possibly for __setattr__, and __delattr__.\n" ]
[ 6, 2, 1 ]
[]
[]
[ "attributeerror", "python" ]
stackoverflow_0002352630_attributeerror_python.txt
Q: Xerces + Python? Does anyone know if there's an available python library compatible with Python2.6 that exposes the Xerces functionality and its XML DOM capabilities? I would define the desired capabilities as: XML DOM select by Xpath & XSLT processor. A: pirxx in theory could match your requirements, but it hasn't been maintained in several years so I'd expect some minor incompatibilities with 2.6 to be likely to show up. However, it might still be worth your while to try it -- perhaps fixing those minor things (if they're indeed minor!) and contributing the fixes upstream (or forking the project if upstream should prove to be totally comatose) might be less work than starting from scratch (which is the only other option I'm aware of).
Xerces + Python?
Does anyone know if there's an available python library compatible with Python2.6 that exposes the Xerces functionality and its XML DOM capabilities? I would define the desired capabilities as: XML DOM select by Xpath & XSLT processor.
[ "pirxx in theory could match your requirements, but it hasn't been maintained in several years so I'd expect some minor incompatibilities with 2.6 to be likely to show up. However, it might still be worth your while to try it -- perhaps fixing those minor things (if they're indeed minor!) and contributing the fixes upstream (or forking the project if upstream should prove to be totally comatose) might be less work than starting from scratch (which is the only other option I'm aware of).\n" ]
[ 1 ]
[]
[]
[ "python", "xerces", "xml", "xpath", "xslt" ]
stackoverflow_0002352512_python_xerces_xml_xpath_xslt.txt
Q: What is a good way to handle database objects in python classes? Should I access global db object directly from within the methods of each class? Or from each method, should I instantiate an instance of the db object? One of my database objects changes depending on the id of the info being accessed so it is created through a function connectToDatabase(id). Should I make this a global function, have it return a database object and instantiate it from each method, or something else? Thanks. A: In this case, like in many others, I prefer dependency injection: have your class (e.g in its __init__) accept the DB connection as an argument. This makes it easier and cleaner to test, lets you switch strategies as needed (e.g. to move to a "pool of DB connections" strategy if you find otherwise you're making too many DB connections at once), and distributes responsibilities more accurately and flexibly. In general, I think of Dependency Injection as probably the most important Design Pattern that was not listed in the great "Gang of 4" book!-) A: SQLAlchemy suggests that a function which creates the session be global. http://www.sqlalchemy.org/docs/reference/orm/sessions.html#sqlalchemy.orm.sessionmaker It is intended that the sessionmaker() function be called within the global scope of an application, and the returned class be made available to the rest of the application as the single class used to instantiate sessions.
What is a good way to handle database objects in python classes?
Should I access global db object directly from within the methods of each class? Or from each method, should I instantiate an instance of the db object? One of my database objects changes depending on the id of the info being accessed so it is created through a function connectToDatabase(id). Should I make this a global function, have it return a database object and instantiate it from each method, or something else? Thanks.
[ "In this case, like in many others, I prefer dependency injection: have your class (e.g in its __init__) accept the DB connection as an argument.\nThis makes it easier and cleaner to test, lets you switch strategies as needed (e.g. to move to a \"pool of DB connections\" strategy if you find otherwise you're making too many DB connections at once), and distributes responsibilities more accurately and flexibly.\nIn general, I think of Dependency Injection as probably the most important Design Pattern that was not listed in the great \"Gang of 4\" book!-)\n", "SQLAlchemy suggests that a function which creates the session be global.\nhttp://www.sqlalchemy.org/docs/reference/orm/sessions.html#sqlalchemy.orm.sessionmaker\n\nIt is intended that the sessionmaker()\n function be called within the global\n scope of an application, and the\n returned class be made available to\n the rest of the application as the\n single class used to instantiate\n sessions.\n\n" ]
[ 2, 1 ]
[]
[]
[ "pylons", "python", "sqlalchemy" ]
stackoverflow_0002352661_pylons_python_sqlalchemy.txt
Q: Custom data types in numpy arrays I'm creating a numpy array which is to be filled with objects of a particular class I've made. I'd like to initialize the array such that it will only ever contain objects of that class. For example, here's what I'd like to do, and what happens if I do it. class Kernel: pass >>> L = np.empty(4,dtype=Kernel) TypeError: data type not understood I can do this: >>> L = np.empty(4,dtype=object) and then assign each element of L as a Kernel object (or any other type of object). It would be so neat were I able to have an array of Kernels, though, from both a programming point of view (type checking) and a mathematical one (operations on sets of functions). Is there any way for me to specify the data type of a numpy array using an arbitrary class? A: If your Kernel class has a predictable amount of member data, then you could define a dtype for it instead of a class. e.g. if it's parameterized by 9 floats and an int, you could do kerneldt = np.dtype([('myintname', np.int32), ('myfloats', np.float64, 9)]) arr = np.empty(dims, dtype=kerneldt) You'll have to do some coercion to turn them into objects of class Kernel every time you want to manipulate methods of a single kernel but that's one way to store the actual data in a NumPy array. If you want to only store a reference, then the object dtype is the best you can do without subclassing ndarray. A: It has to be a Numpy scalar type: http://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars-built-in or a subclass of ndarray: http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html#numpy.ndarray A: As far as I know, enforcing a single type for elements in a numpy.ndarray has to be done manually (unless the array contains Numpy scalars): there is no built-in checking mechanism (your array has dtype=object). If you really want to enforce a single type, you have to subclass ndarray and implement the checks in the appropriate methods (__setitem__, etc.). If you want to implement operations on a set of functions (Kernel objects), you might be able to do so by defining the proper operations directly in your Kernel class. This is what I did for my uncertainties.py module, which handles numpy.ndarrays of numbers with uncertainties.
Custom data types in numpy arrays
I'm creating a numpy array which is to be filled with objects of a particular class I've made. I'd like to initialize the array such that it will only ever contain objects of that class. For example, here's what I'd like to do, and what happens if I do it. class Kernel: pass >>> L = np.empty(4,dtype=Kernel) TypeError: data type not understood I can do this: >>> L = np.empty(4,dtype=object) and then assign each element of L as a Kernel object (or any other type of object). It would be so neat were I able to have an array of Kernels, though, from both a programming point of view (type checking) and a mathematical one (operations on sets of functions). Is there any way for me to specify the data type of a numpy array using an arbitrary class?
[ "If your Kernel class has a predictable amount of member data, then you could define a dtype for it instead of a class. e.g. if it's parameterized by 9 floats and an int, you could do\nkerneldt = np.dtype([('myintname', np.int32), ('myfloats', np.float64, 9)])\narr = np.empty(dims, dtype=kerneldt)\n\nYou'll have to do some coercion to turn them into objects of class Kernel every time you want to manipulate methods of a single kernel but that's one way to store the actual data in a NumPy array. If you want to only store a reference, then the object dtype is the best you can do without subclassing ndarray.\n", "It has to be a Numpy scalar type:\nhttp://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars-built-in\nor a subclass of ndarray:\nhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html#numpy.ndarray\n", "As far as I know, enforcing a single type for elements in a numpy.ndarray has to be done manually (unless the array contains Numpy scalars): there is no built-in checking mechanism (your array has dtype=object). If you really want to enforce a single type, you have to subclass ndarray and implement the checks in the appropriate methods (__setitem__, etc.).\nIf you want to implement operations on a set of functions (Kernel objects), you might be able to do so by defining the proper operations directly in your Kernel class. This is what I did for my uncertainties.py module, which handles numpy.ndarrays of numbers with uncertainties.\n" ]
[ 32, 3, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002350072_numpy_python.txt
Q: Numpy array memory issue I believe I am having a memory issue using numpy arrays. The following code is being run for hours on end: new_data = npy.array([new_x, new_y1, new_y2, new_y3]) private.data = npy.row_stack([private.data, new_data]) where new_x, new_y1, new_y2, new_y3 are floats. After about 5 hours of recording this data every second (more than 72000 floats), the program becomes unresponsive. What I think is happening is some kind of realloc and copy operation that is swamping the process. Does anyone know if this is what is happening? I need a way to record this data without encountering this slowdown issue. There is no way to know even approximately the size of this array beforehand. It does not necessarily need to use a numpy array, but it needs to be something similar. Does anyone know of a good method? A: Use Python lists. Seriously, they grow far more efficiently. This is what they are designed for. They are remarkably efficient in this setting. If you need to create an array out of them at the end (or even occasionally in the midst of this computation), it will be far more efficient to accumulate in a list first. A: Update: I incorporated @EOL's excellent indexing suggestion into the answer. The problem might be the way row_stack grows the destination. You might be better off handling the reallocation yourself. The following code allocates a big empty array, fills it, and grows it as it fills an hour at a time numcols = 4 growsize = 60*60 #60 samples/min * 60 min/hour numrows = 3*growsize #3 hours, to start with private.data = npy.zeros([numrows, numcols]) #alloc one big memory block rowctr = 0 while (recording): private.data[rowctr] = npy.array([new_x, new_y1, new_y2, new_y3]) rowctr += 1 if (rowctr == numrows): #full, grow by another hour's worth of data private.data = npy.row_stack([private.data, npy.zeros([growsize, numcols])]) numrows += growsize This should keep the memory manager from thrashing around too much. I tried this versus row_stack on each iteration and it ran a couple of orders of magnitude faster.
Numpy array memory issue
I believe I am having a memory issue using numpy arrays. The following code is being run for hours on end: new_data = npy.array([new_x, new_y1, new_y2, new_y3]) private.data = npy.row_stack([private.data, new_data]) where new_x, new_y1, new_y2, new_y3 are floats. After about 5 hours of recording this data every second (more than 72000 floats), the program becomes unresponsive. What I think is happening is some kind of realloc and copy operation that is swamping the process. Does anyone know if this is what is happening? I need a way to record this data without encountering this slowdown issue. There is no way to know even approximately the size of this array beforehand. It does not necessarily need to use a numpy array, but it needs to be something similar. Does anyone know of a good method?
[ "Use Python lists. Seriously, they grow far more efficiently. This is what they are designed for. They are remarkably efficient in this setting.\nIf you need to create an array out of them at the end (or even occasionally in the midst of this computation), it will be far more efficient to accumulate in a list first. \n", "Update: I incorporated @EOL's excellent indexing suggestion into the answer.\nThe problem might be the way row_stack grows the destination. You might be better off handling the reallocation yourself. The following code allocates a big empty array, fills it, and grows it as it fills an hour at a time\nnumcols = 4\ngrowsize = 60*60 #60 samples/min * 60 min/hour\nnumrows = 3*growsize #3 hours, to start with\nprivate.data = npy.zeros([numrows, numcols]) #alloc one big memory block\nrowctr = 0\nwhile (recording):\n private.data[rowctr] = npy.array([new_x, new_y1, new_y2, new_y3])\n rowctr += 1\n if (rowctr == numrows): #full, grow by another hour's worth of data\n private.data = npy.row_stack([private.data, npy.zeros([growsize, numcols])])\n numrows += growsize\n\nThis should keep the memory manager from thrashing around too much. I tried this versus row_stack on each iteration and it ran a couple of orders of magnitude faster.\n" ]
[ 3, 2 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0002345518_arrays_numpy_python.txt
Q: How to simplify creating huge data structures in Python I am writing some and I need to pass a complicated data structure to some function. The data structure goes like this: { 'animals': [ 'cows', 'moose', { 'properties': [ 9, 26 ] } ] 'fruits': { 'land': [ 'strawberries', 'other berries' ], 'space': [ 'apples', 'cherries' ] } } This structure looks pretty ugly to me. Can you think of ways how to simplify writing such massive data structures? PS. I made up this structure but my real structure is very similar tho. A: Other languages would solve this problem with objects or structs-- so, something like: class whatever: animals = AnimalObject() fruits = FruitObject() class AnimalObject: animals = ['cows','moose'] properties = [9,26] class FruitObject: land = ['strawberries', 'other berries'] space = ['apples', 'cherries'] Of course, this only works if you know ahead of time what form the data is going to take. If you don't, then maps/lists are your only choice ;-) A: Use objects. You are working with basic types like strings and dictionaries while objects are more powerful. Use function arguments. You can pass the the first-level keys in your dictionary as arguments to your function: def yourfunction(animals, fruits) # do things with fruits and animals pass
How to simplify creating huge data structures in Python
I am writing some and I need to pass a complicated data structure to some function. The data structure goes like this: { 'animals': [ 'cows', 'moose', { 'properties': [ 9, 26 ] } ] 'fruits': { 'land': [ 'strawberries', 'other berries' ], 'space': [ 'apples', 'cherries' ] } } This structure looks pretty ugly to me. Can you think of ways how to simplify writing such massive data structures? PS. I made up this structure but my real structure is very similar tho.
[ "Other languages would solve this problem with objects or structs-- so, something like:\nclass whatever:\n animals = AnimalObject()\n fruits = FruitObject()\n\nclass AnimalObject:\n animals = ['cows','moose']\n properties = [9,26]\n\nclass FruitObject:\n land = ['strawberries', 'other berries']\n space = ['apples', 'cherries']\n\nOf course, this only works if you know ahead of time what form the data is going to take. If you don't, then maps/lists are your only choice ;-)\n", "\nUse objects. You are working with basic types like strings and dictionaries while objects are more powerful.\nUse function arguments. You can pass the the first-level keys in your dictionary as arguments to your function:\n\n\ndef yourfunction(animals, fruits)\n # do things with fruits and animals\n pass\n\n" ]
[ 5, 2 ]
[]
[]
[ "data_structures", "python" ]
stackoverflow_0002352793_data_structures_python.txt
Q: How to add file extensions based on file type on Linux/Unix? This is a question regarding Unix shell scripting (any shell), but any other "standard" scripting language solution would also be appreciated: I have a directory full of files where the filenames are hash values like this: fd73d0cf8ee68073dce270cf7e770b97 fec8047a9186fdcc98fdbfc0ea6075ee These files have different original file types such as png, zip, doc, pdf etc. Can anybody provide a script that would rename the files so they get their appropriate file extension, probably based on the output of the file command? Answer: J.F. Sebastian's script will work for both ouput of the filenames as well as the actual renaming. A: Here's mimetypes' version: #!/usr/bin/env python """It is a `filename -> filename.ext` filter. `ext` is mime-based. """ import fileinput import mimetypes import os import sys from subprocess import Popen, PIPE if len(sys.argv) > 1 and sys.argv[1] == '--rename': do_rename = True del sys.argv[1] else: do_rename = False for filename in (line.rstrip() for line in fileinput.input()): output, _ = Popen(['file', '-bi', filename], stdout=PIPE).communicate() mime = output.split(';', 1)[0].lower().strip() ext = mimetypes.guess_extension(mime, strict=False) if ext is None: ext = os.path.extsep + 'undefined' filename_ext = filename + ext print filename_ext if do_rename: os.rename(filename, filename_ext) Example: $ ls *.file? | python add-ext.py --rename avi.file.avi djvu.file.undefined doc.file.dot gif.file.gif html.file.html ico.file.obj jpg.file.jpe m3u.file.ksh mp3.file.mp3 mpg.file.m1v pdf.file.pdf pdf.file2.pdf pdf.file3.pdf png.file.png tar.bz2.file.undefined Following @Phil H's response that follows @csl' response: #!/usr/bin/env python """It is a `filename -> filename.ext` filter. `ext` is mime-based. """ # Mapping of mime-types to extensions is taken form here: # http://as3corelib.googlecode.com/svn/trunk/src/com/adobe/net/MimeTypeMap.as mime2exts_list = [ ["application/andrew-inset","ez"], ["application/atom+xml","atom"], ["application/mac-binhex40","hqx"], ["application/mac-compactpro","cpt"], ["application/mathml+xml","mathml"], ["application/msword","doc"], ["application/octet-stream","bin","dms","lha","lzh","exe","class","so","dll","dmg"], ["application/oda","oda"], ["application/ogg","ogg"], ["application/pdf","pdf"], ["application/postscript","ai","eps","ps"], ["application/rdf+xml","rdf"], ["application/smil","smi","smil"], ["application/srgs","gram"], ["application/srgs+xml","grxml"], ["application/vnd.adobe.apollo-application-installer-package+zip","air"], ["application/vnd.mif","mif"], ["application/vnd.mozilla.xul+xml","xul"], ["application/vnd.ms-excel","xls"], ["application/vnd.ms-powerpoint","ppt"], ["application/vnd.rn-realmedia","rm"], ["application/vnd.wap.wbxml","wbxml"], ["application/vnd.wap.wmlc","wmlc"], ["application/vnd.wap.wmlscriptc","wmlsc"], ["application/voicexml+xml","vxml"], ["application/x-bcpio","bcpio"], ["application/x-cdlink","vcd"], ["application/x-chess-pgn","pgn"], ["application/x-cpio","cpio"], ["application/x-csh","csh"], ["application/x-director","dcr","dir","dxr"], ["application/x-dvi","dvi"], ["application/x-futuresplash","spl"], ["application/x-gtar","gtar"], ["application/x-hdf","hdf"], ["application/x-javascript","js"], ["application/x-koan","skp","skd","skt","skm"], ["application/x-latex","latex"], ["application/x-netcdf","nc","cdf"], ["application/x-sh","sh"], ["application/x-shar","shar"], ["application/x-shockwave-flash","swf"], ["application/x-stuffit","sit"], ["application/x-sv4cpio","sv4cpio"], ["application/x-sv4crc","sv4crc"], ["application/x-tar","tar"], ["application/x-tcl","tcl"], ["application/x-tex","tex"], ["application/x-texinfo","texinfo","texi"], ["application/x-troff","t","tr","roff"], ["application/x-troff-man","man"], ["application/x-troff-me","me"], ["application/x-troff-ms","ms"], ["application/x-ustar","ustar"], ["application/x-wais-source","src"], ["application/xhtml+xml","xhtml","xht"], ["application/xml","xml","xsl"], ["application/xml-dtd","dtd"], ["application/xslt+xml","xslt"], ["application/zip","zip"], ["audio/basic","au","snd"], ["audio/midi","mid","midi","kar"], ["audio/mpeg","mp3","mpga","mp2"], ["audio/x-aiff","aif","aiff","aifc"], ["audio/x-mpegurl","m3u"], ["audio/x-pn-realaudio","ram","ra"], ["audio/x-wav","wav"], ["chemical/x-pdb","pdb"], ["chemical/x-xyz","xyz"], ["image/bmp","bmp"], ["image/cgm","cgm"], ["image/gif","gif"], ["image/ief","ief"], ["image/jpeg","jpg","jpeg","jpe"], ["image/png","png"], ["image/svg+xml","svg"], ["image/tiff","tiff","tif"], ["image/vnd.djvu","djvu","djv"], ["image/vnd.wap.wbmp","wbmp"], ["image/x-cmu-raster","ras"], ["image/x-icon","ico"], ["image/x-portable-anymap","pnm"], ["image/x-portable-bitmap","pbm"], ["image/x-portable-graymap","pgm"], ["image/x-portable-pixmap","ppm"], ["image/x-rgb","rgb"], ["image/x-xbitmap","xbm"], ["image/x-xpixmap","xpm"], ["image/x-xwindowdump","xwd"], ["model/iges","igs","iges"], ["model/mesh","msh","mesh","silo"], ["model/vrml","wrl","vrml"], ["text/calendar","ics","ifb"], ["text/css","css"], ["text/html","html","htm"], ["text/plain","txt","asc"], ["text/richtext","rtx"], ["text/rtf","rtf"], ["text/sgml","sgml","sgm"], ["text/tab-separated-values","tsv"], ["text/vnd.wap.wml","wml"], ["text/vnd.wap.wmlscript","wmls"], ["text/x-setext","etx"], ["video/mpeg","mpg","mpeg","mpe"], ["video/quicktime","mov","qt"], ["video/vnd.mpegurl","m4u","mxu"], ["video/x-flv","flv"], ["video/x-msvideo","avi"], ["video/x-sgi-movie","movie"], ["x-conference/x-cooltalk","ice"]] #NOTE: take only the first extension mime2ext = dict(x[:2] for x in mime2exts_list) if __name__ == '__main__': import fileinput, os.path from subprocess import Popen, PIPE for filename in (line.rstrip() for line in fileinput.input()): output, _ = Popen(['file', '-bi', filename], stdout=PIPE).communicate() mime = output.split(';', 1)[0].lower().strip() print filename + os.path.extsep + mime2ext.get(mime, 'undefined') Here's a snippet for old python's versions (not tested): #NOTE: take only the first extension mime2ext = {} for x in mime2exts_list: mime2ext[x[0]] = x[1] if __name__ == '__main__': import os import sys # this version supports only stdin (part of fileinput.input() functionality) lines = sys.stdin.read().split('\n') for line in lines: filename = line.rstrip() output = os.popen('file -bi ' + filename).read() mime = output.split(';')[0].lower().strip() try: ext = mime2ext[mime] except KeyError: ext = 'undefined' print filename + '.' + ext It should work on Python 2.3.5 (I guess). A: You can use file -i filename to get a MIME-type. You could potentially lookup the type in a list and then append an extension. You can find a list of MIME-types and example file extensions on the net. A: Following csl's response: You can use file -i filename to get a MIME-type. You could potentially lookup the type in a list and then append an extension. You can find list of MIME-types and suggested file extensions on the net. I'd suggest you write a script that takes the output of file -i filename, and returns an extension (split on spaces, find the '/', look up that term in a table file) in your language of choice - a few lines at most. Then you can do something like: ls | while read f; do mv "$f" "$f".`file -i "$f" | get_extension.py`; done in bash, or throw that in a bash script. Or make the get_extension script bigger, but that makes it less useful next time you want the relevant extension. Edit: change from for f in * to ls | while read f because the latter handles filenames with spaces in (a particular nightmare on Windows). A: Of course, it should be added that deciding on a MIME type just based on file(1) output can be very inaccurate/vague (what's "data" ?) or even completely incorrect... A: Agreeing with Keltia, and elaborating some on his answer: Take care -- some filetypes may be problematic. JPEG2000, for example. And others might return too much info given the "file" command without any option tags. The way to avoid this is to use "file -b" for a brief return of information.BZT
How to add file extensions based on file type on Linux/Unix?
This is a question regarding Unix shell scripting (any shell), but any other "standard" scripting language solution would also be appreciated: I have a directory full of files where the filenames are hash values like this: fd73d0cf8ee68073dce270cf7e770b97 fec8047a9186fdcc98fdbfc0ea6075ee These files have different original file types such as png, zip, doc, pdf etc. Can anybody provide a script that would rename the files so they get their appropriate file extension, probably based on the output of the file command? Answer: J.F. Sebastian's script will work for both ouput of the filenames as well as the actual renaming.
[ "Here's mimetypes' version:\n#!/usr/bin/env python\n\"\"\"It is a `filename -> filename.ext` filter. \n\n `ext` is mime-based.\n\n\"\"\"\nimport fileinput\nimport mimetypes\nimport os\nimport sys\nfrom subprocess import Popen, PIPE\n\nif len(sys.argv) > 1 and sys.argv[1] == '--rename':\n do_rename = True\n del sys.argv[1]\nelse:\n do_rename = False \n\nfor filename in (line.rstrip() for line in fileinput.input()):\n output, _ = Popen(['file', '-bi', filename], stdout=PIPE).communicate()\n mime = output.split(';', 1)[0].lower().strip()\n ext = mimetypes.guess_extension(mime, strict=False)\n if ext is None:\n ext = os.path.extsep + 'undefined'\n filename_ext = filename + ext\n print filename_ext\n if do_rename:\n os.rename(filename, filename_ext)\n\nExample:\n\n$ ls *.file? | python add-ext.py --rename\navi.file.avi\ndjvu.file.undefined\ndoc.file.dot\ngif.file.gif\nhtml.file.html\nico.file.obj\njpg.file.jpe\nm3u.file.ksh\nmp3.file.mp3\nmpg.file.m1v\npdf.file.pdf\npdf.file2.pdf\npdf.file3.pdf\npng.file.png\ntar.bz2.file.undefined\n\n\nFollowing @Phil H's response that follows @csl' response:\n#!/usr/bin/env python\n\"\"\"It is a `filename -> filename.ext` filter. \n\n `ext` is mime-based.\n\"\"\"\n# Mapping of mime-types to extensions is taken form here:\n# http://as3corelib.googlecode.com/svn/trunk/src/com/adobe/net/MimeTypeMap.as\nmime2exts_list = [\n [\"application/andrew-inset\",\"ez\"],\n [\"application/atom+xml\",\"atom\"],\n [\"application/mac-binhex40\",\"hqx\"],\n [\"application/mac-compactpro\",\"cpt\"],\n [\"application/mathml+xml\",\"mathml\"],\n [\"application/msword\",\"doc\"],\n [\"application/octet-stream\",\"bin\",\"dms\",\"lha\",\"lzh\",\"exe\",\"class\",\"so\",\"dll\",\"dmg\"],\n [\"application/oda\",\"oda\"],\n [\"application/ogg\",\"ogg\"],\n [\"application/pdf\",\"pdf\"],\n [\"application/postscript\",\"ai\",\"eps\",\"ps\"],\n [\"application/rdf+xml\",\"rdf\"],\n [\"application/smil\",\"smi\",\"smil\"],\n [\"application/srgs\",\"gram\"],\n [\"application/srgs+xml\",\"grxml\"],\n [\"application/vnd.adobe.apollo-application-installer-package+zip\",\"air\"],\n [\"application/vnd.mif\",\"mif\"],\n [\"application/vnd.mozilla.xul+xml\",\"xul\"],\n [\"application/vnd.ms-excel\",\"xls\"],\n [\"application/vnd.ms-powerpoint\",\"ppt\"],\n [\"application/vnd.rn-realmedia\",\"rm\"],\n [\"application/vnd.wap.wbxml\",\"wbxml\"],\n [\"application/vnd.wap.wmlc\",\"wmlc\"],\n [\"application/vnd.wap.wmlscriptc\",\"wmlsc\"],\n [\"application/voicexml+xml\",\"vxml\"],\n [\"application/x-bcpio\",\"bcpio\"],\n [\"application/x-cdlink\",\"vcd\"],\n [\"application/x-chess-pgn\",\"pgn\"],\n [\"application/x-cpio\",\"cpio\"],\n [\"application/x-csh\",\"csh\"],\n [\"application/x-director\",\"dcr\",\"dir\",\"dxr\"],\n [\"application/x-dvi\",\"dvi\"],\n [\"application/x-futuresplash\",\"spl\"],\n [\"application/x-gtar\",\"gtar\"],\n [\"application/x-hdf\",\"hdf\"],\n [\"application/x-javascript\",\"js\"],\n [\"application/x-koan\",\"skp\",\"skd\",\"skt\",\"skm\"],\n [\"application/x-latex\",\"latex\"],\n [\"application/x-netcdf\",\"nc\",\"cdf\"],\n [\"application/x-sh\",\"sh\"],\n [\"application/x-shar\",\"shar\"],\n [\"application/x-shockwave-flash\",\"swf\"],\n [\"application/x-stuffit\",\"sit\"],\n [\"application/x-sv4cpio\",\"sv4cpio\"],\n [\"application/x-sv4crc\",\"sv4crc\"],\n [\"application/x-tar\",\"tar\"],\n [\"application/x-tcl\",\"tcl\"],\n [\"application/x-tex\",\"tex\"],\n [\"application/x-texinfo\",\"texinfo\",\"texi\"],\n [\"application/x-troff\",\"t\",\"tr\",\"roff\"],\n [\"application/x-troff-man\",\"man\"],\n [\"application/x-troff-me\",\"me\"],\n [\"application/x-troff-ms\",\"ms\"],\n [\"application/x-ustar\",\"ustar\"],\n [\"application/x-wais-source\",\"src\"],\n [\"application/xhtml+xml\",\"xhtml\",\"xht\"],\n [\"application/xml\",\"xml\",\"xsl\"],\n [\"application/xml-dtd\",\"dtd\"],\n [\"application/xslt+xml\",\"xslt\"],\n [\"application/zip\",\"zip\"],\n [\"audio/basic\",\"au\",\"snd\"],\n [\"audio/midi\",\"mid\",\"midi\",\"kar\"],\n [\"audio/mpeg\",\"mp3\",\"mpga\",\"mp2\"],\n [\"audio/x-aiff\",\"aif\",\"aiff\",\"aifc\"],\n [\"audio/x-mpegurl\",\"m3u\"],\n [\"audio/x-pn-realaudio\",\"ram\",\"ra\"],\n [\"audio/x-wav\",\"wav\"],\n [\"chemical/x-pdb\",\"pdb\"],\n [\"chemical/x-xyz\",\"xyz\"],\n [\"image/bmp\",\"bmp\"],\n [\"image/cgm\",\"cgm\"],\n [\"image/gif\",\"gif\"],\n [\"image/ief\",\"ief\"],\n [\"image/jpeg\",\"jpg\",\"jpeg\",\"jpe\"],\n [\"image/png\",\"png\"],\n [\"image/svg+xml\",\"svg\"],\n [\"image/tiff\",\"tiff\",\"tif\"],\n [\"image/vnd.djvu\",\"djvu\",\"djv\"],\n [\"image/vnd.wap.wbmp\",\"wbmp\"],\n [\"image/x-cmu-raster\",\"ras\"],\n [\"image/x-icon\",\"ico\"],\n [\"image/x-portable-anymap\",\"pnm\"],\n [\"image/x-portable-bitmap\",\"pbm\"],\n [\"image/x-portable-graymap\",\"pgm\"],\n [\"image/x-portable-pixmap\",\"ppm\"],\n [\"image/x-rgb\",\"rgb\"],\n [\"image/x-xbitmap\",\"xbm\"],\n [\"image/x-xpixmap\",\"xpm\"],\n [\"image/x-xwindowdump\",\"xwd\"],\n [\"model/iges\",\"igs\",\"iges\"],\n [\"model/mesh\",\"msh\",\"mesh\",\"silo\"],\n [\"model/vrml\",\"wrl\",\"vrml\"],\n [\"text/calendar\",\"ics\",\"ifb\"],\n [\"text/css\",\"css\"],\n [\"text/html\",\"html\",\"htm\"],\n [\"text/plain\",\"txt\",\"asc\"],\n [\"text/richtext\",\"rtx\"],\n [\"text/rtf\",\"rtf\"],\n [\"text/sgml\",\"sgml\",\"sgm\"],\n [\"text/tab-separated-values\",\"tsv\"],\n [\"text/vnd.wap.wml\",\"wml\"],\n [\"text/vnd.wap.wmlscript\",\"wmls\"],\n [\"text/x-setext\",\"etx\"],\n [\"video/mpeg\",\"mpg\",\"mpeg\",\"mpe\"],\n [\"video/quicktime\",\"mov\",\"qt\"],\n [\"video/vnd.mpegurl\",\"m4u\",\"mxu\"],\n [\"video/x-flv\",\"flv\"],\n [\"video/x-msvideo\",\"avi\"],\n [\"video/x-sgi-movie\",\"movie\"],\n [\"x-conference/x-cooltalk\",\"ice\"]]\n\n#NOTE: take only the first extension\nmime2ext = dict(x[:2] for x in mime2exts_list)\n\nif __name__ == '__main__':\n import fileinput, os.path\n from subprocess import Popen, PIPE\n\n for filename in (line.rstrip() for line in fileinput.input()):\n output, _ = Popen(['file', '-bi', filename], stdout=PIPE).communicate()\n mime = output.split(';', 1)[0].lower().strip()\n print filename + os.path.extsep + mime2ext.get(mime, 'undefined')\n\n\nHere's a snippet for old python's versions (not tested):\n#NOTE: take only the first extension\nmime2ext = {}\nfor x in mime2exts_list:\n mime2ext[x[0]] = x[1]\n\nif __name__ == '__main__':\n import os\n import sys\n\n # this version supports only stdin (part of fileinput.input() functionality)\n lines = sys.stdin.read().split('\\n')\n for line in lines:\n filename = line.rstrip()\n output = os.popen('file -bi ' + filename).read() \n mime = output.split(';')[0].lower().strip()\n try: ext = mime2ext[mime]\n except KeyError:\n ext = 'undefined'\n print filename + '.' + ext\n\nIt should work on Python 2.3.5 (I guess).\n", "You can use\nfile -i filename\n\nto get a MIME-type. You could potentially lookup the type in a list and then append an extension. You can find a list of MIME-types and example file extensions on the net.\n", "Following csl's response:\n\nYou can use\nfile -i filename\n\nto get a MIME-type.\n You could potentially lookup the type\n in a list and then append an\n extension. You can find list of\n MIME-types and suggested file\n extensions on the net.\n\nI'd suggest you write a script that takes the output of file -i filename, and returns an extension (split on spaces, find the '/', look up that term in a table file) in your language of choice - a few lines at most. Then you can do something like:\nls | while read f; do mv \"$f\" \"$f\".`file -i \"$f\" | get_extension.py`; done\n\nin bash, or throw that in a bash script. Or make the get_extension script bigger, but that makes it less useful next time you want the relevant extension.\nEdit: change from for f in * to ls | while read f because the latter handles filenames with spaces in (a particular nightmare on Windows).\n", "Of course, it should be added that deciding on a MIME type just based on file(1) output can be very inaccurate/vague (what's \"data\" ?) or even completely incorrect...\n", "Agreeing with Keltia, and elaborating some on his answer:\nTake care -- some filetypes may be problematic.\nJPEG2000, for example.\nAnd others might return too much info given the \"file\" command without any option tags. The way to avoid this is to use \"file -b\" for a brief return of information.BZT\n" ]
[ 18, 12, 7, 2, 0 ]
[]
[]
[ "bash", "linux", "python", "shell", "unix" ]
stackoverflow_0000352837_bash_linux_python_shell_unix.txt
Q: Have to Restart Apache When Using Django On Apache with mod_wsgi I'm creating a web app with Django. Since I'm very familiar with Apache I setup my development environment to have Django run through Apache using mod_wsgi. The only annoyance I have with this is that I have to restart Apache everytime I change my code. Is there a way around this? A: mod_wsgi is great for production but I think the included server is better for development. Anyway you should read this about automatic reloading of source code.
Have to Restart Apache When Using Django On Apache with mod_wsgi
I'm creating a web app with Django. Since I'm very familiar with Apache I setup my development environment to have Django run through Apache using mod_wsgi. The only annoyance I have with this is that I have to restart Apache everytime I change my code. Is there a way around this?
[ "mod_wsgi is great for production but I think the included server is better for development.\nAnyway you should read this about automatic reloading of source code.\n" ]
[ 15 ]
[ "I feel like this is really just one of those things most people deal with. It's really not that big of a deal. I made a bash script to make this as easy as possible. I name it 'ra' (reload apache) so it's short and quick. The following works for most apache installs (on UNIX-based systems):\n#!/bin/bash\nsudo /etc/init.d/apache2 reload\n\nYou could probably use some kind of tool to bind this to a key shortcut/foot pedeal/cron.\n" ]
[ -4 ]
[ "apache", "django", "mod_wsgi", "python", "restart" ]
stackoverflow_0002353012_apache_django_mod_wsgi_python_restart.txt
Q: Python 3 object construction: which is the most Pythonic / the accepted way? Having a background in Java, which is very verbose and strict, I find the ability to mutate Python objects as to give them with fields other than those presented to the constructor really "ugly". Trying to accustom myself to a Pythonic way of thinking, I'm wondering how I should allow my objects to be constructed. My instinct is to have to pass the fields at construction time, such as: def __init__(self, foo, bar, baz=None): self.foo = foo self.bar = bar self.baz = baz But that can become overly verbose and confusing with many fields to pass. To overcome this I assume the best method is to pass one dictionary to the constructor, from which the fields are extracted: def __init__(self, field_map): self.foo = field_map["foo"] self.bar = field_map["bar"] self.baz = field_map["baz"] if baz in field_map else None The other mechanism I can think of is to have the fields added elsewhere, such as: class Blah(object): def __init__(self): pass ... blah = Blah() blah.foo = var1 But as that feels way too loose for me. (I suppose the issue in my head is how I deal with interfaces in Python...) So, to reiterate the question: How I should construct my objects in Python? Is there an accepted convention? A: The first you describe is very common. Some use the shorter class Foo: def __init__(self, foo, bar): self.foo, self.bar = foo, bar Your second approach isn't common, but a similar version is this: class Thing: def __init__(self, **kwargs): self.something = kwargs['something'] #.. which allows to create objects like t = Thing(something=1) This can be further modified to class Thing: def __init__(self, **kwargs): self.__dict__.update(kwargs) allowing t = Thing(a=1, b=2, c=3) print t.a, t.b, t.c # prints 1, 2, 3 As Debilski points out in the comments, the last method is a bit unsafe, you can add a list of accepted parameters like this: class Thing: keywords = 'foo', 'bar', 'snafu', 'fnord' def __init__(self, **kwargs): for kw in self.keywords: setattr(self, kw, kwargs[kw]) There are many variations, there is no common standard that I am aware of. A: I’ve not seen many of your field_maps in real life. I think that would only make sense if you were to use the field_map at some other place in your code as well. Concerning your third example: Even though you don’t need to assign to them (other than None), it is common practice to explicitly declare attributes in the __init__ method, so you’ll easily see what properties your object has. So the following is better than simply having an empty __init__ method (you’ll also get a higher pylint score for that): class Blah(object): def __init__(self): self.foo = None self.bar = None blah = Blah() blah.foo = var1 The problem with this approach is, that your object might be in a not well-defined state after initialisation, because you have not yet defined all of your object’s properties. This depends on your object’s logic (logic in code and in meaning) and how your object works. If it is the case however, I’d advise you not to do it this way. If your object relies on foo and bar to be meaningfully defined, you should really put them inside of your __init__ method. If, however, the properties foo and bar are not mandatory, you’re free to define them afterwards. If readability of the argument lists is an issue for you: Use keyword arguments.
Python 3 object construction: which is the most Pythonic / the accepted way?
Having a background in Java, which is very verbose and strict, I find the ability to mutate Python objects as to give them with fields other than those presented to the constructor really "ugly". Trying to accustom myself to a Pythonic way of thinking, I'm wondering how I should allow my objects to be constructed. My instinct is to have to pass the fields at construction time, such as: def __init__(self, foo, bar, baz=None): self.foo = foo self.bar = bar self.baz = baz But that can become overly verbose and confusing with many fields to pass. To overcome this I assume the best method is to pass one dictionary to the constructor, from which the fields are extracted: def __init__(self, field_map): self.foo = field_map["foo"] self.bar = field_map["bar"] self.baz = field_map["baz"] if baz in field_map else None The other mechanism I can think of is to have the fields added elsewhere, such as: class Blah(object): def __init__(self): pass ... blah = Blah() blah.foo = var1 But as that feels way too loose for me. (I suppose the issue in my head is how I deal with interfaces in Python...) So, to reiterate the question: How I should construct my objects in Python? Is there an accepted convention?
[ "The first you describe is very common. Some use the shorter\nclass Foo:\n def __init__(self, foo, bar):\n self.foo, self.bar = foo, bar\n\nYour second approach isn't common, but a similar version is this:\nclass Thing:\n def __init__(self, **kwargs):\n self.something = kwargs['something']\n #..\n\nwhich allows to create objects like\nt = Thing(something=1)\n\nThis can be further modified to \nclass Thing:\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\nallowing\nt = Thing(a=1, b=2, c=3)\nprint t.a, t.b, t.c # prints 1, 2, 3\n\nAs Debilski points out in the comments, the last method is a bit unsafe, you can add a list of accepted parameters like this:\nclass Thing:\n keywords = 'foo', 'bar', 'snafu', 'fnord'\n def __init__(self, **kwargs):\n for kw in self.keywords:\n setattr(self, kw, kwargs[kw])\n\nThere are many variations, there is no common standard that I am aware of.\n", "I’ve not seen many of your field_maps in real life. I think that would only make sense if you were to use the field_map at some other place in your code as well.\nConcerning your third example: Even though you don’t need to assign to them (other than None), it is common practice to explicitly declare attributes in the __init__ method, so you’ll easily see what properties your object has.\nSo the following is better than simply having an empty __init__ method (you’ll also get a higher pylint score for that):\nclass Blah(object):\n def __init__(self):\n self.foo = None\n self.bar = None\n\nblah = Blah()\nblah.foo = var1\n\nThe problem with this approach is, that your object might be in a not well-defined state after initialisation, because you have not yet defined all of your object’s properties. This depends on your object’s logic (logic in code and in meaning) and how your object works. If it is the case however, I’d advise you not to do it this way. If your object relies on foo and bar to be meaningfully defined, you should really put them inside of your __init__ method.\nIf, however, the properties foo and bar are not mandatory, you’re free to define them afterwards.\nIf readability of the argument lists is an issue for you: Use keyword arguments.\n" ]
[ 9, 3 ]
[]
[]
[ "conventions", "python", "python_3.x" ]
stackoverflow_0002353140_conventions_python_python_3.x.txt
Q: Django sending e-mail u'' around headers I wrote a simple contact form for a client in Django. However, whenever it sends e-mail, it wraps the header values in u'' objects. For example, the From: header is From: (u'my@email.com',) Here's the code that sends the message: The form: class ContactForm(forms.Form): name = forms.CharField(max_length=100) sender = forms.EmailField() subject = forms.CharField(max_length=255) message = forms.CharField(widget=forms.widgets.Textarea(attrs={'rows':15, 'cols': 72})) The contact function: def contact(request): RECAPTCHA_PRIVATE_KEY = '******************' captcha_error = '' if request.method == 'POST': form = ContactForm(request.POST) captcha_response = captcha.submit(request.POST.get("recaptcha_challenge_field", None), request.POST.get("recaptcha_response_field", None), RECAPTCHA_PRIVATE_KEY, request.META.get("REMOTE_ADDR", None)) if not captcha_response.is_valid: captcha_error = "&error=%s" % captcha_response.error_code elif form.is_valid(): name = form.cleaned_data['name'], sender = form.cleaned_data['sender'], subject = form.cleaned_data['subject'], message = form.cleaned_data['message'] recipients = ['email@email.com'] try: send_mail(subject, message, sender, recipients) except BadHeaderError: pass flash_message = 'Thank you for contacting us. We will get back to you shortly.' return render_to_response('pages/contact.html', { 'form': form, 'captcha_error': captcha_error, 'message': flash_message }) It sends the e-mail perfectly, I check the appropriate mailbox and the e-mail appears. But these u'' objects prevent the e-mail's subject from appearing correctly and prevents it from being replied to. What am I doing wrong? Thanks in advance. A: Lose the trailing commas here: elif form.is_valid(): name = form.cleaned_data['name'] sender = form.cleaned_data['sender'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message']
Django sending e-mail u'' around headers
I wrote a simple contact form for a client in Django. However, whenever it sends e-mail, it wraps the header values in u'' objects. For example, the From: header is From: (u'my@email.com',) Here's the code that sends the message: The form: class ContactForm(forms.Form): name = forms.CharField(max_length=100) sender = forms.EmailField() subject = forms.CharField(max_length=255) message = forms.CharField(widget=forms.widgets.Textarea(attrs={'rows':15, 'cols': 72})) The contact function: def contact(request): RECAPTCHA_PRIVATE_KEY = '******************' captcha_error = '' if request.method == 'POST': form = ContactForm(request.POST) captcha_response = captcha.submit(request.POST.get("recaptcha_challenge_field", None), request.POST.get("recaptcha_response_field", None), RECAPTCHA_PRIVATE_KEY, request.META.get("REMOTE_ADDR", None)) if not captcha_response.is_valid: captcha_error = "&error=%s" % captcha_response.error_code elif form.is_valid(): name = form.cleaned_data['name'], sender = form.cleaned_data['sender'], subject = form.cleaned_data['subject'], message = form.cleaned_data['message'] recipients = ['email@email.com'] try: send_mail(subject, message, sender, recipients) except BadHeaderError: pass flash_message = 'Thank you for contacting us. We will get back to you shortly.' return render_to_response('pages/contact.html', { 'form': form, 'captcha_error': captcha_error, 'message': flash_message }) It sends the e-mail perfectly, I check the appropriate mailbox and the e-mail appears. But these u'' objects prevent the e-mail's subject from appearing correctly and prevents it from being replied to. What am I doing wrong? Thanks in advance.
[ "Lose the trailing commas here:\n elif form.is_valid():\n name = form.cleaned_data['name']\n sender = form.cleaned_data['sender']\n subject = form.cleaned_data['subject']\n message = form.cleaned_data['message']\n\n" ]
[ 7 ]
[]
[]
[ "django", "email", "python" ]
stackoverflow_0002353136_django_email_python.txt
Q: Sorting based on the count in a related field in Django I have two models, Image and Tag. Each Image object can have more than one Tag associated with it, and I want to find my most frequently used tags. How would I go about this? It seems easy enough but I can't seem to figure it out. A: Django has (only recently) acquired Aggregate support, so now you could do something like this: from django.db.models import Count Tag.objects.annotate(img_count=Count('image')).order_by('img_count')
Sorting based on the count in a related field in Django
I have two models, Image and Tag. Each Image object can have more than one Tag associated with it, and I want to find my most frequently used tags. How would I go about this? It seems easy enough but I can't seem to figure it out.
[ "Django has (only recently) acquired Aggregate support, so now you could do something like this:\nfrom django.db.models import Count\nTag.objects.annotate(img_count=Count('image')).order_by('img_count')\n\n" ]
[ 1 ]
[]
[]
[ "django", "python", "relational_algebra", "sql" ]
stackoverflow_0002353205_django_python_relational_algebra_sql.txt
Q: GAE python database object design for simple list of values I'm really new to database object design so please forgive any weirdness in my question. Basically, I am use Google AppEngine (Python) and contructing an object to track user info. One of these pieces of data is 40 Achievement scores. Do I make a list of ints in the User object for this? Or do I make a separate entity with my user id, the achievement index (0-39) and the score and then do a query to grab these 40 items every time I want to get the user data in total? The latter approach seems more object oriented to me, and certainly better if I extend it to have more than just scores for these 40 achievements. However, considering that I might not extend it, should I even consider just doing a simple list of 40 ints in my user data? I would then forgo doing a query, getting the sorted list of achievements, reading the score from each one just to process a response etc. Is doing this latter approach just such a common practice and hand-waved as not even worth batting an eyelash at in terms of thinking it might be more costly or complex processing wise? A: I like the simple idea of keeping the list of 40 ints, but you can't force feed it into App Engine's existing User class, whose layout is determined by the GAE API (and doesn't include those 40 ints). So that list will inevitably need to live in a separate entity (i.e., each instance of a separate model).
GAE python database object design for simple list of values
I'm really new to database object design so please forgive any weirdness in my question. Basically, I am use Google AppEngine (Python) and contructing an object to track user info. One of these pieces of data is 40 Achievement scores. Do I make a list of ints in the User object for this? Or do I make a separate entity with my user id, the achievement index (0-39) and the score and then do a query to grab these 40 items every time I want to get the user data in total? The latter approach seems more object oriented to me, and certainly better if I extend it to have more than just scores for these 40 achievements. However, considering that I might not extend it, should I even consider just doing a simple list of 40 ints in my user data? I would then forgo doing a query, getting the sorted list of achievements, reading the score from each one just to process a response etc. Is doing this latter approach just such a common practice and hand-waved as not even worth batting an eyelash at in terms of thinking it might be more costly or complex processing wise?
[ "I like the simple idea of keeping the list of 40 ints, but you can't force feed it into App Engine's existing User class, whose layout is determined by the GAE API (and doesn't include those 40 ints). So that list will inevitably need to live in a separate entity (i.e., each instance of a separate model).\n" ]
[ 2 ]
[]
[]
[ "database", "google_app_engine", "object", "python" ]
stackoverflow_0002353135_database_google_app_engine_object_python.txt
Q: Anybody know how to toggle caps lock on/off in Python? I'm trying to toggle caps lock on/off when the two shift buttons are held down for a second. I've tried using the virtkey module, but it's not working. That module does work for other keys though, so I don't think I'm using the module incorrectly. Does anybody have a way for doing this? Just to be clear, I want to actually toggle caps lock on/off and not just the LED. Thanks! A: This works for me (turns the led on and off as well as enable/disable caps) import virtkey v = virtkey.virtkey() v.press_keycode(66) v.release_keycode(66) # first release doesn't release it v.release_keycode(66) Here are some more examples v.press_keycode(66) # turns capslock on v.release_keycode(66) v.press_keycode(66) # turns capslock off v.release_keycode(66) You can also get a toggle like behaviour just using release_keycode v.release_keycode(66) # toggles capslock v.release_keycode(66) # toggles back again capslock A: Funny thing. I gave virtkey a try in the interpreter, and it seemed like it was working. After calling press_keycode(50), my machine acts like caps lock has been pressed (Ubuntu 9.10, python-virtkey .50ubuntu2). If I release the key- release_keycode(50)- it acts like nothing has happened. import virtkey v = virtkey.virtkey() v.press_keycode(50) if run as a script, leaves the caps key pressed for a virtual terminal tab. Very annoying. Have you looked into the xvkbd command? It's an X virtual keyboard with command line options, and worst case you could call it from python. Another idea to look into is xmodmap, which lets you re-map keys in X. See this post on SU for an example.
Anybody know how to toggle caps lock on/off in Python?
I'm trying to toggle caps lock on/off when the two shift buttons are held down for a second. I've tried using the virtkey module, but it's not working. That module does work for other keys though, so I don't think I'm using the module incorrectly. Does anybody have a way for doing this? Just to be clear, I want to actually toggle caps lock on/off and not just the LED. Thanks!
[ "This works for me (turns the led on and off as well as enable/disable caps)\nimport virtkey\n\nv = virtkey.virtkey()\nv.press_keycode(66)\nv.release_keycode(66) # first release doesn't release it\nv.release_keycode(66)\n\nHere are some more examples\nv.press_keycode(66) # turns capslock on\nv.release_keycode(66)\nv.press_keycode(66) # turns capslock off\nv.release_keycode(66)\n\nYou can also get a toggle like behaviour just using release_keycode\nv.release_keycode(66) # toggles capslock\nv.release_keycode(66) # toggles back again capslock\n\n", "Funny thing. I gave virtkey a try in the interpreter, and it seemed like it was working. After calling press_keycode(50), my machine acts like caps lock has been pressed (Ubuntu 9.10, python-virtkey .50ubuntu2). If I release the key- release_keycode(50)- it acts like nothing has happened.\nimport virtkey\n\nv = virtkey.virtkey()\nv.press_keycode(50)\n\nif run as a script, leaves the caps key pressed for a virtual terminal tab. Very annoying.\nHave you looked into the xvkbd command? It's an X virtual keyboard with command line options, and worst case you could call it from python. Another idea to look into is xmodmap, which lets you re-map keys in X. See this post on SU for an example.\n" ]
[ 4, 0 ]
[]
[]
[ "capslock", "keyboard", "linux", "python" ]
stackoverflow_0002353112_capslock_keyboard_linux_python.txt
Q: Is there a better Python bundle for textmate than the one in the bundle repository? At this time Textmate's official Python bundle is really bare bones, especially in comparison to the Ruby bundle. Does anyone know of a Python bundle that is more complete? EDIT: I am fully aware that there are editors and environments that are better suited to Python development, but I am really just interested to see if there is a third party Textmate bundle available. A: I took a look and noticed that there has been a lot of work on Python-related bundles recently. Also, it seems I missed the memo on the best new way to get bundles: Install GetBundles
Is there a better Python bundle for textmate than the one in the bundle repository?
At this time Textmate's official Python bundle is really bare bones, especially in comparison to the Ruby bundle. Does anyone know of a Python bundle that is more complete? EDIT: I am fully aware that there are editors and environments that are better suited to Python development, but I am really just interested to see if there is a third party Textmate bundle available.
[ "I took a look and noticed that there has been a lot of work on Python-related bundles recently. Also, it seems I missed the memo on the best new way to get bundles:\nInstall GetBundles\n" ]
[ 9 ]
[ "I use Komodo Edit and BBEdit for MacOS development.\n\nThey handle Python whitespace perfectly.\nIt's easy to roll my own snippets and components in either tool.\nThey are really good editors for Python.\n\nBut I don't want to discuss these things.\n" ]
[ -18 ]
[ "python", "textmate", "textmatebundles" ]
stackoverflow_0000688245_python_textmate_textmatebundles.txt
Q: CPython - Internally, what is stored on the stack and heap? In C#, Value Types (eg: int, float, etc) are stored on the stack. Method parameters may also be stored on the stack as well. Most everything else, however, is stored on the heap. This includes Lists, objects, etc. I was wondering, does CPython do the same thing internally? What does it store on the stack, and what does it put on the heap? A: All Python objects in the CPython implementation go on the heap. You can read in detail how Python's memory management works here in the documentation: Memory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured internally by the Python memory manager. The Python memory manager has different components which deal with various dynamic storage management aspects, like sharing, segmentation, preallocation or caching. Note that Python itself is just a language, and says nothing about how internals like memory management should work; this is a detail left to implementers. A: Python's runtime only deals in references to objects (which all live in the heap): what goes on Python's stack (as operands and results of its bytecode operations) are always references (to values that live elsewhere).
CPython - Internally, what is stored on the stack and heap?
In C#, Value Types (eg: int, float, etc) are stored on the stack. Method parameters may also be stored on the stack as well. Most everything else, however, is stored on the heap. This includes Lists, objects, etc. I was wondering, does CPython do the same thing internally? What does it store on the stack, and what does it put on the heap?
[ "All Python objects in the CPython implementation go on the heap. You can read in detail how Python's memory management works here in the documentation:\n\nMemory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured internally by the Python memory manager. The Python memory manager has different components which deal with various dynamic storage management aspects, like sharing, segmentation, preallocation or caching.\n\nNote that Python itself is just a language, and says nothing about how internals like memory management should work; this is a detail left to implementers.\n", "Python's runtime only deals in references to objects (which all live in the heap): what goes on Python's stack (as operands and results of its bytecode operations) are always references (to values that live elsewhere).\n" ]
[ 20, 13 ]
[]
[]
[ "cpython", "memory_management", "python", "python_internals" ]
stackoverflow_0002353552_cpython_memory_management_python_python_internals.txt
Q: How can I convert string to "command" in Python? How can I convert this so it could execute? Traceback (most recent call last): File "C:\Users\Shady\Desktop\tet.py", line 14, in <module> exec test File "<string>", line 1 print "hello world" ^ IndentationError: unexpected indent source: test = ''.join(clientIp.split("test6")[1:]) A: You might need to use lstrip() on the string to get rid of any leading whitespace before passing it to exec.
How can I convert string to "command" in Python?
How can I convert this so it could execute? Traceback (most recent call last): File "C:\Users\Shady\Desktop\tet.py", line 14, in <module> exec test File "<string>", line 1 print "hello world" ^ IndentationError: unexpected indent source: test = ''.join(clientIp.split("test6")[1:])
[ "You might need to use lstrip() on the string to get rid of any leading whitespace before passing it to exec.\n" ]
[ 3 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002353736_python_string.txt
Q: How to write modern Python tests? What is the latest way to write Python tests? What modules/frameworks to use? And another question: are doctest tests still of any value? Or should all the tests be written in a more modern testing framework? Thanks, Boda Cydo. A: The usual way is to use the builtin unittest module for creating unit tests and bundling them together to test suites which can be run independently. unittest is very similar to (and inspired by) jUnit and thus very easy to use. If you're interested in the very latest changes, take a look at the new PyCon talk by Michael Foord: PyCon 2010: New and Improved: Coming changes to unittest A: Using the built-in unittest module is as relevant and easy as ever. The other unit testing options, py.test,nose, and twisted.trial are mostly compatible with unittest. Doctests are of the same value they always were—they are great for testing your documentation, not your code. If you are going to put code examples in your docstrings, doctest can assure you keep them correct and up to date. There's nothing worse than trying to reproduce an example and failing, only to later realize it was actually the documentation's fault. A: I don't know much about doctests, but at my university, nose testing is taught and encouraged. Nose can be installed by following this procedure (I'm assuming you're using a PC - Windows OS): install setuptools Run DOS Command Prompt (Start -> All Programs -> Accessories -> Command Prompt) For this step to work, you must be connected to the internet. In DOS, type: C:\Python25\Scripts\easy_install nose If you are on a different OS, check this site EDIT: It's been two years since I originally wrote this post. Now, I've learned of this programming principle called Designing by Contract. This allows a programmer to define preconditions, postconditions and invariants (called contracts) for all functions in their code. The effect is that an error is raised if any of these contracts are violated. The DbC framework that I would recommend for python is called PyContract I have successfully used it in my evolutionary programming framework A: In my current project I'm using unittest, minimock, nose. In the past I've made heavy use of doctests, but in a large projects some tests can get kinda unwieldy, so I tend to reserve usage of doctests for simpler functions. If you are using setuptools or distribute (you should be switching to distribute), you can set up nose as the default test collector so that you can run your tests with "python setup.py test" setup(name='foo', ... test_suite='nose.collector', ... Now running "python setup.py test" will invoke nose, which will crawl your project for things that look like tests and run them, accumulating the results. If you also have doctests in your project, you can run nosetests with the --with-doctest option to enable the doctest plugin. nose also has integration with coverage nosetests --with-coverage. You can also use the --cover-html --cover-html-dir options to generate an HTML coverage report for each module, with each line of code that is not under test highlighted. I wouldn't get too obsessed with getting coverage to report 100% test coverage for all modules. Some code is better left for integration tests, which I'll cover at the end. I have become a huge fan of minimock, as it makes testing code with a lot of external dependencies really easy. While it works really well when paired with doctest, it can be used with any testing framework using the unittest.TraceTracker class. I would encourage you to avoid using it to test all of your code though, since you should still try to write your code so that each translation unit can be tested in isolation without mocking. Sometimes that's not possible though. Here is an (untested) example of such a test using minimock and unittest: # tests/test_foo.py import minimock import unittest import foo class FooTest(unittest2.TestCase): def setUp(self): # Track all calls into our mock objects. If we don't use a TraceTracker # then all output will go to stdout, but we want to capture it. self.tracker = minimock.TraceTracker() def tearDown(self): # Restore all objects in global module state that minimock had # replaced. minimock.restore() def test_bar(self): # foo.bar invokes urllib2.urlopen, and then calls read() on the # resultin file object, so we'll use minimock to create a mocked # urllib2. urlopen_result = minimock.Mock('urlobject', tracker=self.tracker) urlopen_result.read = minimock.Mock( 'urlobj.read', tracker=self.tracker, returns='OMG') foo.urllib2.urlopen = minimock.Mock( 'urllib2.urlopen', tracker=self.tracker, returns=urlopen_result) # Now when we call foo.bar(URL) and it invokes # *urllib2.urlopen(URL).read()*, it will not actually send a request # to URL, but will instead give us back the dummy response body 'OMG', # which it then returns. self.assertEquals(foo.bar('http://example.com/foo'), 'OMG') # Now we can get trace info from minimock to verify that our mocked # urllib2 was used as intended. self.tracker has traced our calls to # *urllib2.urlopen()* minimock.assert_same_trace(self.tracker, """\ Called urllib2.urlopen('http://example.com/foo) Called urlobj.read() Called urlobj.close()""") Unit tests shouldn't be the only kinds of tests you write though. They are certainly useful and IMO extremely important if you plan on maintaining this code for any extended period of time. They make refactoring easier and help catch regressions, but they don't really test the interaction between various components and how they interact (if you do it right). When I start getting to the point where I have a mostly finished product with decent test coverage that I intend to release, I like to write at least one integration test that runs the complete program in an isolated environment. I've had a lot of success with this on my current project. I had about 80% unit test coverage, and the rest of the code was stuff like argument parsing, command dispatch and top level application state, which is difficult to cover in unit tests. This program has a lot of external dependencies, hitting about a dozen different web services and interacting with about 6,000 machines in production, so running this in isolation proved kinda difficult. I ended up writing an integration test which spawns a WSGI server written with eventlet and webob that simulates all of the services my program interacts with in production. Then the integration test monkey patches our web service client library to intercept all HTTP requests and send them to the WSGI application. After doing that, it loads a state file that contains a serialized snapshot of the state of the cluster, and invokes the application by calling it's main() function. Now all of the external services my program interacts with are simulated, so that I can run my program as it would be run in production in a repeatable manner. A: The important thing to remember about doctests is that the tests are based on string comparisons, and the way that numbers are rendered as strings will vary on different platforms and even in different python interpreters. Most of my work deals with computations, so I use doctests only to test my examples and my version string. I put a few in the __init__.py since that will show up as the front page of my epydoc-generated API documentation. I use nose for testing, although I'm very interested in checking out the latest changes to py.test.
How to write modern Python tests?
What is the latest way to write Python tests? What modules/frameworks to use? And another question: are doctest tests still of any value? Or should all the tests be written in a more modern testing framework? Thanks, Boda Cydo.
[ "The usual way is to use the builtin unittest module for creating unit tests and bundling them together to test suites which can be run independently. unittest is very similar to (and inspired by) jUnit and thus very easy to use.\nIf you're interested in the very latest changes, take a look at the new PyCon talk by Michael Foord:\nPyCon 2010: New and Improved: Coming changes to unittest\n", "Using the built-in unittest module is as relevant and easy as ever. The other unit testing options, py.test,nose, and twisted.trial are mostly compatible with unittest. \nDoctests are of the same value they always were—they are great for testing your documentation, not your code. If you are going to put code examples in your docstrings, doctest can assure you keep them correct and up to date. There's nothing worse than trying to reproduce an example and failing, only to later realize it was actually the documentation's fault.\n", "I don't know much about doctests, but at my university, nose testing is taught and encouraged.\nNose can be installed by following this procedure (I'm assuming you're using a PC - Windows OS):\n\ninstall setuptools\nRun DOS Command Prompt (Start -> All Programs -> Accessories -> Command Prompt)\nFor this step to work, you must be connected to the internet. In DOS, type: C:\\Python25\\Scripts\\easy_install nose\n\nIf you are on a different OS, check this site\nEDIT:\nIt's been two years since I originally wrote this post. Now, I've learned of this programming principle called Designing by Contract. This allows a programmer to define preconditions, postconditions and invariants (called contracts) for all functions in their code. The effect is that an error is raised if any of these contracts are violated.\nThe DbC framework that I would recommend for python is called PyContract I have successfully used it in my evolutionary programming framework\n", "In my current project I'm using unittest, minimock, nose. In the past I've made heavy use of doctests, but in a large projects some tests can get kinda unwieldy, so I tend to reserve usage of doctests for simpler functions.\nIf you are using setuptools or distribute (you should be switching to distribute), you can set up nose as the default test collector so that you can run your tests with \"python setup.py test\"\nsetup(name='foo',\n ...\n test_suite='nose.collector',\n ...\n\nNow running \"python setup.py test\" will invoke nose, which will crawl your project for things that look like tests and run them, accumulating the results. If you also have doctests in your project, you can run nosetests with the --with-doctest option to enable the doctest plugin.\nnose also has integration with coverage\nnosetests --with-coverage.\n\nYou can also use the --cover-html --cover-html-dir options to generate an HTML coverage report for each module, with each line of code that is not under test highlighted. I wouldn't get too obsessed with getting coverage to report 100% test coverage for all modules. Some code is better left for integration tests, which I'll cover at the end.\nI have become a huge fan of minimock, as it makes testing code with a lot of external dependencies really easy. While it works really well when paired with doctest, it can be used with any testing framework using the unittest.TraceTracker class. I would encourage you to avoid using it to test all of your code though, since you should still try to write your code so that each translation unit can be tested in isolation without mocking. Sometimes that's not possible though.\nHere is an (untested) example of such a test using minimock and unittest:\n# tests/test_foo.py\nimport minimock\nimport unittest\n\nimport foo\n\nclass FooTest(unittest2.TestCase):\n def setUp(self):\n # Track all calls into our mock objects. If we don't use a TraceTracker\n # then all output will go to stdout, but we want to capture it.\n self.tracker = minimock.TraceTracker()\n\n def tearDown(self):\n # Restore all objects in global module state that minimock had\n # replaced.\n minimock.restore()\n\n def test_bar(self):\n # foo.bar invokes urllib2.urlopen, and then calls read() on the\n # resultin file object, so we'll use minimock to create a mocked\n # urllib2.\n urlopen_result = minimock.Mock('urlobject', tracker=self.tracker)\n urlopen_result.read = minimock.Mock(\n 'urlobj.read', tracker=self.tracker, returns='OMG')\n foo.urllib2.urlopen = minimock.Mock(\n 'urllib2.urlopen', tracker=self.tracker, returns=urlopen_result)\n\n # Now when we call foo.bar(URL) and it invokes\n # *urllib2.urlopen(URL).read()*, it will not actually send a request\n # to URL, but will instead give us back the dummy response body 'OMG',\n # which it then returns.\n self.assertEquals(foo.bar('http://example.com/foo'), 'OMG')\n\n # Now we can get trace info from minimock to verify that our mocked\n # urllib2 was used as intended. self.tracker has traced our calls to\n # *urllib2.urlopen()*\n minimock.assert_same_trace(self.tracker, \"\"\"\\\nCalled urllib2.urlopen('http://example.com/foo)\nCalled urlobj.read()\nCalled urlobj.close()\"\"\")\n\nUnit tests shouldn't be the only kinds of tests you write though. They are certainly useful and IMO extremely important if you plan on maintaining this code for any extended period of time. They make refactoring easier and help catch regressions, but they don't really test the interaction between various components and how they interact (if you do it right).\nWhen I start getting to the point where I have a mostly finished product with decent test coverage that I intend to release, I like to write at least one integration test that runs the complete program in an isolated environment.\nI've had a lot of success with this on my current project. I had about 80% unit test coverage, and the rest of the code was stuff like argument parsing, command dispatch and top level application state, which is difficult to cover in unit tests. This program has a lot of external dependencies, hitting about a dozen different web services and interacting with about 6,000 machines in production, so running this in isolation proved kinda difficult.\nI ended up writing an integration test which spawns a WSGI server written with eventlet and webob that simulates all of the services my program interacts with in production. Then the integration test monkey patches our web service client library to intercept all HTTP requests and send them to the WSGI application. After doing that, it loads a state file that contains a serialized snapshot of the state of the cluster, and invokes the application by calling it's main() function. Now all of the external services my program interacts with are simulated, so that I can run my program as it would be run in production in a repeatable manner.\n", "The important thing to remember about doctests is that the tests are based on string comparisons, and the way that numbers are rendered as strings will vary on different platforms and even in different python interpreters.\nMost of my work deals with computations, so I use doctests only to test my examples and my version string. I put a few in the __init__.py since that will show up as the front page of my epydoc-generated API documentation.\nI use nose for testing, although I'm very interested in checking out the latest changes to py.test.\n" ]
[ 12, 9, 5, 2, 0 ]
[]
[]
[ "python", "testing" ]
stackoverflow_0002352516_python_testing.txt
Q: How can I verify and create values on the Windows registry with Python? How is the simpler way to verify if the value is already created or create Windows registry values ? A: Use the standard Python library module _winreg (it's renamed to winreg, no leading _, if you're using Python 3). You always start with one of the constant keys named _winreg.HKEYsomething; to see them all, do: >>> import _winreg >>> [k for k in dir(_winreg) if k.startswith('HKEY')] and repeatedly use (to navigate down the keys' tree) functions such as _winreg.Openkey (in a try/except to catch the WindowsError it raises when a key is not present). A: you can use _winreg. here's an example enumerating the startup(Run) import _winreg j=0 startup = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Run") while 1: try: print _winreg.EnumValue(startup,j) j+=1 except : break
How can I verify and create values on the Windows registry with Python?
How is the simpler way to verify if the value is already created or create Windows registry values ?
[ "Use the standard Python library module _winreg (it's renamed to winreg, no leading _, if you're using Python 3).\nYou always start with one of the constant keys named _winreg.HKEYsomething; to see them all, do:\n >>> import _winreg\n >>> [k for k in dir(_winreg) if k.startswith('HKEY')]\n\nand repeatedly use (to navigate down the keys' tree) functions such as _winreg.Openkey (in a try/except to catch the WindowsError it raises when a key is not present).\n", "you can use _winreg. here's an example enumerating the startup(Run)\nimport _winreg\nj=0\nstartup = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run\")\nwhile 1:\n try:\n print _winreg.EnumValue(startup,j)\n j+=1\n except : break \n\n" ]
[ 3, 1 ]
[]
[]
[ "python", "registry" ]
stackoverflow_0002353833_python_registry.txt
Q: Accessing a ServerFactory from the Service in Twisted I've been trying to come up with a decent design for multiple factories access each others information. For example, I have the following services: 1 management web service, a VirtualHost instance (multiple domains) and a built in DNS service. Going through the finger tutorial was very helpful but it lacks some key points. It never has a service accessing or executing a method of a factory. I have a hard time believing everyone is implementing 100% of all their logic inside of a single service, and just using the various factories to call those methods defined in the service. If I wanted to update my DNS records, how would my management service tell the DNS Factory, 'hey reload your authority files'? Any hints on how everyone else is doing this sort of inter-factory inter-service communication? A: Well, after some help from a friend. I figured it out. If you create a multiservice, you can just pass the multiservice object to all your child services (I pass it in the init). Then you do setName('servicename'). Then from another service you can just get the information like so: x = self.multiService.getServiceNamed('servicename') and access it that way. Works like a charm! -omgpants
Accessing a ServerFactory from the Service in Twisted
I've been trying to come up with a decent design for multiple factories access each others information. For example, I have the following services: 1 management web service, a VirtualHost instance (multiple domains) and a built in DNS service. Going through the finger tutorial was very helpful but it lacks some key points. It never has a service accessing or executing a method of a factory. I have a hard time believing everyone is implementing 100% of all their logic inside of a single service, and just using the various factories to call those methods defined in the service. If I wanted to update my DNS records, how would my management service tell the DNS Factory, 'hey reload your authority files'? Any hints on how everyone else is doing this sort of inter-factory inter-service communication?
[ "Well, after some help from a friend. I figured it out. If you create a multiservice, you can just pass the multiservice object to all your child services (I pass it in the init). Then you do setName('servicename'). Then from another service you can just get the information like so: x = self.multiService.getServiceNamed('servicename') and access it that way. Works like a charm!\n-omgpants\n" ]
[ 2 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0002350394_python_twisted.txt
Q: Switching mod_python from using python2.4 to python2.5 My goal is to have Apache process a python script and output to the requesting client. My server has both Python2.4 and Python2.5.5 installed. I have Apache configured to correctly process python scripts and tested with a simple test script. However, the real script I am trying to run requires Python2.5.5. Mod_Python seems to be utilizing Python2.4. I am getting the following PythonDebug output when I request the file: Mod_python error: "PythonHandler output.py" ... AssertionError: Please use Python 2.5 or greater Additional information: Checking the Python version from the command line: python -V returns Python 2.5.5 The Apache error log shows the following error type: [Mon Mar 01 14:04:27 2010] [error] [client xxx.xxx.xxx.xxx] PythonHandler output: File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 464, in import_module\n module = imp.load_module(mname, f, p, d) Python2.5.5 seems to be installed to a different directory than Python 2.4: Python2.5.5 /usr/local/lib/python2.5 Python2.4 /usr/lib/python2.4/ Is there any way to update mod_python to use Python2.5.5? A: No. Rebuild it against 2.5.5 instead.
Switching mod_python from using python2.4 to python2.5
My goal is to have Apache process a python script and output to the requesting client. My server has both Python2.4 and Python2.5.5 installed. I have Apache configured to correctly process python scripts and tested with a simple test script. However, the real script I am trying to run requires Python2.5.5. Mod_Python seems to be utilizing Python2.4. I am getting the following PythonDebug output when I request the file: Mod_python error: "PythonHandler output.py" ... AssertionError: Please use Python 2.5 or greater Additional information: Checking the Python version from the command line: python -V returns Python 2.5.5 The Apache error log shows the following error type: [Mon Mar 01 14:04:27 2010] [error] [client xxx.xxx.xxx.xxx] PythonHandler output: File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 464, in import_module\n module = imp.load_module(mname, f, p, d) Python2.5.5 seems to be installed to a different directory than Python 2.4: Python2.5.5 /usr/local/lib/python2.5 Python2.4 /usr/lib/python2.4/ Is there any way to update mod_python to use Python2.5.5?
[ "No. Rebuild it against 2.5.5 instead.\n" ]
[ 0 ]
[]
[]
[ "mod_python", "python" ]
stackoverflow_0002354043_mod_python_python.txt
Q: Remote system event Notification Library Hi I am looking for some sort of library that will allow: - multiple remote applications to register with the system on which events it is interested in - When this event occurs, the system will sent out notification to these remote applications regarding this event - Objects, or hash tables information should be able to be exchanged as well between the system and the remote application The system will be implemented in either Python, or Java, and it will serve as a middleware between a database and external applications. I am not sure if such a library exists, or if it will most suited to implement this as message exchanges. I have heard of twisted, pyro, but not sure of the extent of their capabilities. I had used RPyC previously, but it don't seem to fit the picture naturally. If someone can also point out what is available on the java side as well, I would really appreciated. Plz advise, thnx! A: I think you are looking for a queuing system. Give JMS a try.
Remote system event Notification Library
Hi I am looking for some sort of library that will allow: - multiple remote applications to register with the system on which events it is interested in - When this event occurs, the system will sent out notification to these remote applications regarding this event - Objects, or hash tables information should be able to be exchanged as well between the system and the remote application The system will be implemented in either Python, or Java, and it will serve as a middleware between a database and external applications. I am not sure if such a library exists, or if it will most suited to implement this as message exchanges. I have heard of twisted, pyro, but not sure of the extent of their capabilities. I had used RPyC previously, but it don't seem to fit the picture naturally. If someone can also point out what is available on the java side as well, I would really appreciated. Plz advise, thnx!
[ "I think you are looking for a queuing system. Give JMS a try.\n" ]
[ 1 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002354064_java_python.txt
Q: Controlling distutils from Scons I have a C++ library that I build using Scons which is eventually linked into (among other things) a Python extension. Once I have built the library with scons, I have written a standard setup.py script which I call to build and install the extension. My main problem is that setup.py does not recognize when the library has been rebuilt (only when the extension's code has been changed), so every time I rebuild the library, I have to "clean" the extension before building it again. Also, if I change the directory structure, I would prefer to only need to edit the Scons files. And finally, it's just slightly more convenient to need only call scons instead of having to call scons in addition to setup.py. Does anyone know of a way to integrate distutils into Scons so that it can take advantage of the knowledge Scons has about which files need to be rebuilt? A: You can do any command line from SCons. See Writing Your Own Builders. Then, you can detect any changes for a given file format by writing a scanner. A: I have successfully created SConstruct to compile extensions for Python written in Pyrex. The main idea is to get appropriate C-compiler flags from distutils and then setup your Environment. Check this pages on scons wiki: http://www.scons.org/wiki/PythonExtensions http://www.scons.org/wiki/PyrexPythonExtensions
Controlling distutils from Scons
I have a C++ library that I build using Scons which is eventually linked into (among other things) a Python extension. Once I have built the library with scons, I have written a standard setup.py script which I call to build and install the extension. My main problem is that setup.py does not recognize when the library has been rebuilt (only when the extension's code has been changed), so every time I rebuild the library, I have to "clean" the extension before building it again. Also, if I change the directory structure, I would prefer to only need to edit the Scons files. And finally, it's just slightly more convenient to need only call scons instead of having to call scons in addition to setup.py. Does anyone know of a way to integrate distutils into Scons so that it can take advantage of the knowledge Scons has about which files need to be rebuilt?
[ "You can do any command line from SCons. See Writing Your Own Builders. Then, you can detect any changes for a given file format by writing a scanner.\n", "I have successfully created SConstruct to compile extensions for Python written in Pyrex. The main idea is to get appropriate C-compiler flags from distutils and then setup your Environment.\nCheck this pages on scons wiki:\n\nhttp://www.scons.org/wiki/PythonExtensions\nhttp://www.scons.org/wiki/PyrexPythonExtensions\n\n" ]
[ 1, 0 ]
[]
[]
[ "distutils", "python", "scons" ]
stackoverflow_0002351553_distutils_python_scons.txt
Q: GoogleAppEngine web proxy Does anyone know of a simple open source proxy capable of running on google app engine or where to start in making one? (preferably in python, I'm trying to bypass a site blocking system) A: You can try Mirrorrr: http://code.google.com/p/mirrorrr/ Or Masher Nations, Itube Appengine, Tohr, etc.
GoogleAppEngine web proxy
Does anyone know of a simple open source proxy capable of running on google app engine or where to start in making one? (preferably in python, I'm trying to bypass a site blocking system)
[ "You can try Mirrorrr:\nhttp://code.google.com/p/mirrorrr/\nOr Masher Nations, Itube Appengine, Tohr, etc.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "proxy", "python" ]
stackoverflow_0002354170_google_app_engine_proxy_python.txt
Q: How to force Excel VBA to use updated COM server I'm developing a COM server to be used from Excel VBA. When I update the server (edit code, unregister, re-register) Excel seems to carry on using the original version of the COM server, not the updated version. The only way I have found to get it to use the updated version is to close and re-open Excel, which gets a bit irritating. Is there a way to force Excel to use the newly registered version (maybe some kind of "clear cache" option)? More details: The server is being developed in Python using win32com. In VBA I'm doing something like: set obj=CreateObject("Foo.Bar") obj.baz() Where Foo.Bar is the COM server I have registered in the registry. If I unregister the server then run the VBA code, I get a "can't create object" error from VBA, so it must realise that something is going on. But once I reregister it picks up the old version. Any hints appreciated! Thanks, Andy A: I've found a solution to my problem - the general idea is to set things up so that the main COM server class dynamically loads the rest of the COM server code when it is called. So in Python I've created a COM server class that looks something like: import main_code class COMInterface: _public_methods_ = [ 'method1' ] _reg_progid_ = "My.Test" _reg_clsid_ = "{D6AA2A12-A5CE-4B6C-8603-7952B711728B}" def methods(self, input1,input2,input3): # force python to reload the code that does the actual work reload(main_code) return main_code.Runner().go(input1,input2,input3) The main_code module contains the code that does the actual work and is reloaded each time the COM method is called. This works as long as the inputs don't change. There will presumably be a runtime penalty for this, so might want to remove the reload for the final version, but it works for development purposes. A: Just a suggestion, have you tried to Unload the object? Maybe create a button in your excel spredsheat that force to unload the object. I hope it helps
How to force Excel VBA to use updated COM server
I'm developing a COM server to be used from Excel VBA. When I update the server (edit code, unregister, re-register) Excel seems to carry on using the original version of the COM server, not the updated version. The only way I have found to get it to use the updated version is to close and re-open Excel, which gets a bit irritating. Is there a way to force Excel to use the newly registered version (maybe some kind of "clear cache" option)? More details: The server is being developed in Python using win32com. In VBA I'm doing something like: set obj=CreateObject("Foo.Bar") obj.baz() Where Foo.Bar is the COM server I have registered in the registry. If I unregister the server then run the VBA code, I get a "can't create object" error from VBA, so it must realise that something is going on. But once I reregister it picks up the old version. Any hints appreciated! Thanks, Andy
[ "I've found a solution to my problem - the general idea is to set things up so that the main COM server class dynamically loads the rest of the COM server code when it is called. So in Python I've created a COM server class that looks something like:\nimport main_code\n\nclass COMInterface:\n _public_methods_ = [ 'method1' ]\n _reg_progid_ = \"My.Test\"\n _reg_clsid_ = \"{D6AA2A12-A5CE-4B6C-8603-7952B711728B}\"\n\n def methods(self, input1,input2,input3):\n # force python to reload the code that does the actual work \n reload(main_code)\n return main_code.Runner().go(input1,input2,input3)\n\nThe main_code module contains the code that does the actual work and is reloaded each time the COM method is called. This works as long as the inputs don't change. There will presumably be a runtime penalty for this, so might want to remove the reload for the final version, but it works for development purposes.\n", "Just a suggestion, have you tried to Unload the object? Maybe create a button in your excel spredsheat that force to unload the object.\nI hope it helps\n" ]
[ 2, 0 ]
[]
[]
[ "com", "excel", "python", "vba", "win32com" ]
stackoverflow_0002339993_com_excel_python_vba_win32com.txt
Q: Running Python With STDIN From Bash I have a bash code (Mybash1.sh) where the result I need to pass to another bash code (Mybash2.sh) that contain Python Here are the codes. Mybash1.sh #! /bin/bash # Mybash1.sh cut -f1,3 input_file.txt | sort | ./Mybash2.sh Mybash2.sh is this: #! /bin/bash #Mybash2.sh python mycode.py foo.txt <("$@") > output.txt # do something for output.txt The problem I have is that "output.txt" in Mybash2.sh contain no result. Is there a correct way to execute Python in Mybash2.sh? Note that mycode.py will work if I run it on an intermediate temporary file given from Mybash1.sh. But I wanted to avoid using that, since I will call Mybash2.sh in many instances within Mybash1.sh. Snippet of mycode.py looks like this: if __name__ == "__main__": import sys, os, fileinput progName = os.path.basename(sys.argv[0]) if len(sys.argv) != 3: sys.exit('Usage: ' + progName + ' file1 file2') file1 = fileinput.input(sys.argv[1]) file2 = fileinput.input(sys.argv[2]) # do something for file1 and file2 file1.close() file2.close() A: In python, you want to have file2 = sys.stdin. And then: #! /bin/bash #Mybash2.sh python mycode.py foo.txt > output.txt EDIT: I've just seen the fileinput docs and it seems that if you supply '-' to fileinput.input(), it will read stdin, so without any changes in your Python, this should work: #! /bin/bash #Mybash2.sh python mycode.py foo.txt - > output.txt A: in your myscript1.sh, you are passing a pipeline to myscript2.sh, therefore, its some sort of STDIN for myscript2.sh. You should read that STDIN from myscript2.sh, not taking in input arguments. eg myscript2.sh #!/bin/bash while read myinput do echo "myinput is $myinput" # assuming you are passing each input line from the cut command into Python python mycode.py foo.txt $myinput > output.txt done Lastly, why all these dependencies? can't you do everything in Python, or shell??
Running Python With STDIN From Bash
I have a bash code (Mybash1.sh) where the result I need to pass to another bash code (Mybash2.sh) that contain Python Here are the codes. Mybash1.sh #! /bin/bash # Mybash1.sh cut -f1,3 input_file.txt | sort | ./Mybash2.sh Mybash2.sh is this: #! /bin/bash #Mybash2.sh python mycode.py foo.txt <("$@") > output.txt # do something for output.txt The problem I have is that "output.txt" in Mybash2.sh contain no result. Is there a correct way to execute Python in Mybash2.sh? Note that mycode.py will work if I run it on an intermediate temporary file given from Mybash1.sh. But I wanted to avoid using that, since I will call Mybash2.sh in many instances within Mybash1.sh. Snippet of mycode.py looks like this: if __name__ == "__main__": import sys, os, fileinput progName = os.path.basename(sys.argv[0]) if len(sys.argv) != 3: sys.exit('Usage: ' + progName + ' file1 file2') file1 = fileinput.input(sys.argv[1]) file2 = fileinput.input(sys.argv[2]) # do something for file1 and file2 file1.close() file2.close()
[ "In python, you want to have file2 = sys.stdin.\nAnd then:\n#! /bin/bash\n#Mybash2.sh\npython mycode.py foo.txt > output.txt\n\nEDIT: I've just seen the fileinput docs and it seems that if you supply '-' to fileinput.input(), it will read stdin, so without any changes in your Python, this should work:\n#! /bin/bash\n#Mybash2.sh\npython mycode.py foo.txt - > output.txt\n\n", "in your myscript1.sh, you are passing a pipeline to myscript2.sh, therefore, its some sort of STDIN for myscript2.sh. You should read that STDIN from myscript2.sh, not taking in input arguments. eg myscript2.sh\n#!/bin/bash\nwhile read myinput\ndo\n echo \"myinput is $myinput\"\n # assuming you are passing each input line from the cut command into Python\n python mycode.py foo.txt $myinput > output.txt\ndone\n\nLastly, why all these dependencies? can't you do everything in Python, or shell??\n" ]
[ 2, 0 ]
[]
[]
[ "bash", "linux", "python", "stdin", "unix" ]
stackoverflow_0002354724_bash_linux_python_stdin_unix.txt
Q: Reading from the serial port from C++ or Python on windows I need to read the serial port from windows, using either Python or C++. What API/Library should I use? Can you direct me to a tutorial? Thanks! A: In python you've excellent package pyserial that should be cross-platform (I've used only in GNU/Linux environment). Give it a look, it's very simple to use but very powerful! Of course examples are provided! By the way, if it can be useful here you can find a project of mine which use pyserial, as an extended example. A: In C++: CreateFile("\\\\.\\COM39", ...) SetCommState SetCommTimeouts ReadFile, WriteFile CloseHandle There is also a full documentation on communication resources. A: This is classic article about Win32 serial communications: http://msdn.microsoft.com/en-us/library/ms810467.aspx A: In python it is as simple as importing pyserial and use its open() method (if you are using quite standard system, otherwise you have to adjust a number of parameters to match your environment of course). EDIT: As pointed out by Enrico, pyserial is not a default package in many distributions, so you have to install it by your own. I suggest to install and use easy-install, by setuptools to handle your python addons packages.
Reading from the serial port from C++ or Python on windows
I need to read the serial port from windows, using either Python or C++. What API/Library should I use? Can you direct me to a tutorial? Thanks!
[ "In python you've excellent package pyserial that should be cross-platform (I've used only in GNU/Linux environment).\nGive it a look, it's very simple to use but very powerful!\nOf course examples are provided!\nBy the way, if it can be useful here you can find a project of mine which use pyserial, as an extended example.\n", "In C++:\n\nCreateFile(\"\\\\\\\\.\\\\COM39\", ...)\nSetCommState\nSetCommTimeouts\nReadFile, WriteFile\nCloseHandle\n\nThere is also a full documentation on communication resources.\n", "This is classic article about Win32 serial communications:\nhttp://msdn.microsoft.com/en-us/library/ms810467.aspx\n", "In python it is as simple as importing pyserial and use its open() method (if you are using quite standard system, otherwise you have to adjust a number of parameters to match your environment of course).\nEDIT:\nAs pointed out by Enrico, pyserial is not a default package in many distributions, so you have to install it by your own.\nI suggest to install and use easy-install, by setuptools to handle your python addons packages.\n" ]
[ 6, 5, 3, 3 ]
[]
[]
[ "c++", "python", "serial_port", "windows" ]
stackoverflow_0002354905_c++_python_serial_port_windows.txt
Q: Universal construct for STDIN and Fileinput in Python Code I want my code to be able to accept input from a file AND stdin. What's the construct to do it? I mean a unifying construct that implies file1 = sys.stdin and file1 = fileinput.input(sys.argv[1]) A: import fileinput for line in fileinput.input(): print line A: "Unifying construct" sounds like you want to be able to access either a file provided as an argument or sys.stdin through one variable, so you can just tell functions to get a line from that thing. Luckily, sys.stdin is just another File object, so you have exactly the same functionality with both and it's as easy as a try/except block: try: from sys import argv file1 = open(argv[1]) except: from sys import stdin file1 = stdin You'll get sys.stdin if argv[1] is out of range (IndexError) or can't be opened (IOError). If you just want to concatenate the two, use file1 = sys.argv[1].open().read() + sys.stdin.read()
Universal construct for STDIN and Fileinput in Python Code
I want my code to be able to accept input from a file AND stdin. What's the construct to do it? I mean a unifying construct that implies file1 = sys.stdin and file1 = fileinput.input(sys.argv[1])
[ "import fileinput\nfor line in fileinput.input():\n print line\n\n", "\"Unifying construct\" sounds like you want to be able to access either a file provided as an argument or sys.stdin through one variable, so you can just tell functions to get a line from that thing. Luckily, sys.stdin is just another File object, so you have exactly the same functionality with both and it's as easy as a try/except block:\n\ntry:\n from sys import argv\n file1 = open(argv[1])\nexcept:\n from sys import stdin\n file1 = stdin\n\nYou'll get sys.stdin if argv[1] is out of range (IndexError) or can't be opened (IOError).\nIf you just want to concatenate the two, use file1 = sys.argv[1].open().read() + sys.stdin.read()\n" ]
[ 6, 0 ]
[]
[]
[ "linux", "python", "unix" ]
stackoverflow_0002355007_linux_python_unix.txt
Q: How do I get the URL of an HTTP redirect's target? I am writing client-side Python unit tests to verify whether the HTTP 302 redirects on my Google App Engine site are pointing to the right pages. So far, I have been calling urllib2.urlopen(my_url).geturl(). However, I have encountered 2 issues: the URL returned by geturl() does not appear to include URL query strings like ?k1=v1&k2=v2; how can I see these? (I need to check whether I correctly passed along the visitor's original URL query string to the redirect page.) geturl() shows the final URL after any additional redirects. I just care about the first redirect (the one from my site); I am agnostic to anything after that. For example, let's assume my site is example.com. If a user requests http://www.example.com/somepath/?q=foo, I might want to redirect them to http://www.anothersite.com?q=foo. That other site might do another redirect to http://subdomain.anothersite.com?q=foo, which I can't control or predict. How can I make sure my redirect is correct? A: Use httplib (and look at the return status and Location header of the response) to avoid the "auto-follow redirects" that's impeding your testing. There's a good example here. A: Supply follow_redirects=False to the fetch function, then retrieve the location of the first redirect from the 'location' header in the response, like so: response = urlfetch.fetch(your_url, follow_redirects=False) location = response.headers['Location']
How do I get the URL of an HTTP redirect's target?
I am writing client-side Python unit tests to verify whether the HTTP 302 redirects on my Google App Engine site are pointing to the right pages. So far, I have been calling urllib2.urlopen(my_url).geturl(). However, I have encountered 2 issues: the URL returned by geturl() does not appear to include URL query strings like ?k1=v1&k2=v2; how can I see these? (I need to check whether I correctly passed along the visitor's original URL query string to the redirect page.) geturl() shows the final URL after any additional redirects. I just care about the first redirect (the one from my site); I am agnostic to anything after that. For example, let's assume my site is example.com. If a user requests http://www.example.com/somepath/?q=foo, I might want to redirect them to http://www.anothersite.com?q=foo. That other site might do another redirect to http://subdomain.anothersite.com?q=foo, which I can't control or predict. How can I make sure my redirect is correct?
[ "Use httplib (and look at the return status and Location header of the response) to avoid the \"auto-follow redirects\" that's impeding your testing. There's a good example here.\n", "Supply follow_redirects=False to the fetch function, then retrieve the location of the first redirect from the 'location' header in the response, like so:\nresponse = urlfetch.fetch(your_url, follow_redirects=False)\nlocation = response.headers['Location']\n\n" ]
[ 5, 5 ]
[]
[]
[ "google_app_engine", "http", "python", "redirect" ]
stackoverflow_0002353689_google_app_engine_http_python_redirect.txt
Q: python parsing url after string I want to extract a string from a url (link). That string is in a <h3></h3> tag. link = http://www.test.com/page.html Content of link: <h3>Text here</h3> What would be an elegant way to first get the content/sourcecode of page.html and then exctract the link? Thanks! A: I'd recommend Beatiful Soup. That's a nice parser for botched HTML pages (for the most cases you don't have to worry about the page not being well-formed). A: You can use URLLib2 to retrieve the content of the URL: http://docs.python.org/library/urllib2.html You could then use the HTML parser in the Python libraries to find the right content: http://docs.python.org/library/htmlparser.html A: import urllib2 url="http://www.test.com/page.html" page=urllib2.urlopen(url) data=page.read() for item in data.split("</h3>"): if "<h3>" in item: print item.split("<h3>")[1]
python parsing url after string
I want to extract a string from a url (link). That string is in a <h3></h3> tag. link = http://www.test.com/page.html Content of link: <h3>Text here</h3> What would be an elegant way to first get the content/sourcecode of page.html and then exctract the link? Thanks!
[ "I'd recommend Beatiful Soup. That's a nice parser for botched HTML pages (for the most cases you don't have to worry about the page not being well-formed).\n", "You can use URLLib2 to retrieve the content of the URL:\nhttp://docs.python.org/library/urllib2.html\nYou could then use the HTML parser in the Python libraries to find the right content:\nhttp://docs.python.org/library/htmlparser.html\n", "import urllib2\nurl=\"http://www.test.com/page.html\"\npage=urllib2.urlopen(url)\ndata=page.read()\nfor item in data.split(\"</h3>\"):\n if \"<h3>\" in item:\n print item.split(\"<h3>\")[1]\n\n" ]
[ 2, 1, 1 ]
[ "Provided the text you want is the only <h3>-wrapped text on the page, try:\nfrom urllib2 import urlopen\nfrom re import search\ntext = search(r'(?<=<h3>).+?(?=</h3>)', urlopen(link).read()).group(0)\nIf there are multiple <h3>-wrapped strings you can either put more details into the pattern or use re.finditer()/re.findall()\n" ]
[ -1 ]
[ "parsing", "python", "regex" ]
stackoverflow_0002355177_parsing_python_regex.txt
Q: Access module masked by variable name How do I access a module named x that I masked with a variable named x? A: don't name your variable x or use import ... as style. >>> sys = 2 >>> import sys as s >>> s <module 'sys' (built-in)> >>> sys 2 A: use sys.modules[module_name] ... and you should avoid masking module names: use wisely the import statement e.g. import XYZ as ABC. You can also rely on using a more complete namespace "path" e.g. os.path.xxx A: import x as someotherx
Access module masked by variable name
How do I access a module named x that I masked with a variable named x?
[ "don't name your variable x or use import ... as style.\n>>> sys = 2\n>>> import sys as s\n>>> s\n<module 'sys' (built-in)>\n>>> sys\n2\n\n", "use sys.modules[module_name] ... and you should avoid masking module names: use wisely the import statement e.g. import XYZ as ABC.\nYou can also rely on using a more complete namespace \"path\" e.g. os.path.xxx\n", "import x as someotherx\n\n" ]
[ 3, 1, 0 ]
[]
[]
[ "namespaces", "python" ]
stackoverflow_0002355310_namespaces_python.txt
Q: Python DBAPI time out for connections? I was attempting to test for connection failure, and unfortunately it's not failing if the IP address of the host is fire walled. This is the code: def get_connection(self, conn_data): rtu, hst, prt, usr, pwd, db = conn_data try: self.conn = pgdb.connect(host=hst+":"+prt, user=usr, password=pwd, database=db) self.cur = self.conn.cursor() return True except pgdb.Error as e: logger.exception("Error trying to connect to the server.") return False if self.get_connection(conn_data): # Do stuff here: If I try to connect to a known server but give an incorrect user name, it will trigger the exception and fail. However if I try to connect to a machine that does not respond (firewalled) it never gets passed self.conn = pgdb.connect() How to I wait or test for time out rather than have my app appear to hang when a user mistypes an IP address? A: What you are experiencing is the pain of firewalls, and the timeout is the normal TCP timeout. A: You can usually pass timeout argument in connect function. If it doesn't exist you could try with socket.timeout or default timeout: import socket socket.setdefaulttimeout(10) # sets timeout to 10 seconds This will apply this setting to all connections(socket based) you make and will fail after 10 seconds of waiting.
Python DBAPI time out for connections?
I was attempting to test for connection failure, and unfortunately it's not failing if the IP address of the host is fire walled. This is the code: def get_connection(self, conn_data): rtu, hst, prt, usr, pwd, db = conn_data try: self.conn = pgdb.connect(host=hst+":"+prt, user=usr, password=pwd, database=db) self.cur = self.conn.cursor() return True except pgdb.Error as e: logger.exception("Error trying to connect to the server.") return False if self.get_connection(conn_data): # Do stuff here: If I try to connect to a known server but give an incorrect user name, it will trigger the exception and fail. However if I try to connect to a machine that does not respond (firewalled) it never gets passed self.conn = pgdb.connect() How to I wait or test for time out rather than have my app appear to hang when a user mistypes an IP address?
[ "What you are experiencing is the pain of firewalls, and the timeout is the normal TCP timeout.\n", "You can usually pass timeout argument in connect function. If it doesn't exist you could try with socket.timeout or default timeout:\nimport socket\nsocket.setdefaulttimeout(10) # sets timeout to 10 seconds\n\nThis will apply this setting to all connections(socket based) you make and will fail after 10 seconds of waiting.\n" ]
[ 0, 0 ]
[]
[]
[ "python", "python_db_api" ]
stackoverflow_0002355401_python_python_db_api.txt
Q: Ugly combination of generator expression with for loop The following appears in my Python 2.6 code: for src, dst in ([s,d] for s in universe for d in universe if s != d): Can I do much better? What I particularly don't like is that I'm in effect specifying the same pair twice, once for the for loop and again for the generator expression. I'm uncertain whether I'd prefer: for src, dst in itertools.product(universe, universe): if src != dst: Is there a way to express this loop concisely? universe happens to be a list, if it makes any difference. Order of iteration doesn't matter. A: You could use simple nested for-loops: for src in universe: for dst in universe: if src == dst: continue ... I'd say this is the most easy to read syntax in this case. A: I suggest keeping it entirely functional or entirely with comprehensions. Here's an implementation that's entirely functional. import itertools import operator def inner_product(iterable): "the product of an iterable with itself" return itertools.product(iterable, repeat=2) def same(pair): "does this pair contain two of the same thing?" return operator.is_(*pair) universe = 'abcd' pairs = inner_product(universe) unique_pairs = itertools.ifilterfalse(same, pairs) for pair in unique_pairs: print pair """ ('a', 'b') ('a', 'c') ('a', 'd') ('b', 'a') ('b', 'c') ('b', 'd') ('c', 'a') ('c', 'b') ('c', 'd') ('d', 'a') ('d', 'b') ('d', 'c') """ A: itertools.product can take a "repeat" keyword argument if you want to have the same sequence as more than one parameter: itertools.product(universe, repeat=2) it is a matter of opinion as to whether this is more readable. You could replace your original code with: for (src, dest) in filter(lambda (a,b): a!=b, itertools.product(universe, repeat=2)): ...
Ugly combination of generator expression with for loop
The following appears in my Python 2.6 code: for src, dst in ([s,d] for s in universe for d in universe if s != d): Can I do much better? What I particularly don't like is that I'm in effect specifying the same pair twice, once for the for loop and again for the generator expression. I'm uncertain whether I'd prefer: for src, dst in itertools.product(universe, universe): if src != dst: Is there a way to express this loop concisely? universe happens to be a list, if it makes any difference. Order of iteration doesn't matter.
[ "You could use simple nested for-loops:\nfor src in universe:\n for dst in universe:\n if src == dst:\n continue\n ...\n\nI'd say this is the most easy to read syntax in this case.\n", "I suggest keeping it entirely functional or entirely with comprehensions. Here's an implementation that's entirely functional.\nimport itertools \nimport operator\n\ndef inner_product(iterable):\n \"the product of an iterable with itself\"\n return itertools.product(iterable, repeat=2)\n\ndef same(pair):\n \"does this pair contain two of the same thing?\"\n return operator.is_(*pair)\n\nuniverse = 'abcd'\n\npairs = inner_product(universe)\nunique_pairs = itertools.ifilterfalse(same, pairs)\nfor pair in unique_pairs:\n print pair\n\n\"\"\"\n('a', 'b')\n('a', 'c')\n('a', 'd')\n('b', 'a')\n('b', 'c')\n('b', 'd')\n('c', 'a')\n('c', 'b')\n('c', 'd')\n('d', 'a')\n('d', 'b')\n('d', 'c')\n\"\"\"\n\n", "itertools.product can take a \"repeat\" keyword argument if you want to have the same sequence as more than one parameter:\nitertools.product(universe, repeat=2)\n\nit is a matter of opinion as to whether this is more readable.\nYou could replace your original code with:\nfor (src, dest) in filter(lambda (a,b): a!=b, itertools.product(universe, repeat=2)):\n ...\n\n" ]
[ 5, 3, 1 ]
[]
[]
[ "for_loop", "generator", "python" ]
stackoverflow_0002355542_for_loop_generator_python.txt
Q: Group a string into 3s in a loop (python) I have a nine character string and need to perform operations on groups of three characters in a loop. How would i achieve this in python? A: Maybe something like this? >>> a = "123456789" >>> for grp in [a[:3], a[3:6], a[6:]]: print grp Of course, if you need to generalize, >>> def split3(aString): while len(aString) > 0: yield aString[:3] aString = aString[3:] >>> for c in split3(a): print c A: >>> s = "123456789" >>> import textwrap >>> textwrap.wrap(s,3) ['123', '456', '789'] or you can use itertools import itertools def grouper(n, iterable): args = [iter(iterable)] * n return itertools.izip_longest(*args) for i in grouper(3,"o my gosh"): print i output $ ./python.py ('o', ' ', 'm') ('y', ' ', 'g') ('o', 's', 'h') A: Simplest way: >>> s = "123456789" >>> for group in (s[:3], s[3:6], s[6:]): print group ... 123 456 789 In the more general case, look at: http://code.activestate.com/recipes/303799-chunks/
Group a string into 3s in a loop (python)
I have a nine character string and need to perform operations on groups of three characters in a loop. How would i achieve this in python?
[ "Maybe something like this?\n>>> a = \"123456789\"\n>>> for grp in [a[:3], a[3:6], a[6:]]:\n print grp\n\nOf course, if you need to generalize,\n>>> def split3(aString):\n while len(aString) > 0:\n yield aString[:3]\n aString = aString[3:]\n\n\n>>> for c in split3(a):\n print c\n\n", ">>> s = \"123456789\"\n>>> import textwrap\n>>> textwrap.wrap(s,3)\n['123', '456', '789']\n\nor you can use itertools\nimport itertools\ndef grouper(n, iterable):\n args = [iter(iterable)] * n\n return itertools.izip_longest(*args)\n\nfor i in grouper(3,\"o my gosh\"):\n print i\n\noutput\n$ ./python.py\n('o', ' ', 'm')\n('y', ' ', 'g')\n('o', 's', 'h')\n\n", "Simplest way:\n>>> s = \"123456789\"\n>>> for group in (s[:3], s[3:6], s[6:]): print group\n...\n123\n456\n789\n\nIn the more general case, look at: http://code.activestate.com/recipes/303799-chunks/\n" ]
[ 4, 4, 3 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0002355650_loops_python.txt
Q: How can I create my own corpus in the Python Natural Language Toolkit? I have recently expanded the names corpus in nltk and would like to know how I can turn the two files I have (male.txt, female.txt) in to a corpus so I can access them using the existing nltk.corpus methods. Does anyone have any suggestions? Many thanks, James. A: As the readme says, the names corpus is not in the public domain -- you should send an email with any changes you make to the corpus author (address is in that file). Apart from that detail of law and courtesy, you can simply replace either or both of those files with your own, they're in perfectly simple format (one name per line, comments allowed [[and ignored]] and start with '#'). To install a totally new corpus rather than just tweaking an existing ones, you could start with the docs given here. A: Came to understand how corpus reading works by looking at the source code in nltk.corpus and then looking at the corpora (located in /home/[user]/nltk_data/corpora/names - this will probably be in My Documents for XP and somewhere in User for Win7 users). The structure of the corpus and its related function will give a good understanding of how to use the different corpora available in NLTK. In my case I looked at the names variable in nltk.corpus' source code and was interested in the WordListCorpusReader function as the names corpus is simply a list of words. A: Alex is right, start with the docs, and figure out which corpus reader will work for your corpus. The simple instantiate it, given the path to your corpus file(s). As you'll see in the docs, the builtin corpora are simply instances of particular corpus reader classes. Look thru the code in the nltk.corpus package should be helpful as well.
How can I create my own corpus in the Python Natural Language Toolkit?
I have recently expanded the names corpus in nltk and would like to know how I can turn the two files I have (male.txt, female.txt) in to a corpus so I can access them using the existing nltk.corpus methods. Does anyone have any suggestions? Many thanks, James.
[ "As the readme says, the names corpus is not in the public domain -- you should send an email with any changes you make to the corpus author (address is in that file). Apart from that detail of law and courtesy, you can simply replace either or both of those files with your own, they're in perfectly simple format (one name per line, comments allowed [[and ignored]] and start with '#').\nTo install a totally new corpus rather than just tweaking an existing ones, you could start with the docs given here.\n", "Came to understand how corpus reading works by looking at the source code in nltk.corpus and then looking at the corpora (located in /home/[user]/nltk_data/corpora/names - this will probably be in My Documents for XP and somewhere in User for Win7 users).\nThe structure of the corpus and its related function will give a good understanding of how to use the different corpora available in NLTK.\nIn my case I looked at the names variable in nltk.corpus' source code and was interested in the WordListCorpusReader function as the names corpus is simply a list of words.\n", "Alex is right, start with the docs, and figure out which corpus reader will work for your corpus. The simple instantiate it, given the path to your corpus file(s). As you'll see in the docs, the builtin corpora are simply instances of particular corpus reader classes. Look thru the code in the nltk.corpus package should be helpful as well.\n" ]
[ 4, 1, 0 ]
[]
[]
[ "nlp", "nltk", "python" ]
stackoverflow_0002168793_nlp_nltk_python.txt
Q: python ImportError: No module named primes I'm really new to Python. I'm trying to import a third party module called primes.py. I have placed this module in C:\Python26\Lib (the location where I installed Python). I then have another file which is trying to import this module. The file attempting to import primes is located at C:\Python26. In my Python file I have the following two lines: import primes import sys When I run this file, I get the following error: ImportError: No module named primes Can anyone help me out? A: The module needs to be on your PYTHONPATH or in the same directory as the script, app, or module that is trying to import the module. I'm not a Windows programmer but if you have placed the module in 'C:\Python26\Lib' and your path is set to 'C:\Python26' you need to add '\Python26\Lib' to your PYTHONPATH. I'm not certain on what the syntax would be but it should be something like 'C:\Python26;C:\Python26\Lib'. Assuming everything is the same on Windows, the subdirectories are not searched automatically. I think a more appropriate place to put the module is to place it in 'site-packages', I don't know how this is accomplished on Windows. On *nix systems there is a script 'setup.py' that comes with the package/module, and uses 'setuptools' to build and install the package/module for you. A: you probably should located this under site-packages directory or a private folder instead. Check your sys.path to understand your import paths. A: Put primes.py in the lib/site-packages/ directory. Also: no need to put your own Python files under the installation directory: I'd advise you to put them somewhere else (where it makes sense).
python ImportError: No module named primes
I'm really new to Python. I'm trying to import a third party module called primes.py. I have placed this module in C:\Python26\Lib (the location where I installed Python). I then have another file which is trying to import this module. The file attempting to import primes is located at C:\Python26. In my Python file I have the following two lines: import primes import sys When I run this file, I get the following error: ImportError: No module named primes Can anyone help me out?
[ "The module needs to be on your PYTHONPATH or in the same directory as the script, app, or module that is trying to import the module.\nI'm not a Windows programmer but if you have placed the module in 'C:\\Python26\\Lib' and your path is set to 'C:\\Python26' you need to add '\\Python26\\Lib' to your PYTHONPATH. I'm not certain on what the syntax would be but it should be something like 'C:\\Python26;C:\\Python26\\Lib'. Assuming everything is the same on Windows, the subdirectories are not searched automatically.\nI think a more appropriate place to put the module is to place it in 'site-packages', I don't know how this is accomplished on Windows. On *nix systems there is a script 'setup.py' that comes with the package/module, and uses 'setuptools' to build and install the package/module for you.\n", "you probably should located this under site-packages directory or a private folder instead. Check your sys.path to understand your import paths.\n", "Put primes.py in the lib/site-packages/ directory.\nAlso: no need to put your own Python files under the installation directory: I'd advise you to put them somewhere else (where it makes sense).\n" ]
[ 2, 1, 0 ]
[]
[]
[ "importerror", "python" ]
stackoverflow_0002355953_importerror_python.txt
Q: Tower of hanoi, python -> scheme, shows error. What am I missing? The python implementation import sys def move(src, dst, tmp, num): if num == 1: print 'Move from', src, 'to', dst else: move(src, tmp, dst, num-1) move(src, dst, tmp, 1) move(tmp, dst, src, num-1) move('left', 'right', 'middle', int(sys.argv[1])) Gives the right solution for tower of hanoi. But my scheme port, (define move (lambda (src dst tmp num) (if (= num 1) (printf "Move from ~s to ~s \n" src dst) ((move src tmp dst (- num 1)) (move src dst tmp 1) (move tmp dst src (- num 1)))))) Gives the right solution but in the end throws the following error. procedure application: expected procedure, given: #<void>; arguments were: #<void> #<void> I know that its my print statement that is throwing the error, but I can't figure out why is this happening ? A: ((move src tmp dst (- num 1)) (move src dst tmp 1) (move tmp dst src (- num 1))) The above code doesn't do what you think it does :) To execute a series of expressions / statements you need something like this: ((λ () (move src tmp dst (- num 1)) (move src dst tmp 1) (move tmp dst src (- num 1)))) The syntactic sugar in Scheme is (begin (move ...) (move ...) (move ...) ...) ((move ...) (move ...) (move ...)) will be evaluated, and the code seems to work. But as soon as the recursion ends, the interpreter will try to execute it as (op param1 param2) and there is where you get the error #<void>; arguments were: #<void> #<void>
Tower of hanoi, python -> scheme, shows error. What am I missing?
The python implementation import sys def move(src, dst, tmp, num): if num == 1: print 'Move from', src, 'to', dst else: move(src, tmp, dst, num-1) move(src, dst, tmp, 1) move(tmp, dst, src, num-1) move('left', 'right', 'middle', int(sys.argv[1])) Gives the right solution for tower of hanoi. But my scheme port, (define move (lambda (src dst tmp num) (if (= num 1) (printf "Move from ~s to ~s \n" src dst) ((move src tmp dst (- num 1)) (move src dst tmp 1) (move tmp dst src (- num 1)))))) Gives the right solution but in the end throws the following error. procedure application: expected procedure, given: #<void>; arguments were: #<void> #<void> I know that its my print statement that is throwing the error, but I can't figure out why is this happening ?
[ " ((move src tmp dst (- num 1))\n (move src dst tmp 1)\n (move tmp dst src (- num 1)))\n\nThe above code doesn't do what you think it does :) \nTo execute a series of expressions / statements you need something like this:\n((λ ()\n (move src tmp dst (- num 1))\n (move src dst tmp 1)\n (move tmp dst src (- num 1))))\n\nThe syntactic sugar in Scheme is\n(begin\n (move ...)\n (move ...)\n (move ...)\n ...)\n\n\n((move ...) (move ...) (move ...))\n\nwill be evaluated, and the code seems to work. But as soon as the recursion ends,\nthe interpreter will try to execute it as (op param1 param2) and there is where\nyou get the error #<void>; arguments were: #<void> #<void>\n" ]
[ 4 ]
[]
[]
[ "python", "scheme", "towers_of_hanoi" ]
stackoverflow_0002356229_python_scheme_towers_of_hanoi.txt
Q: How to post a file via HTTP with cookies using python poster lib Using Chris Atlee's python poster library is there any way to include cookie handling? I have python http login code, which works with cookies: cookiejar = cookielib.CookieJar() urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) request = urllib2.Request(login_url, params) result = urlOpener.open(request) But when I need to upload a file, I don't know how to use both poster lib code and cookie handling code. Poster lib seems to need to call urllib2.urlopen() and not some custom url opener, like in the code above. For instance, I don't know how to use cookies with the python file post code below: register_openers() params = {'file': open("test.txt", "rb"), 'name': 'upload test'} datagen, headers = multipart_encode(params) request = urllib2.Request(upload_url, datagen, headers) result = urllib2.urlopen(request) A: I sent an email to Chris AtLee asking whether we could get a basic authentication example. He was very cool about answering my questions and even ran some example code I sent him. To include cookie handling, you do something like this: opener = poster.streaminghttp.register_openers() opener.add_handler(urllib2.HTTPCookieProcessor(cookielib.CookieJar())) # Add cookie handler params = {'file': open("test.txt", "rb"), 'name': 'upload test'} datagen, headers = poster.encode.multipart_encode(params) request = urllib2.Request(upload_url, datagen, headers) result = urllib2.urlopen(request) To add basic authentication to the request, you simply do this (I added the base64 encode line for completeness): opener = poster.streaminghttp.register_openers() params = {'file': open("test.txt", "rb"), 'name': 'upload test'} datagen, headers = poster.encode.multipart_encode(params) request = urllib2.Request(upload_url, datagen, headers) auth = base64.encodestring('%s:%s' % ('username', 'password'))[:-1] # This is just standard un/pw encoding request.add_header('Authorization', 'Basic %s' % auth ) # Add Auth header to request result = urllib2.urlopen(request) Hope this helps. And another big thanks to Chris AtLee. A: You don't have to modify the original source code, just install all required openers manually (without calling register_openers()): import urllib2 import cookielib import poster handlers = [poster.streaminghttp.StreamingHTTPHandler(), poster.streaminghttp.StreamingHTTPRedirectHandler(), urllib2.HTTPCookieProcessor(cookielib.CookieJar())] urllib2.install_opener(urllib2.build_opener(*handlers)) datagen, headers = poster.encode.multipart_encode({"image1": open("DSC0001.jpg", "rb")}) request = urllib2.Request("http://localhost:5000/upload_image", datagen, headers) print urllib2.urlopen(request).read() A: Have you tried this: cookiejar = cookielib.CookieJar() urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) register_openers() params = {'file': open("test.txt", "rb"), 'name': 'upload test'} datagen, headers = multipart_encode(params) request = urllib2.Request(upload_url, datagen, headers) result = urlOpener.open(request) A: I've figured out how to do this. I'm not sure if this is the best way to go about things, but it works, so I'll share it. In order to use the poster lib with cookies one must add urllib2.HTTPCookieProcessor to the opener built in poster.streaminghttp.register_openers(). Essentially, modify poster.streaminghttp.register_openers() to look like the code below, and if you want to have cookie handling, pass in a cookiejar object. def register_openers(cookiejar=None): """Register the streaming http handlers in the global urllib2 default opener object. Returns the created OpenerDirector object.""" handlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler] if hasattr(httplib, "HTTPS"): handlers.append(StreamingHTTPSHandler) if cookiejar: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar), *handlers) else: opener = urllib2.build_opener(*handlers) urllib2.install_opener(opener) return opener Sample Usage: # Logging in import urllib, urllib2, cookielib from poster.encode import multipart_encode from poster.streaminghttp import register_openers cookiejar = cookielib.CookieJar() loginOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) params = urllib.urlencode({'username':'admin', 'password':'default'}) login_url = "http://127.0.0.1:8000/account/login/" request = urllib2.Request(login_url, params) login = loginOpener.open(request) # Upload File # use the login cookie for file upload register_openers(cookiejar=cookiejar) params = {'entity_file': open("test.txt", "rb"),'name': 'test', 'action':'upload'} upload_url = "http://127.0.0.1:8000/upload/" datagen, headers = multipart_encode(params) request = urllib2.Request(upload_url, datagen, headers) result = urllib2.urlopen(request)
How to post a file via HTTP with cookies using python poster lib
Using Chris Atlee's python poster library is there any way to include cookie handling? I have python http login code, which works with cookies: cookiejar = cookielib.CookieJar() urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) request = urllib2.Request(login_url, params) result = urlOpener.open(request) But when I need to upload a file, I don't know how to use both poster lib code and cookie handling code. Poster lib seems to need to call urllib2.urlopen() and not some custom url opener, like in the code above. For instance, I don't know how to use cookies with the python file post code below: register_openers() params = {'file': open("test.txt", "rb"), 'name': 'upload test'} datagen, headers = multipart_encode(params) request = urllib2.Request(upload_url, datagen, headers) result = urllib2.urlopen(request)
[ "I sent an email to Chris AtLee asking whether we could get a basic authentication example. He was very cool about answering my questions and even ran some example code I sent him. \nTo include cookie handling, you do something like this:\nopener = poster.streaminghttp.register_openers()\nopener.add_handler(urllib2.HTTPCookieProcessor(cookielib.CookieJar())) # Add cookie handler\nparams = {'file': open(\"test.txt\", \"rb\"), 'name': 'upload test'}\ndatagen, headers = poster.encode.multipart_encode(params)\nrequest = urllib2.Request(upload_url, datagen, headers)\nresult = urllib2.urlopen(request)\n\nTo add basic authentication to the request, you simply do this (I added the base64 encode line for completeness):\nopener = poster.streaminghttp.register_openers()\nparams = {'file': open(\"test.txt\", \"rb\"), 'name': 'upload test'}\ndatagen, headers = poster.encode.multipart_encode(params)\nrequest = urllib2.Request(upload_url, datagen, headers)\nauth = base64.encodestring('%s:%s' % ('username', 'password'))[:-1] # This is just standard un/pw encoding \nrequest.add_header('Authorization', 'Basic %s' % auth ) # Add Auth header to request\nresult = urllib2.urlopen(request)\n\nHope this helps. And another big thanks to Chris AtLee.\n", "You don't have to modify the original source code, just install all required openers manually (without calling register_openers()):\nimport urllib2\nimport cookielib\nimport poster\n\nhandlers = [poster.streaminghttp.StreamingHTTPHandler(),\n poster.streaminghttp.StreamingHTTPRedirectHandler(),\n urllib2.HTTPCookieProcessor(cookielib.CookieJar())]\n\nurllib2.install_opener(urllib2.build_opener(*handlers))\n\n\ndatagen, headers = poster.encode.multipart_encode({\"image1\": open(\"DSC0001.jpg\", \"rb\")})\n\nrequest = urllib2.Request(\"http://localhost:5000/upload_image\", datagen, headers)\n\nprint urllib2.urlopen(request).read()\n\n", "Have you tried this:\ncookiejar = cookielib.CookieJar()\nurlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))\nregister_openers()\nparams = {'file': open(\"test.txt\", \"rb\"), 'name': 'upload test'}\ndatagen, headers = multipart_encode(params)\nrequest = urllib2.Request(upload_url, datagen, headers)\nresult = urlOpener.open(request)\n\n", "I've figured out how to do this. I'm not sure if this is the best way to go about things, but it works, so I'll share it. In order to use the poster lib with cookies one must add urllib2.HTTPCookieProcessor to the opener built in poster.streaminghttp.register_openers().\nEssentially, modify poster.streaminghttp.register_openers() to look like the code below, and if you want to have cookie handling, pass in a cookiejar object.\ndef register_openers(cookiejar=None):\n \"\"\"Register the streaming http handlers in the global urllib2 default\n opener object.\n\n Returns the created OpenerDirector object.\"\"\"\n handlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler]\n if hasattr(httplib, \"HTTPS\"):\n handlers.append(StreamingHTTPSHandler)\n\n if cookiejar:\n opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar), *handlers)\n else:\n opener = urllib2.build_opener(*handlers)\n\n\n urllib2.install_opener(opener)\n\n return opener\n\nSample Usage:\n# Logging in\nimport urllib, urllib2, cookielib\n\nfrom poster.encode import multipart_encode\nfrom poster.streaminghttp import register_openers\n\ncookiejar = cookielib.CookieJar()\nloginOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))\n\nparams = urllib.urlencode({'username':'admin', 'password':'default'})\nlogin_url = \"http://127.0.0.1:8000/account/login/\"\nrequest = urllib2.Request(login_url, params)\nlogin = loginOpener.open(request)\n\n# Upload File\n# use the login cookie for file upload\nregister_openers(cookiejar=cookiejar)\n\nparams = {'entity_file': open(\"test.txt\", \"rb\"),'name': 'test', 'action':'upload'}\nupload_url = \"http://127.0.0.1:8000/upload/\"\n\ndatagen, headers = multipart_encode(params)\n\nrequest = urllib2.Request(upload_url, datagen, headers)\nresult = urllib2.urlopen(request)\n\n" ]
[ 7, 1, 0, 0 ]
[]
[]
[ "cookies", "file_upload", "http", "python" ]
stackoverflow_0001690446_cookies_file_upload_http_python.txt
Q: Python: Import Data from Open Office calc with lxml How can I import data for example for the field A1? When I use etree.parse() I get an error, because I dont have a xml file. A: It's a zip file: import zipfile from lxml import etree z = zipfile.ZipFile('mydocument.ods') data = z.read('content.xml') data = etree.XML(data) etree.dump(data)
Python: Import Data from Open Office calc with lxml
How can I import data for example for the field A1? When I use etree.parse() I get an error, because I dont have a xml file.
[ "It's a zip file:\nimport zipfile\nfrom lxml import etree\n\nz = zipfile.ZipFile('mydocument.ods')\n\ndata = z.read('content.xml')\ndata = etree.XML(data)\n\netree.dump(data)\n\n" ]
[ 1 ]
[]
[]
[ "import", "lxml", "openoffice_calc", "python" ]
stackoverflow_0002356451_import_lxml_openoffice_calc_python.txt
Q: Reusing module references in Python (Matplotlib) I think I may have misunderstood something here... But here goes. I'm using the psd method in matplotlib inside a loop, I'm not making it plot anything, I just want the numerical result, so: import pylab as pyl ... psdResults = pyl.psd(inputData, NFFT=512, Fs=sampleRate, window=blackman) But that's being looped 36 times every time I run the function it's in. I'm getting a slow memory leak when I run my program over time, so used 'heapy' to monitor this, and every time I run the function, it adds 36 to these 3 heaps: dict matplotlib.line.Line26 dict matplotlib.transforms.CompositeAffine2D dict matplotlib.path.Path I can only conclude that each time I use the psd method it merely adds it to some dictionary somewhere, whereas I want to effectively wipe the memory - i.e. reset pylab each loop so it doesn't store anything. I could be misinterpreting heapy but it seems pretty clear that pylab is just growing each loop even though I only want to use it's psd method, I don't want it saving the results anywhere itself ! Cheers A: Try this: from matplotlib import mlab psdResults = mlab.psd(inputData, NFFT=512, Fs=sampleRate, window=blackman) Does that improve the situation?
Reusing module references in Python (Matplotlib)
I think I may have misunderstood something here... But here goes. I'm using the psd method in matplotlib inside a loop, I'm not making it plot anything, I just want the numerical result, so: import pylab as pyl ... psdResults = pyl.psd(inputData, NFFT=512, Fs=sampleRate, window=blackman) But that's being looped 36 times every time I run the function it's in. I'm getting a slow memory leak when I run my program over time, so used 'heapy' to monitor this, and every time I run the function, it adds 36 to these 3 heaps: dict matplotlib.line.Line26 dict matplotlib.transforms.CompositeAffine2D dict matplotlib.path.Path I can only conclude that each time I use the psd method it merely adds it to some dictionary somewhere, whereas I want to effectively wipe the memory - i.e. reset pylab each loop so it doesn't store anything. I could be misinterpreting heapy but it seems pretty clear that pylab is just growing each loop even though I only want to use it's psd method, I don't want it saving the results anywhere itself ! Cheers
[ "Try this:\nfrom matplotlib import mlab\npsdResults = mlab.psd(inputData, NFFT=512, Fs=sampleRate, window=blackman)\n\nDoes that improve the situation?\n" ]
[ 3 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0002356695_matplotlib_python.txt
Q: Date fields and Django's loaddata Can a date be loaded into a DateField using Django's loaddata admin feature? I have a JSON file that I'm using to bulk load data into my app. When you dumpdata, date fields are outputted in the format yyyy-mm-dd. However, if you try loading data back in with the same format, the field is treated as a string and the load fails. For example, I have a field authorization_date of type models.DateField(). When the value of a field is "2001-12-14", I get the following error: > Warning: Data truncated for column 'authorization_date' at row 1 So how can I load dates using Django's loaddata? A: Sounds like something else is broken, lupefiasco. Django has a pretty extensive set of tests to make sure you can dumpdata -> loaddata just fine. Sounds like it may be a Ticket#5007 [http://code.djangoproject.com/ticket/5007], but it could just as well be one of many others. The error is after all rather vague. Are you running django-trunk? In that case I first suggest updating the trunk (just in case :)). Except for that, you'll need to give us more info: what database are you running? Django version? Actually, I suggest you just take all this information and post to the django-users group, there are probably a lot more devs there who can help you.
Date fields and Django's loaddata
Can a date be loaded into a DateField using Django's loaddata admin feature? I have a JSON file that I'm using to bulk load data into my app. When you dumpdata, date fields are outputted in the format yyyy-mm-dd. However, if you try loading data back in with the same format, the field is treated as a string and the load fails. For example, I have a field authorization_date of type models.DateField(). When the value of a field is "2001-12-14", I get the following error: > Warning: Data truncated for column 'authorization_date' at row 1 So how can I load dates using Django's loaddata?
[ "Sounds like something else is broken, lupefiasco. Django has a pretty extensive set of tests to make sure you can dumpdata -> loaddata just fine.\nSounds like it may be a Ticket#5007 [http://code.djangoproject.com/ticket/5007], but it could just as well be one of many others. The error is after all rather vague. Are you running django-trunk? In that case I first suggest updating the trunk (just in case :)).\nExcept for that, you'll need to give us more info: what database are you running? Django version?\nActually, I suggest you just take all this information and post to the django-users group, there are probably a lot more devs there who can help you.\n" ]
[ 0 ]
[]
[]
[ "bulk_load", "django", "python" ]
stackoverflow_0002350557_bulk_load_django_python.txt
Q: Modern client/server authentication techniques I'm building a non-browser client-server (XULRunner-CherryPy) application using HTTP for communication. The area I'm pondering now is user authentication. Since I don't have substantial knowledge in security I would much prefer using tried-and-tested approaches and ready-made libraries over trying to invent and/or build something myself. I've been reading a lot of articles lately and I can say all I have been left with is a lot of frustration, most of which contributed by this and this blog posts. What I think I need is: Secure storage of passwords in the database (adaptive hashing?) Secure wire transmission of user credentials (digest authentication? SSL?) Secure token authentication for subsequent requests (not sure about this) So the question is: what are the modern (headache-free preferrably) techniques and/or libraries that implement this? (No sensitive information, like credit card numbers, will be stored). I've been looking at OAuth and they have a new revision which they strongly recommend to use. The problem is the docs are still in development and there are no libraries implementing the new revision (?). A: This may not be a complete answer, but I would like to offer some reassuring news about rainbow tables and the web. I wouldn't worry too much about Rainbow Tables with regards to the web for the following reasons: (1) Rainbow table cracks work by examining the hashed password. On the web, the hashed password is stored on your database so to even consider using rainbow tables one would first need to hack your entire database. (2) If you use a salt as most password storage systems do, then rainbow tables rapidly become unfeasible. Basically a salt adds a series of extra bits to the end of a given password. In order to use a rainbow table, it would need to accommodate the extra bits in each plaintext password. For example the first link you showed us had a rainbow table implementation that could crack up to 14 characters in a password. Therefore if you had more than 14 bytes of a salt that system would be useless. A: Amazon Web Services, OpenID, and OAuth have examples of request signing. Amazon Web Services is an easy example to follow because there isn't a more complex protocol around the interactions. They basically involve having the client or server sign a request by hashing all of its fields with a previously set up key (or keypair), and having the other end verify the signature by doing the same. Replaying the hash is prevented by including a nonce or timestamp in the fields. Setting up keys or other credentials to allow this can be done over SSL, and it should be noted that one of the motivation of OAuth WRAP is to replace some or all of this request signing with SSL, for ease of implementation. A: After a lot of poking around and trying to write my own prototype based on Amazon S3 design which (I thought) was pretty secure, I found this excellent website which has answers to all my questions, an Enterprise Security API Toolkit, and much, much more: OWASP.
Modern client/server authentication techniques
I'm building a non-browser client-server (XULRunner-CherryPy) application using HTTP for communication. The area I'm pondering now is user authentication. Since I don't have substantial knowledge in security I would much prefer using tried-and-tested approaches and ready-made libraries over trying to invent and/or build something myself. I've been reading a lot of articles lately and I can say all I have been left with is a lot of frustration, most of which contributed by this and this blog posts. What I think I need is: Secure storage of passwords in the database (adaptive hashing?) Secure wire transmission of user credentials (digest authentication? SSL?) Secure token authentication for subsequent requests (not sure about this) So the question is: what are the modern (headache-free preferrably) techniques and/or libraries that implement this? (No sensitive information, like credit card numbers, will be stored). I've been looking at OAuth and they have a new revision which they strongly recommend to use. The problem is the docs are still in development and there are no libraries implementing the new revision (?).
[ "This may not be a complete answer, but I would like to offer some reassuring news about rainbow tables and the web. I wouldn't worry too much about Rainbow Tables with regards to the web for the following reasons: \n(1) Rainbow table cracks work by examining the hashed password. On the web, the hashed password is stored on your database so to even consider using rainbow tables one would first need to hack your entire database.\n(2) If you use a salt as most password storage systems do, then rainbow tables rapidly become unfeasible. Basically a salt adds a series of extra bits to the end of a given password. In order to use a rainbow table, it would need to accommodate the extra bits in each plaintext password. For example the first link you showed us had a rainbow table implementation that could crack up to 14 characters in a password. Therefore if you had more than 14 bytes of a salt that system would be useless.\n", "Amazon Web Services, OpenID, and OAuth have examples of request signing. Amazon Web Services is an easy example to follow because there isn't a more complex protocol around the interactions. They basically involve having the client or server sign a request by hashing all of its fields with a previously set up key (or keypair), and having the other end verify the signature by doing the same. Replaying the hash is prevented by including a nonce or timestamp in the fields.\nSetting up keys or other credentials to allow this can be done over SSL, and it should be noted that one of the motivation of OAuth WRAP is to replace some or all of this request signing with SSL, for ease of implementation.\n", "After a lot of poking around and trying to write my own prototype based on Amazon S3 design which (I thought) was pretty secure, I found this excellent website which has answers to all my questions, an Enterprise Security API Toolkit, and much, much more: OWASP.\n" ]
[ 1, 1, 1 ]
[]
[]
[ "authentication", "client_server", "python", "xulrunner" ]
stackoverflow_0001975793_authentication_client_server_python_xulrunner.txt
Q: Creating a global function, accessible from all classes, with Python + Pylons Using pylons 0.9.7, I'm trying to make a function that connects to a database on demand. I'd like it to be accessible from all functions within all model classes. In model/__init__.py, I have: #Establish an on-demand connection to the central database def connectCentral(): engine = engine_from_config(config, 'sqlalchemy.central.') central.engine = engine central.Session.configure(bind=engine) This function is accessible everywhere. However, when I try to run it from within a class specified in model/class.py, it returns: NameError: global name 'connectCentral' is not defined Do I have to do any kind of special import? Is there a better way to do this? Thanks. A: from model import connectCentral A: Have you done import init ? Or rather from init import connectCentral? If you did, that such name should be defined. If not, you can try writing global connectCentral in method's body, but I believe it is only for using global variables. Are you sure, this modules is supposed to have name init.py rather than __init__.py? Could you post some more code, where you are trying to use your function? EDIT So you are having __init__.py, fine. Are you doing import from model import connectCentral? Don't you have any circural imports (like import from __init__.py in class.py and import from class.py in __init__.py)?
Creating a global function, accessible from all classes, with Python + Pylons
Using pylons 0.9.7, I'm trying to make a function that connects to a database on demand. I'd like it to be accessible from all functions within all model classes. In model/__init__.py, I have: #Establish an on-demand connection to the central database def connectCentral(): engine = engine_from_config(config, 'sqlalchemy.central.') central.engine = engine central.Session.configure(bind=engine) This function is accessible everywhere. However, when I try to run it from within a class specified in model/class.py, it returns: NameError: global name 'connectCentral' is not defined Do I have to do any kind of special import? Is there a better way to do this? Thanks.
[ "from model import connectCentral\n\n", "Have you done import init ? Or rather from init import connectCentral?\nIf you did, that such name should be defined. If not, you can try writing global connectCentral in method's body, but I believe it is only for using global variables.\nAre you sure, this modules is supposed to have name init.py rather than __init__.py? Could you post some more code, where you are trying to use your function?\nEDIT\nSo you are having __init__.py, fine. Are you doing import from model import connectCentral? Don't you have any circural imports (like import from __init__.py in class.py and import from class.py in __init__.py)?\n" ]
[ 2, 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002357419_pylons_python.txt
Q: Why does supplying stdin to subprocess.Popen cause what is written to stdout to change? I'm using Python's subprocess.Popen to perform some FTP using the binary client of the host operating system. I can't use ftplib or any other library for various reasons. The behavior of the binary seems to change if I attach a stdin handler to the Popen instance. For example, using XP's ftp client, which accepts a text file of commands to issue: >>>from subprocess import Popen, PIPE >>>p = Popen(['ftp','-A','-s:commands.txt','example.com'], stdout=PIPE) >>>p.communicate()[0] 'Connected to example.com. 220 ProFTPD 1.3.1 Server (Debian) ... 331 Anonymous login ok, send your complete email address as your password <snip> ftp> binary 200 Type set to I ftp> get /testfiles/100.KiB 200 PORT command successful 150 Opening BINARY mode data connection for /testfiles/100.KiB (102400 bytes) 226 Transfer complete ftp: 102400 bytes received in 0.28Seconds 365.71Kbytes/sec. ftp> quit >>> commands.txt: binary get /testfiles/100.KiB quit When also supplying stdin, all you get in stdout is: >>>from subprocess import Popen, PIPE >>>p = Popen(['ftp','-A','-s:commands.txt','example.com'], stdin=PIPE, stdout=PIPE) >>>p.communicate()[0] 'binary get /testfiles/100.KiB quit' >>> Initially I thought this was a quirk of the XP ftp client, perhaps knowing it wasn't in interactive mode and therefore limiting its output. However, the same behaviour happens with OS X's ftp - all the server responses are missing from stdout if stdin is supplied - which leads me to think that this is normal behaviour. In Windows I can use the -s switch to effectively script ftp without using stdin, but on other platforms one relies on the shell for that kind of interaction. Python version is 2.6.x on both platforms. Why would supplying a handle for stdin change stdout, and where have the server responses gone to? A: The program may be using isatty(3) to detect presence of a tty on stdin. A: I think I read somewhere (but can't remember where) that Windows ftp client came from one of the original BSD implementations. In that it would certainly shares some relationship with Mac OS X's ftp implementation. For me, this is not related to Popen but to the client ftp program implementation, which makes some checks about the context in which it is launched (to see if it's interacting with a human or a shell script), using isatty(3) as mentionned with Ignacio in his answer. This is common practise for programs which can be used in both context. A well known example is GNU grep implementation for the --color=auto option : it will colorize output only if stdout is a tty, and not if the output of grep is piped into another command.
Why does supplying stdin to subprocess.Popen cause what is written to stdout to change?
I'm using Python's subprocess.Popen to perform some FTP using the binary client of the host operating system. I can't use ftplib or any other library for various reasons. The behavior of the binary seems to change if I attach a stdin handler to the Popen instance. For example, using XP's ftp client, which accepts a text file of commands to issue: >>>from subprocess import Popen, PIPE >>>p = Popen(['ftp','-A','-s:commands.txt','example.com'], stdout=PIPE) >>>p.communicate()[0] 'Connected to example.com. 220 ProFTPD 1.3.1 Server (Debian) ... 331 Anonymous login ok, send your complete email address as your password <snip> ftp> binary 200 Type set to I ftp> get /testfiles/100.KiB 200 PORT command successful 150 Opening BINARY mode data connection for /testfiles/100.KiB (102400 bytes) 226 Transfer complete ftp: 102400 bytes received in 0.28Seconds 365.71Kbytes/sec. ftp> quit >>> commands.txt: binary get /testfiles/100.KiB quit When also supplying stdin, all you get in stdout is: >>>from subprocess import Popen, PIPE >>>p = Popen(['ftp','-A','-s:commands.txt','example.com'], stdin=PIPE, stdout=PIPE) >>>p.communicate()[0] 'binary get /testfiles/100.KiB quit' >>> Initially I thought this was a quirk of the XP ftp client, perhaps knowing it wasn't in interactive mode and therefore limiting its output. However, the same behaviour happens with OS X's ftp - all the server responses are missing from stdout if stdin is supplied - which leads me to think that this is normal behaviour. In Windows I can use the -s switch to effectively script ftp without using stdin, but on other platforms one relies on the shell for that kind of interaction. Python version is 2.6.x on both platforms. Why would supplying a handle for stdin change stdout, and where have the server responses gone to?
[ "The program may be using isatty(3) to detect presence of a tty on stdin.\n", "I think I read somewhere (but can't remember where) that Windows ftp client came from one of the original BSD implementations. In that it would certainly shares some relationship with Mac OS X's ftp implementation. \nFor me, this is not related to Popen but to the client ftp program implementation, which makes some checks about the context in which it is launched (to see if it's interacting with a human or a shell script), using isatty(3) as mentionned with Ignacio in his answer. This is common practise for programs which can be used in both context. A well known example is GNU grep implementation for the --color=auto option : it will colorize output only if stdout is a tty, and not if the output of grep is piped into another command. \n" ]
[ 7, 4 ]
[]
[]
[ "popen", "python", "stdin", "stdout", "subprocess" ]
stackoverflow_0002356391_popen_python_stdin_stdout_subprocess.txt
Q: How to get parameters of fail case in Python unittest? I'm running an assertEqual test case for a list of methods in a particular class. These methods are expanded from string form to something callable using getattr(). How can I get unittest to tell me the particular method which failed? Meaning: how can I get unittest to print to stdout the particular parameters which caused the failure of the assert? Any advice greatly appreciated. Thanks A: You can pass assertEqual a third argument (technically fourth if you count self), which is the error message it will return. So the following should do more or less what you're looking for: class MethodTest(TestCase): def test_method(self): obj = MyClass() for method in "frob", "defrob", "refrob": self.assertEqual(getattr(obj, method)(), 42, "obj.%s() is not equal to 42" % method)
How to get parameters of fail case in Python unittest?
I'm running an assertEqual test case for a list of methods in a particular class. These methods are expanded from string form to something callable using getattr(). How can I get unittest to tell me the particular method which failed? Meaning: how can I get unittest to print to stdout the particular parameters which caused the failure of the assert? Any advice greatly appreciated. Thanks
[ "You can pass assertEqual a third argument (technically fourth if you count self), which is the error message it will return. So the following should do more or less what you're looking for:\nclass MethodTest(TestCase):\n def test_method(self):\n obj = MyClass()\n for method in \"frob\", \"defrob\", \"refrob\":\n self.assertEqual(getattr(obj, method)(), 42, \"obj.%s() is not equal to 42\" % method)\n\n" ]
[ 6 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0002357921_python_unit_testing.txt
Q: Linux/Python: Monitor /proc/acpi files without polling? Is there any way to monitor /proc files, such as /proc/acpi/battery/BAT0/state /proc/acpi/ac_adapter/ADP0/state in a non-polling fashion, similar to inotify on a normal filesystem? I want to do this in a PyGTK app, so I tried using PyGObject's gio.FileMonitor, but no dice. A Python solution that plays well with gtk.main() would be ideal. A: Probably you can get the information you want by listening to the ACPI events. Preferably not directly (/proc/acpi/event), but via acpid or other high-level interface. Update: the other, higher level interface is the DBus interface provided by DeviceKit-power / UPower. Files in /proc are not regular files, rather a simple interface to kernel state, so many facilities for regular files won't work there.
Linux/Python: Monitor /proc/acpi files without polling?
Is there any way to monitor /proc files, such as /proc/acpi/battery/BAT0/state /proc/acpi/ac_adapter/ADP0/state in a non-polling fashion, similar to inotify on a normal filesystem? I want to do this in a PyGTK app, so I tried using PyGObject's gio.FileMonitor, but no dice. A Python solution that plays well with gtk.main() would be ideal.
[ "Probably you can get the information you want by listening to the ACPI events. Preferably not directly (/proc/acpi/event), but via acpid or other high-level interface.\nUpdate: the other, higher level interface is the DBus interface provided by DeviceKit-power / UPower.\nFiles in /proc are not regular files, rather a simple interface to kernel state, so many facilities for regular files won't work there.\n" ]
[ 2 ]
[]
[]
[ "inotify", "linux", "pygobject", "pygtk", "python" ]
stackoverflow_0002357930_inotify_linux_pygobject_pygtk_python.txt
Q: Suggestions for first-time sourceforge project contributer? Hey all. I'm a professional software developer here in Seattle, WA USA. I program for/work in a Windows shop, but I've recently began considering contributing to an Open Source project, specifically one under the Python License (CNRI Python License). I realize that contacting a human resources representative where I work is the first step, but could any existing source forge contributors give me any advice? A: Apparently the answer is that there'll be no problem with it. :) Thanks for all the help, you guys!
Suggestions for first-time sourceforge project contributer?
Hey all. I'm a professional software developer here in Seattle, WA USA. I program for/work in a Windows shop, but I've recently began considering contributing to an Open Source project, specifically one under the Python License (CNRI Python License). I realize that contacting a human resources representative where I work is the first step, but could any existing source forge contributors give me any advice?
[ "Apparently the answer is that there'll be no problem with it. :) Thanks for all the help, you guys!\n" ]
[ 0 ]
[]
[]
[ "licensing", "open_source", "python", "sourceforge" ]
stackoverflow_0002353868_licensing_open_source_python_sourceforge.txt
Q: Serial communication. Sending DTR in the right way? I'm dealing with a gm29 by Sony Ericsson. The datasheet says that plugging the power is not sufficient to switch on the modem. It says: activate the RS232 control line DTR, high for > 0.2s. I'm writing some tests in python, but: #!/usr/bin/env python import serial from time import sleep socket = serial.Serial('/dev/ttyS0', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=1, xonxoff=0, rtscts=0 ) socket.setDTR(True) sleep(3) socket.setDTR(False) try: while True: socket.write('AT'+chr(13)); sleep(1) print "Reading" print socket.readlines() except: socket.close() does not works... I there a way to get DTR high in other ways? Let's say minicom or some other stuff? Or, easily, am I missing something? Thanks in advance. Ok, that was driving me mad. The clue is that the power supplier was "broken", or better, it works good testing with a tester, but plugging on the modem some wires moves and does not carry voltage... Thanks anyway for the answer, marked as correct 'couse it was :D A: There are several things that occur to me here. 1) the spec says that DTR is active low, so you may need to swap the true and false values to setDTR(), depending on who is confused here. 2) You are setting DTR to false after you wake the modem. This tells the modem to go offline, and ignore all input till it goes true again. Try the following: import serial from time import sleep conn = serial.Serial('/dev/ttyS0', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=1, xonxoff=0, rtscts=0 ) # Wake Modem conn.setDTR(True) sleep(3) conn.setDTR(False) sleep(5) # Start talking conn.setDTR(True) try: while True: conn.write('AT'+chr(13)); print conn.readline() # readlines() will probably never return. finally: conn.close() 3) socket is probably a bad name for your serial connection.
Serial communication. Sending DTR in the right way?
I'm dealing with a gm29 by Sony Ericsson. The datasheet says that plugging the power is not sufficient to switch on the modem. It says: activate the RS232 control line DTR, high for > 0.2s. I'm writing some tests in python, but: #!/usr/bin/env python import serial from time import sleep socket = serial.Serial('/dev/ttyS0', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=1, xonxoff=0, rtscts=0 ) socket.setDTR(True) sleep(3) socket.setDTR(False) try: while True: socket.write('AT'+chr(13)); sleep(1) print "Reading" print socket.readlines() except: socket.close() does not works... I there a way to get DTR high in other ways? Let's say minicom or some other stuff? Or, easily, am I missing something? Thanks in advance. Ok, that was driving me mad. The clue is that the power supplier was "broken", or better, it works good testing with a tester, but plugging on the modem some wires moves and does not carry voltage... Thanks anyway for the answer, marked as correct 'couse it was :D
[ "There are several things that occur to me here.\n1) the spec says that DTR is active low, so you may need to swap the true and false values to setDTR(), depending on who is confused here.\n2) You are setting DTR to false after you wake the modem. This tells the modem to go offline, and ignore all input till it goes true again. Try the following:\nimport serial\nfrom time import sleep\n\nconn = serial.Serial('/dev/ttyS0',\n baudrate=9600,\n bytesize=serial.EIGHTBITS,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n timeout=1,\n xonxoff=0,\n rtscts=0\n )\n# Wake Modem\nconn.setDTR(True)\nsleep(3)\nconn.setDTR(False)\n\nsleep(5)\n\n# Start talking\nconn.setDTR(True)\ntry:\n while True:\n conn.write('AT'+chr(13));\n print conn.readline() # readlines() will probably never return.\nfinally:\n conn.close()\n\n3) socket is probably a bad name for your serial connection.\n" ]
[ 4 ]
[]
[]
[ "modem", "python", "serial_port" ]
stackoverflow_0002357610_modem_python_serial_port.txt
Q: Making user-made HTML templates safe I want to allow users to create tiny templates that I then render in Django with a predefined context. I am assuming the Django rendering is safe (I asked a question about this before), but there is still the risk of cross-site-scripting, and I'd like to prevent this. One of the main requirements of these templates is that the user should have some control over the layout of the page, not just it's semantics. I see a couple of solutions: Allow the user to use HTML, but filter out dangerous tags manually in the final step (things like <script> and <a onclick='..'>. I'm not so enthusiastic about this option, because I'm afraid I might overlook some tags. Even then, the user could still use absolute positioning on <divs> to mess up a thing or two on the rest of the page. Use a markup language that produces safe HTML. From what I can see, in most markup languages, I could strip any html, and then process the result. The problem with this is that most markup languages are not very powerful layout-wise. As far as I could see there is no way to center elements in Markdown, not even in ReST. The pro here is that some markup languages are well-documented, and users might already know how to use them. Come up with some proprietary markup. The cons I see here are pretty much all implied by the word proprietary. So, to summarize: Is there some safe and easy way to "purify" HTML — preventing xss — or is there a reasonably ubiquitous markup language that gives some control over layout and styling. Resources: My earlier question about Django templates Class names in markdown. A: Seeing Pekka's answer, I tried to quickly Google an HTML Purifier equivalent in Python. Here's what I came up with: Python HTML Sanitizer. At first glance, it looks pretty good to me. A: There's PHP-Based HTML purifier, I have not used it myself yet but heard very good things about it. They promise a lot: HTML Purifier is a standards-compliant HTML filter library written in PHP. HTML Purifier will not only remove all malicious code (better known as XSS) with a thoroughly audited, secure yet permissive whitelist, it will also make sure your documents are standards compliant, something only achievable with a comprehensive knowledge of W3C's specifications. Maybe it's worth a try even though it's not Python based. Update: @Matchu has found a Python based alternative that looks good too. You'll have a lot of very difficult edge cases, though, just think about Flash embeds. Plus, malicious uses of position: absolute are extremely difficult to track down (there's position: relative that could achieve the same effect, but also be a completely legitimate layout tool.) Maybe take a look at what - for example - EBay allow, and don't allow? If anybody has the necessary experience to know what's dangerous and what isn't from millions of examples, they do. Related resources on EBay: HTML & JavaScript with examples Site Interference it's unclear, though, what is just forbidden, and what gets filtered From what I found, they don't seem to publish their internal HTML blacklists, but output an error message if forbidden code is found. (Probably a wise move on their part, but unfortunate for the purposes of this question.) A: "Use a markup language that produces safe HTML." Clearly, the only sensible approach. "The problem with this is that most markup languages are not very powerful layout-wise." False. "no way to center elements in ReST." False. Centering is a style -- a CSS feature -- not a markup feature. The want to center is to assign an CSS Class to a piece of text. The .. class:: directive does this. You can also define your own interpreted text role, if that's necessary for specifying an inline class on a piece of <span> markup. A: You are overlooking server side security issues. You need to be very careful that users can't use the templates import or include mechanism to access files they don't have permission to. The bigger challenge is to prevent the template system from infinite loops and recursion. This is an obvious threat to system performance, but depending on the implementation and deployment setup, the server may never timeout. With a finite number of python threads at your disposal, repeated calls to a misbehaving template could quickly bring your site down.
Making user-made HTML templates safe
I want to allow users to create tiny templates that I then render in Django with a predefined context. I am assuming the Django rendering is safe (I asked a question about this before), but there is still the risk of cross-site-scripting, and I'd like to prevent this. One of the main requirements of these templates is that the user should have some control over the layout of the page, not just it's semantics. I see a couple of solutions: Allow the user to use HTML, but filter out dangerous tags manually in the final step (things like <script> and <a onclick='..'>. I'm not so enthusiastic about this option, because I'm afraid I might overlook some tags. Even then, the user could still use absolute positioning on <divs> to mess up a thing or two on the rest of the page. Use a markup language that produces safe HTML. From what I can see, in most markup languages, I could strip any html, and then process the result. The problem with this is that most markup languages are not very powerful layout-wise. As far as I could see there is no way to center elements in Markdown, not even in ReST. The pro here is that some markup languages are well-documented, and users might already know how to use them. Come up with some proprietary markup. The cons I see here are pretty much all implied by the word proprietary. So, to summarize: Is there some safe and easy way to "purify" HTML — preventing xss — or is there a reasonably ubiquitous markup language that gives some control over layout and styling. Resources: My earlier question about Django templates Class names in markdown.
[ "Seeing Pekka's answer, I tried to quickly Google an HTML Purifier equivalent in Python. Here's what I came up with: Python HTML Sanitizer. At first glance, it looks pretty good to me.\n", "There's PHP-Based HTML purifier, I have not used it myself yet but heard very good things about it. They promise a lot:\n\nHTML Purifier is a standards-compliant \n HTML filter library written in \n PHP. HTML Purifier will not only remove all malicious \n code (better known as XSS) with a thoroughly audited, \n secure yet permissive whitelist,\n it will also make sure your documents are \n standards compliant, something only achievable with a \n comprehensive knowledge of W3C's specifications.\n\nMaybe it's worth a try even though it's not Python based. Update: @Matchu has found a Python based alternative that looks good too.\nYou'll have a lot of very difficult edge cases, though, just think about Flash embeds. Plus, malicious uses of position: absolute are extremely difficult to track down (there's position: relative that could achieve the same effect, but also be a completely legitimate layout tool.) Maybe take a look at what - for example - EBay allow, and don't allow? If anybody has the necessary experience to know what's dangerous and what isn't from millions of examples, they do.\nRelated resources on EBay:\n\nHTML & JavaScript with examples\nSite Interference it's unclear, though, what is just forbidden, and what gets filtered\n\nFrom what I found, they don't seem to publish their internal HTML blacklists, but output an error message if forbidden code is found. (Probably a wise move on their part, but unfortunate for the purposes of this question.) \n", "\"Use a markup language that produces safe HTML.\"\nClearly, the only sensible approach.\n\"The problem with this is that most markup languages are not very powerful layout-wise.\"\nFalse.\n\"no way to center elements in ReST.\"\nFalse.\nCentering is a style -- a CSS feature -- not a markup feature. \n\nThe want to center is to assign an CSS Class to a piece of text. The .. class:: directive does this.\nYou can also define your own interpreted text role, if that's necessary for specifying an inline class on a piece of <span> markup.\n\n", "You are overlooking server side security issues. You need to be very careful that users can't use the templates import or include mechanism to access files they don't have permission to.\nThe bigger challenge is to prevent the template system from infinite loops and recursion. This is an obvious threat to system performance, but depending on the implementation and deployment setup, the server may never timeout. With a finite number of python threads at your disposal, repeated calls to a misbehaving template could quickly bring your site down.\n" ]
[ 3, 1, 1, 0 ]
[]
[]
[ "html", "markup", "python", "security", "xss" ]
stackoverflow_0002357750_html_markup_python_security_xss.txt
Q: Prevent Windows 7 Shutdown I know that shutdown -a will abort a Windows shutdown, but I need to know if there is anything any where I can check for to see if a shutdown is in progress. Ideally, I'd like a small program like this: import os while True: shuttingDown = <shutdown variable to check> if shuttingDown: os.system("shutdown.exe -a") A: For preventing a Windows shutdown when it is happening, you can react to the WM_QUERYENDSESSION message (don't know if you can do that easily with Python's win32 API but it's simple in C). This might not prevent applications from closing because Windows sends WM_ENDSESSION to those that answer TRUE to the query message. I guess you rather want to prevent a timed shutdown using "shutdown.exe". I'm sure that program uses InitiateSystemShutdown to show the shutdown dialog, but there are no resources on intercepting that call (at least I didn't find any or know of a Windows feature that allows such a thing).
Prevent Windows 7 Shutdown
I know that shutdown -a will abort a Windows shutdown, but I need to know if there is anything any where I can check for to see if a shutdown is in progress. Ideally, I'd like a small program like this: import os while True: shuttingDown = <shutdown variable to check> if shuttingDown: os.system("shutdown.exe -a")
[ "For preventing a Windows shutdown when it is happening, you can react to the WM_QUERYENDSESSION message (don't know if you can do that easily with Python's win32 API but it's simple in C). This might not prevent applications from closing because Windows sends WM_ENDSESSION to those that answer TRUE to the query message.\nI guess you rather want to prevent a timed shutdown using \"shutdown.exe\". I'm sure that program uses InitiateSystemShutdown to show the shutdown dialog, but there are no resources on intercepting that call (at least I didn't find any or know of a Windows feature that allows such a thing).\n" ]
[ 1 ]
[]
[]
[ "python", "shutdown", "windows", "windows_7" ]
stackoverflow_0002358929_python_shutdown_windows_windows_7.txt
Q: How do you make Python wait so that you can read the output? I've always been a heavy user of Notepad2, as it is fast, feature-rich, and supports syntax highlighting. Recently I've been using it for Python. My problem: when I finish editing a certain Python source code, and try to launch it, the screen disappears before I can see the output pop up. Is there any way for me to make the results wait so that I can read it, short of using an input() or time-delay function? Otherwise I'd have to use IDLE, because of the output that stops for you to read. (My apologies if this question is a silly one, but I'm very new at Python and programming in general.) A: you could start in the command window. e.g.: c:\tmp\python>main.py adding raw_input() (or input() in py3k) at the end of your script will let you freeze it for until enter is pressed, but it's not a good thing to do. A: This is a "problem" with Notepad2, not Python itself. Unless you want to use input()/sleep (or any other blocking function) in your scripts, I think you have to turn to the settings in Notepad2 and see what that has to offer. A: If you don't want to use raw_input() or input() you could log your output (stdout, stderr) to a file or files. You could either use the logging module, or just redirect sys.stdout and sys.stderr. I would suggest using a combination of the logging and traceback if you want to log errors with their trace stack. Something like this maybe: import logging, traceback logging.basicConfig(filename=r'C:\Temp\log.txt', level=logging.DEBUG) try: #do some stuff logging.debug('I did some stuff!') except SomeException: logging.error(traceback.format_exc()) Here's an example of redirecting stdout and stderr: if __name__ == '__main__': save_out = sys.stdout # save the original stdout so you can put it back later out_file = open(r'C:\Temp\out.txt', 'w') sys.stdout = out_file save_err = sys.stderr err_file = open(r'C:\Temp\err.txt', 'w') sys.stderr = err_file main() #call your main function sys.stdout = save_out # set stdout back to it's original object sys.stderr = save_err out_file.close() err_file.close() I'm going to point out that this is not the easiest or most straight forward way to go. A: You can add a call to raw_input() to the end of your script in order to make it wait until you press Enter.
How do you make Python wait so that you can read the output?
I've always been a heavy user of Notepad2, as it is fast, feature-rich, and supports syntax highlighting. Recently I've been using it for Python. My problem: when I finish editing a certain Python source code, and try to launch it, the screen disappears before I can see the output pop up. Is there any way for me to make the results wait so that I can read it, short of using an input() or time-delay function? Otherwise I'd have to use IDLE, because of the output that stops for you to read. (My apologies if this question is a silly one, but I'm very new at Python and programming in general.)
[ "you could start in the command window. e.g.:\nc:\\tmp\\python>main.py\n\nadding raw_input() (or input() in py3k) at the end of your script will let you freeze it for until enter is pressed, but it's not a good thing to do.\n", "This is a \"problem\" with Notepad2, not Python itself.\nUnless you want to use input()/sleep (or any other blocking function) in your scripts, I think you have to turn to the settings in Notepad2 and see what that has to offer.\n", "If you don't want to use raw_input() or input() you could log your output (stdout, stderr) to a file or files.\nYou could either use the logging module, or just redirect sys.stdout and sys.stderr.\nI would suggest using a combination of the logging and traceback if you want to log errors with their trace stack.\nSomething like this maybe:\nimport logging, traceback\nlogging.basicConfig(filename=r'C:\\Temp\\log.txt', level=logging.DEBUG)\n\ntry:\n #do some stuff\n logging.debug('I did some stuff!')\nexcept SomeException:\n logging.error(traceback.format_exc())\n\nHere's an example of redirecting stdout and stderr:\nif __name__ == '__main__':\n save_out = sys.stdout # save the original stdout so you can put it back later\n out_file = open(r'C:\\Temp\\out.txt', 'w')\n sys.stdout = out_file\n\n save_err = sys.stderr\n err_file = open(r'C:\\Temp\\err.txt', 'w')\n sys.stderr = err_file\n\n main() #call your main function\n\n sys.stdout = save_out # set stdout back to it's original object\n sys.stderr = save_err\n\n out_file.close()\n err_file.close()\n\nI'm going to point out that this is not the easiest or most straight forward way to go.\n", "You can add a call to raw_input() to the end of your script in order to make it wait until you press Enter.\n" ]
[ 3, 3, 3, 0 ]
[]
[]
[ "ide", "python" ]
stackoverflow_0002356651_ide_python.txt