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: How do I (successfully) decode a encoded password from command line openSSL? Using PyCrypto (although I've tried this in ObjC with OpenSSL bindings as well) : from Crypto.Cipher import DES import base64 obj=DES.new('abcdefgh', DES.MODE_ECB) plain="Guido van Rossum is a space alien.XXXXXX" ciph=obj.encrypt(plain) e...
How do I (successfully) decode a encoded password from command line openSSL?
Using PyCrypto (although I've tried this in ObjC with OpenSSL bindings as well) : from Crypto.Cipher import DES import base64 obj=DES.new('abcdefgh', DES.MODE_ECB) plain="Guido van Rossum is a space alien.XXXXXX" ciph=obj.encrypt(plain) enc=base64.b64encode(ciph) #print ciph print enc outputs a base64 encoded value of...
[ "\necho ESzjTnGMRFnfVOJwQfqtyXOI8yzAatioyufiSdE1dx02McNkZ2IvBg== | openssl enc -nopad -a -des-ecb -K 6162636465666768 -iv 0 -p -d\n\n6162636465666768 is the ASCII \"abcdefgh\" written out in hexadecimal.\nBut note that DES in ECB mode is probably not a good way to encode passwords and also is not the \"DES crypt\" ...
[ 4 ]
[]
[]
[ "bash", "encryption", "linux", "openssl", "python" ]
stackoverflow_0000426294_bash_encryption_linux_openssl_python.txt
Q: How do I timestamp simultaneous function calls in Python? I have a read function in a module. If I perform that function simultaneously I need to timestamp it. How do I do this? A: I'll offer a slightly different approach: import time def timestampit(func): def decorate(*args, **kwargs): decorate.ti...
How do I timestamp simultaneous function calls in Python?
I have a read function in a module. If I perform that function simultaneously I need to timestamp it. How do I do this?
[ "I'll offer a slightly different approach:\nimport time\n\ndef timestampit(func):\n def decorate(*args, **kwargs):\n decorate.timestamp = time.time()\n return func(*args, **kwargs)\n return decorate\n\n@timestampit\ndef hello():\n print 'hello'\n\n\nhello()\nprint hello.timestamp\n\ntime.slee...
[ 6, 2, 0, 0 ]
[]
[]
[ "function_call", "python", "simultaneous_calls", "timestamping" ]
stackoverflow_0000427152_function_call_python_simultaneous_calls_timestamping.txt
Q: Does anyone know of a Python equivalent of FMPP? Does anyone know of a Python equivalent for FMPP the text file preprocessor? Follow up: I am reading the docs and looking at the examples for the suggestions given. Just to expand. My usage of FMPP is to read in a data file (csv) and use multiple templates depending...
Does anyone know of a Python equivalent of FMPP?
Does anyone know of a Python equivalent for FMPP the text file preprocessor? Follow up: I am reading the docs and looking at the examples for the suggestions given. Just to expand. My usage of FMPP is to read in a data file (csv) and use multiple templates depending on that data to create multi page reports in html all...
[ "Let me add Mako Fine fast tool (and it even uses ${var} syntax).\nNote: Mako, Jinja and Cheetah are textual languages (they process and generate text). I'd order them Mako > Jinja > Cheetah (in term of features and readability), but people's preferences vary.\nKid and it's successor Genshi are HTML/XML aware attri...
[ 3, 2, 1, 1 ]
[]
[]
[ "fmpp", "freemarker", "preprocessor", "python", "template_engine" ]
stackoverflow_0000427095_fmpp_freemarker_preprocessor_python_template_engine.txt
Q: How do I search for unpublished Plone content in an IPython debug shell? I like to use IPython's zope profile to inspect my Plone instance, but a few annoying permissions differences come up compared to inserting a breakpoint and hitting it with the admin user. For example, I would like to iterate over the content...
How do I search for unpublished Plone content in an IPython debug shell?
I like to use IPython's zope profile to inspect my Plone instance, but a few annoying permissions differences come up compared to inserting a breakpoint and hitting it with the admin user. For example, I would like to iterate over the content objects in an unpublished testing folder. This query will return no results i...
[ "here's the (very dirty) code I use to manage my plone app from the debug shell. It may requires some updates depending on your versions of Zope and Plone.\nfrom sys import stdin, stdout, exit\nimport base64\nfrom thread import get_ident\nfrom ZPublisher.HTTPRequest import HTTPRequest\nfrom ZPublisher.HTTPResponse ...
[ 2, 1 ]
[]
[]
[ "plone", "python" ]
stackoverflow_0000279119_plone_python.txt
Q: Python 3.0 and language evolution Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity? Also, do you believe that this is how programming langua...
Python 3.0 and language evolution
Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity? Also, do you believe that this is how programming languages should evolve or is the price to pa...
[ "The only language I can think of to attempt such a mid-stream change would be Perl. Of course, Python is beating Perl to that particular finish line by releasing first. It should be noted, however, that Perl's changes are much more extensive than Python's and likely will be harder to detangle.\n(There's a price fo...
[ 16, 13, 9, 7, 6, 4, 4, 2, 1, 1, 0, 0 ]
[]
[]
[ "programming_languages", "python", "python_3.x" ]
stackoverflow_0000273524_programming_languages_python_python_3.x.txt
Q: Is it possible to implement Python code-completion in TextMate? PySmell seems like a good starting point. I think it should be possible, PySmell's idehelper.py does a majority of the complex stuff, it should just be a case of giving it the current line, offering up the completions (the bit I am not sure about) and...
Is it possible to implement Python code-completion in TextMate?
PySmell seems like a good starting point. I think it should be possible, PySmell's idehelper.py does a majority of the complex stuff, it should just be a case of giving it the current line, offering up the completions (the bit I am not sure about) and then replacing the line with the selected one. >>> import idehelper ...
[ "EDIT: I've actually took your code above and integrated into a command. It will properly show a completion list for you to choose.\nYou can grab it here: http://github.com/orestis/pysmell/tree/master (hit download and do python setup.py install). It's rough but it works. - please report any errors on http://code.g...
[ 9, 4, 1, 0 ]
[]
[]
[ "autocomplete", "python", "text_editor", "textmate" ]
stackoverflow_0000221339_autocomplete_python_text_editor_textmate.txt
Q: Ordered lists in django i have very simple problem. I need to create model, that represent element of ordered list. This model can be implemented like this: class Item(models.Model): data = models.TextField() order = models.IntegerField() or like this: class Item(models.Model): data = models.TextField...
Ordered lists in django
i have very simple problem. I need to create model, that represent element of ordered list. This model can be implemented like this: class Item(models.Model): data = models.TextField() order = models.IntegerField() or like this: class Item(models.Model): data = models.TextField() next = models.ForeignK...
[ "Essentially, the second solution you propose is a linked list. Linked list implemented at the database level are usually not a good idea. To retrieve a list of n elements, you will need n database access (or use complicated queries). Performance wise, retrieving a list in O(n) is awfully not efficient.\nIn regular...
[ 21, 6 ]
[ "There is another solution.\nclass Item(models.Model):\n data = models.TextField()\n\nYou can just pickle or marshal Python list into the data field and the load it up. This one is good for updating and reading, but not for searching e.g. fetching all lists that contain a specific item.\n" ]
[ -6 ]
[ "django", "django_models", "python" ]
stackoverflow_0000428149_django_django_models_python.txt
Q: Measure load time for python cgi script? I use python cgi for our intranet application. When I measure time, the script takes 4s to finish. But after that, it still takes another 11s to show the screen in the browser. The screen is build with tables (size: 10 KB, 91 KB uncompressed) and has a large css file (5 KB...
Measure load time for python cgi script?
I use python cgi for our intranet application. When I measure time, the script takes 4s to finish. But after that, it still takes another 11s to show the screen in the browser. The screen is build with tables (size: 10 KB, 91 KB uncompressed) and has a large css file (5 KB, 58 KB uncompressed). I used YSlow and did as...
[ "I think I'd grab a copy of Ethereal and watch the TCP connection between the browser and the script, if I were concerned about whether the server is not getting its job done in an acceptable amount of time. If you see the TCP socket close before that 11s gap, you know that your issue is entirely on the browser si...
[ 1, 1 ]
[]
[]
[ "browser", "cgi", "css", "html", "python" ]
stackoverflow_0000428704_browser_cgi_css_html_python.txt
Q: Can I use urllib to submit a SOAP request? I have a SOAP request that is known to work using a tool like, say, SoapUI, but I am trying to get it to work using urllib. This is what I have tried so far and it did not work: import urllib f = "".join(open("ws_request_that_works_in_soapui", "r").readlines()) urllib.url...
Can I use urllib to submit a SOAP request?
I have a SOAP request that is known to work using a tool like, say, SoapUI, but I am trying to get it to work using urllib. This is what I have tried so far and it did not work: import urllib f = "".join(open("ws_request_that_works_in_soapui", "r").readlines()) urllib.urlopen('http://url.com/to/Router?wsdl', f) I have...
[ "Well, I answered my own question\nimport httplib\n\nf = \"\".join(open('ws_request', 'r'))\n\nwebservice = httplib.HTTP('localhost', 8083)\nwebservice.putrequest(\"POST\", \"Router?wsdl\")\nwebservice.putheader(\"User-Agent\", \"Python post\")\nwebservice.putheader(\"Content-length\", \"%d\" % len(f))\nwebservice....
[ 8, 3 ]
[]
[]
[ "python", "soap" ]
stackoverflow_0000429164_python_soap.txt
Q: Best way to poll a web service (eg, for a twitter app) I need to poll a web service, in this case twitter's API, and I'm wondering what the conventional wisdom is on this topic. I'm not sure whether this is important, but I've always found feedback useful in the past. A couple scenarios I've come up with: The que...
Best way to poll a web service (eg, for a twitter app)
I need to poll a web service, in this case twitter's API, and I'm wondering what the conventional wisdom is on this topic. I'm not sure whether this is important, but I've always found feedback useful in the past. A couple scenarios I've come up with: The querying process starts every X seconds, eg a cron job runs a p...
[ "\"Do I just run a python script that doesn't end?\"\nHow is this unfamiliar territory?\nimport time\npolling_interval = 36.0 # (100 requests in 3600 seconds)\nrunning= True\nwhile running:\n start= time.clock()\n poll_twitter()\n anything_else_that_seems_important()\n work_duration = time.clock() - sta...
[ 5, 0 ]
[]
[]
[ "polling", "python", "twitter" ]
stackoverflow_0000430226_polling_python_twitter.txt
Q: Draw rounded corners on photo with PIL My site is full of rounded corners on every box and picture, except for the thumbnails of user uploaded photos. How can I use the Python Imaging Library to 'draw' white or transparent rounded corners onto each thumbnail? A: From Fredrik Lundh: create a mask image with round...
Draw rounded corners on photo with PIL
My site is full of rounded corners on every box and picture, except for the thumbnails of user uploaded photos. How can I use the Python Imaging Library to 'draw' white or transparent rounded corners onto each thumbnail?
[ "From Fredrik Lundh:\ncreate a mask image with round corners (either with your favourite image \neditor or using ImageDraw/aggdraw or some such).\nin your program, load the mask image, and cut out the four corners using \n\"crop\".\nthen, for each image, create a thumbnail as usual, and use the corner \nmasks on th...
[ 7, 0 ]
[]
[]
[ "python", "python_imaging_library", "rounded_corners" ]
stackoverflow_0000430379_python_python_imaging_library_rounded_corners.txt
Q: Scripting LMMS from Python Recently I asked about scripting FruityLoops or Reason from Python, which didn't turn up much. Today I found LMMS, a free-software FruityLoops clone. So, similarly. Has anyone tried scripting this from Python (or similar)? Is there an API or wrapper for accessing its resources from outsi...
Scripting LMMS from Python
Recently I asked about scripting FruityLoops or Reason from Python, which didn't turn up much. Today I found LMMS, a free-software FruityLoops clone. So, similarly. Has anyone tried scripting this from Python (or similar)? Is there an API or wrapper for accessing its resources from outside? If not, what would be the ri...
[ "It seems you can write plugins for LMMS using C++. By embedding Python in the C++ plugin you can effectively script the program in Python. \n", "Look at http://www.csounds.com/ for an approach to scripting music synth programs in Python.\n", "You can connect pretty much everything in LMMS to a MIDI input. Try ...
[ 5, 0, 0 ]
[]
[]
[ "audio_player", "python" ]
stackoverflow_0000427037_audio_player_python.txt
Q: Convert CVS/SVN to a Programming Snippets Site I use cvs to maintain all my python snippets, notes, c, c++ code. As the hosting provider provides a public web- server also, I was thinking that I should convert the cvs automatically to a programming snippets website. cvsweb is not what I mean. doxygen is for a co...
Convert CVS/SVN to a Programming Snippets Site
I use cvs to maintain all my python snippets, notes, c, c++ code. As the hosting provider provides a public web- server also, I was thinking that I should convert the cvs automatically to a programming snippets website. cvsweb is not what I mean. doxygen is for a complete project and to browse the self-referencing co...
[ "Run Trac on the server linked to the (svn) repository. The Trac wiki can conveniently refer to files and changesets. You get TODO tickets, too.\n", "enscript or pygmentize (part of pygments) can be used to convert code to HTML. You can use a custom header or footer to link to the actual code for download.\n", ...
[ 3, 1, 0 ]
[]
[]
[ "cvs", "python", "rest", "svn", "web_applications" ]
stackoverflow_0000408621_cvs_python_rest_svn_web_applications.txt
Q: Regular expression: replace the suffix of a string ending in '.js' but not 'min.js' Assume infile is a variable holding the name of an input file, and similarly outfile for output file. If infile ends in .js, I'd like to replace with .min.js and that's easy enough (I think). outfile = re.sub(r'\b.js$', '.min.js',...
Regular expression: replace the suffix of a string ending in '.js' but not 'min.js'
Assume infile is a variable holding the name of an input file, and similarly outfile for output file. If infile ends in .js, I'd like to replace with .min.js and that's easy enough (I think). outfile = re.sub(r'\b.js$', '.min.js', infile) But my question is if infile ends in .min.js, then I do not want the substitutio...
[ "You want to do a negative lookbehind assertion. For instance,\noutfile = re.sub(r\"(?<!\\.min)\\.js$\", \".min.js\", infile)\n\nYou can find more about this here: http://docs.python.org/library/re.html#regular-expression-syntax\n", "For tasks this simple, there's no need for regexps. String methods can be more r...
[ 9, 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000430047_python_regex.txt
Q: How to process a YAML stream in Python I have a command line app the continuously outputs YAML data in the form: - col0: datum0 col1: datum1 col2: datum2 - col0: datum0 col1: datum1 col2: datum2 ... It does this for all of eternity. I would like to write a Python script that continuously reads each of th...
How to process a YAML stream in Python
I have a command line app the continuously outputs YAML data in the form: - col0: datum0 col1: datum1 col2: datum2 - col0: datum0 col1: datum1 col2: datum2 ... It does this for all of eternity. I would like to write a Python script that continuously reads each of these records. The PyYAML library seems best a...
[ "Here is what I've ended up using since there does not seem to be a built-in method for accomplishing what I want. This function should be generic enough that it can read in a stream of YAML and return top-level objects as they are encountered.\ndef streamInYAML(stream):\n y = stream.readline()\n cont = 1\n ...
[ 4, 2 ]
[]
[]
[ "command_line", "python", "streaming", "yaml" ]
stackoverflow_0000429162_command_line_python_streaming_yaml.txt
Q: Regex for links in html text I hope this question is not a RTFM one. I am trying to write a Python script that extracts links from a standard HTML webpage (the <link href... tags). I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links? Ad...
Regex for links in html text
I hope this question is not a RTFM one. I am trying to write a Python script that extracts links from a standard HTML webpage (the <link href... tags). I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links? Adam UPDATE: I am actually looking f...
[ "Regexes with HTML get messy. Just use a DOM parser like Beautiful Soup.\n", "As others have suggested, if real-time-like performance isn't necessary, BeautifulSoup is a good solution:\nimport urllib2\nfrom BeautifulSoup import BeautifulSoup\n\nhtml = urllib2.urlopen(\"http://www.google.com\").read()\nsoup = Be...
[ 17, 8, 5, 4, 3, 1, 1, 0 ]
[]
[]
[ "href", "html", "hyperlink", "python", "regex" ]
stackoverflow_0000430966_href_html_hyperlink_python_regex.txt
Q: Why do managed attributes just work for class attributes and not for instance attributes in python? To illustrate the question check the following code: class MyDescriptor(object): def __get__(self, obj, type=None): print "get", self, obj, type return self._v def __set__(self, obj, value): self._v ...
Why do managed attributes just work for class attributes and not for instance attributes in python?
To illustrate the question check the following code: class MyDescriptor(object): def __get__(self, obj, type=None): print "get", self, obj, type return self._v def __set__(self, obj, value): self._v = value print "set", self, obj, value return None class SomeClass1(object): m = MyDescriptor()...
[ "To answer your second question, where is _v?\nYour version of the descriptor keeps _v in the descriptor itself. Each instance of the descriptor (the class-level instance SomeClass1, and all of the object-level instances in objects of class SomeClass2 will have distinct values of _v.\nLook at this version. This ...
[ 3, 3, 0 ]
[]
[]
[ "attributes", "descriptor", "python" ]
stackoverflow_0000428264_attributes_descriptor_python.txt
Q: Unpack to unknown number of variables? How could I unpack a tuple of unknown to, say, a list? I have a number of columns of data and they get split up into a tuple by some function. I want to unpack this tuple to variables but I do not know how many columns I will have. Is there any way to dynamically unpack it to...
Unpack to unknown number of variables?
How could I unpack a tuple of unknown to, say, a list? I have a number of columns of data and they get split up into a tuple by some function. I want to unpack this tuple to variables but I do not know how many columns I will have. Is there any way to dynamically unpack it to as many variables as I need?
[ "You can use the asterisk to unpack a variable length, for instance:\nfoo, bar, *other = funct()\n\nThis should put the first item into foo, the second into bar, and all the rest into other.\nUpdate: I forgot to mention that this is Python 3.0 compatible only.\n", "Unpack the tuple to a list?\nl = list(t)\n\n", ...
[ 35, 10, 4 ]
[]
[]
[ "casting", "iterable_unpacking", "python" ]
stackoverflow_0000431944_casting_iterable_unpacking_python.txt
Q: Restarting a Python Interpreter Quietly I have a python interpreter embedded inside an application. The application takes a long time to start up and I have no ability to restart the interpreter without restarting the whole application. What I would like to do is to essentially save the state of the interpreter an...
Restarting a Python Interpreter Quietly
I have a python interpreter embedded inside an application. The application takes a long time to start up and I have no ability to restart the interpreter without restarting the whole application. What I would like to do is to essentially save the state of the interpreter and return to that state easily. I started by s...
[ "Try this code from ActiveState recipes: http://code.activestate.com/recipes/572213/\nIt extends pickle so it supports pickling anything defined in the shell console. Theoretically you should just be able to pickle the main module, according to their documentation:\nimport savestate, pickle, __main__\npickle.dump(...
[ 5, 1, 1, 0, 0 ]
[]
[]
[ "interpreter", "python" ]
stackoverflow_0000431432_interpreter_python.txt
Q: when to delete user's session I'm writing a webapp that will only be used by authenticated users. Some temporary databases and log files will be created during each user session. I'd like to erase all these temp files when the session is finished. Obviously, a logout or window close event would be sufficient to c...
when to delete user's session
I'm writing a webapp that will only be used by authenticated users. Some temporary databases and log files will be created during each user session. I'd like to erase all these temp files when the session is finished. Obviously, a logout or window close event would be sufficient to close the session, but in some cases...
[ "User sessions should have a timeout value and should be closed when the timeout expires or the user logs out. Log out is an obvious time to do this and the time out needs to be there in case the user navigates away from your application without logging out.\n", "A cron job to clean up any expired session data i...
[ 1, 1, 0 ]
[]
[]
[ "python", "session" ]
stackoverflow_0000432115_python_session.txt
Q: How to assign a new class attribute via __dict__? I want to assign a class attribute via a string object - but how? Example: class test(object): pass a = test() test.value = 5 a.value # -> 5 test.__dict__['value'] # -> 5 # BUT: attr_name = 'next_value' test.__dict__[attr_name] = 10 # -> 'dictproxy' object doe...
How to assign a new class attribute via __dict__?
I want to assign a class attribute via a string object - but how? Example: class test(object): pass a = test() test.value = 5 a.value # -> 5 test.__dict__['value'] # -> 5 # BUT: attr_name = 'next_value' test.__dict__[attr_name] = 10 # -> 'dictproxy' object does not support item assignment
[ "There is a builtin function for this:\nsetattr(test, attr_name, 10)\n\nReference: http://docs.python.org/library/functions.html#setattr\nExample:\n>>> class a(object): pass\n>>> a.__dict__['wut'] = 4\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: 'dictproxy' object does no...
[ 79 ]
[]
[]
[ "attributes", "class", "oop", "python" ]
stackoverflow_0000432786_attributes_class_oop_python.txt
Q: Python Library to Generate VCF Files? Know of any good libraries for this? I did some searches and didn't come across anything. Someone somewhere must have done this before, I hate to reinvent the wheel. A: I would look at: http://vobject.skyhouseconsulting.com/usage.html (look under "Usage examples") Very eas...
Python Library to Generate VCF Files?
Know of any good libraries for this? I did some searches and didn't come across anything. Someone somewhere must have done this before, I hate to reinvent the wheel.
[ "I would look at:\nhttp://vobject.skyhouseconsulting.com/usage.html (look under \"Usage examples\")\nVery easy parsing and generation of both vCal and vCard.\n", "PyCoCuMa appears to have a VCF parser built into it, and it'll generate VCard output. You might have some luck with it. I played around with it a bit; ...
[ 8, 2 ]
[]
[]
[ "python", "vcf_vcard" ]
stackoverflow_0000433331_python_vcf_vcard.txt
Q: Filtering a complete date in django? There are several filter methods for dates (year,month,day). If I want to match a full date, say 2008/10/18, is there a better way than this: Entry.objects.filter(pub_date__year=2008).filter(pub_date__month=10).filter(pub_date__day=18) A: How about using a datetime object. Fo...
Filtering a complete date in django?
There are several filter methods for dates (year,month,day). If I want to match a full date, say 2008/10/18, is there a better way than this: Entry.objects.filter(pub_date__year=2008).filter(pub_date__month=10).filter(pub_date__day=18)
[ "How about using a datetime object. For example:\nfrom datetime import datetime\nEntry.objects.filter(pub_date=datetime(2008, 10, 18))\n\n" ]
[ 10 ]
[]
[]
[ "date", "django", "django_queryset", "filter", "python" ]
stackoverflow_0000433507_date_django_django_queryset_filter_python.txt
Q: Shorthand adding/appending in Python I like that in PHP I can do the following $myInteger++; $myString += 'more text'; With Python I must do the following myInteger = myInteger + 1 myString = myString + "more text" Is there a better way to add or append to a variable in Python? A: Python doesn't have the incre...
Shorthand adding/appending in Python
I like that in PHP I can do the following $myInteger++; $myString += 'more text'; With Python I must do the following myInteger = myInteger + 1 myString = myString + "more text" Is there a better way to add or append to a variable in Python?
[ "Python doesn't have the increment (++) and decrement (--) operators, but it does have the += operator (and -=, etc.) so you can do this:\nmyInteger += 1\nmyString += \"more text\"\n\n", "You could do it in the same way you are doing it in PHP:\nvar += 1\n\nBut my advice is to write it down clear:\nvar = var + 1\...
[ 35, 3 ]
[]
[]
[ "python" ]
stackoverflow_0000433795_python.txt
Q: Is late binding consistent with the philosophy of "readibility counts"? I am sorry all - I am not here to blame Python. This is just a reflection on whether what I believe is right. Being a Python devotee for two years, I have been writing only small apps and singing Python's praises wherever I go. I recently had ...
Is late binding consistent with the philosophy of "readibility counts"?
I am sorry all - I am not here to blame Python. This is just a reflection on whether what I believe is right. Being a Python devotee for two years, I have been writing only small apps and singing Python's praises wherever I go. I recently had the chance to read Django's code, and have started wondering if Python really...
[ "The code fragment you present is fairly atypical (which might also because you probably made it up):\n\nyou wouldn't normally have an instance variable (self.c) that is a floating point number at some point, and a string at a different point. It should be either a number or a string all the time.\nyou normally don...
[ 14, 5, 3, 3, 2, 2, 2, 0 ]
[]
[]
[ "python", "readability" ]
stackoverflow_0000433662_python_readability.txt
Q: extracting stream from pdf in python How can I extract the part of this stream (the one named BLABLABLA) from the pdf file which contains it?? <</Contents 583 0 R/CropBox[0 0 595.22 842]/MediaBox[0 0 595.22 842]/Parent 29 0 /Resources<</ColorSpace<</CS0 563 0 R>>/ExtGState<</GS0 568 0 R>>/Font<</TT0 559 0 R/TT1 5...
extracting stream from pdf in python
How can I extract the part of this stream (the one named BLABLABLA) from the pdf file which contains it?? <</Contents 583 0 R/CropBox[0 0 595.22 842]/MediaBox[0 0 595.22 842]/Parent 29 0 /Resources<</ColorSpace<</CS0 563 0 R>>/ExtGState<</GS0 568 0 R>>/Font<</TT0 559 0 R/TT1 560 0 R/TT2 561 0 R/TT3 562 0 R>>/ProcSet[/...
[ "IIUC, a stream in a PDF is just a sequence of binary data. I think you are wanting to extract part of an object. Are you wanting a standard object, like an image or text? It would be a lot easier to give you example code if there was a real example.\nThis might help get you started:\nimport pyPdf\npdf = pyPdf.P...
[ 1 ]
[]
[]
[ "pdf", "pypdf", "python", "reportlab", "stream" ]
stackoverflow_0000429437_pdf_pypdf_python_reportlab_stream.txt
Q: TKinter windows do not appear when using multiprocessing on Linux I want to spawn another process to display an error message asynchronously while the rest of the application continues. I'm using the multiprocessing module in Python 2.6 to create the process and I'm trying to display the window with TKinter. Thi...
TKinter windows do not appear when using multiprocessing on Linux
I want to spawn another process to display an error message asynchronously while the rest of the application continues. I'm using the multiprocessing module in Python 2.6 to create the process and I'm trying to display the window with TKinter. This code worked okay on Windows, but running it on Linux the TKinter wind...
[ "This discussion could be helpful.\n\nHere's some sample problems I found: \n\nWhile the multiprocessing module follows threading closely, it's definitely not an exact match. One example: since parameters to a\n process must be pickleable, I had to go through a lot of code\n changes to avoid passing Tkinter objec...
[ 4, 0 ]
[]
[]
[ "linux", "multiprocessing", "python", "tkinter" ]
stackoverflow_0000410469_linux_multiprocessing_python_tkinter.txt
Q: Analyse python list with algorithm for counting occurences over date ranges The following shows the structure of some data I have (format: a list of lists) data = [ [1,2008-12-01], [1,2008-12-01], [2,2008-12-01] ... (the lists continue) ] The dates range from 2008-12-01 to 2008-12-25. The first field id...
Analyse python list with algorithm for counting occurences over date ranges
The following shows the structure of some data I have (format: a list of lists) data = [ [1,2008-12-01], [1,2008-12-01], [2,2008-12-01] ... (the lists continue) ] The dates range from 2008-12-01 to 2008-12-25. The first field identifies a user by id, the second field (a date field) shows when this user visit...
[ "Your result is a dictionary, right?\n{ userNumber: setOfDays }\n\nHow about this to get started.\nfrom collections import defaultdict\nvisits = defaultdict(set)\nfor user, date in someList:\n visits[user].add(date)\n\nThis gives you a dictionary with a set of dates on which they visited. \ncounts = defaultdict...
[ 4, 1, 1, 0, 0, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0000433669_algorithm_python.txt
Q: What is the easiest way to export data from a live Google App Engine application? I'm especially interested in solutions with source code available (Django independency is a plus, but I'm willing to hack my way through) A: You can, of course, write your own handler. Other than that, your options currently are li...
What is the easiest way to export data from a live Google App Engine application?
I'm especially interested in solutions with source code available (Django independency is a plus, but I'm willing to hack my way through)
[ "You can, of course, write your own handler. Other than that, your options currently are limited to:\n\ngae-rest, which provides a RESTful interface to the datastore.\napprocket, a tool for replicating between MySQL and App Engine.\nThe amusingly named GAEBAR - Google App Engine Backup and Restore.\n\n", "Update:...
[ 6, 3 ]
[]
[]
[ "frameworks", "google_app_engine", "python" ]
stackoverflow_0000426820_frameworks_google_app_engine_python.txt
Q: How do I install a Python extension module using distutils? I'm working on a Python package named "lehmer" that includes a bunch of extension modules written in C. Currently, I have a single extension module, "rng". I am using Python's Distutils to build and install the module. I can compile and install the module...
How do I install a Python extension module using distutils?
I'm working on a Python package named "lehmer" that includes a bunch of extension modules written in C. Currently, I have a single extension module, "rng". I am using Python's Distutils to build and install the module. I can compile and install the module, but when I try to import the module using import lehmer.rng or ...
[ "For the record (and because I am tired of seeing this marked as unanswered), here were the problems:\n\nSince the current directory is automatically added to the Python packages path, the interpreter was first looking in the current directory for packages; since some C modules were not compiled in the current dire...
[ 4 ]
[]
[]
[ "distutils", "module", "python" ]
stackoverflow_0000302867_distutils_module_python.txt
Q: Ensuring contact form email isn't lost (python) I have a website with a contact form. User submits name, email and message and the site emails me the details. Very occasionally my server has a problem with it's email system and so the user gets an error and those contact details are lost. (Don't say: get a better ...
Ensuring contact form email isn't lost (python)
I have a website with a contact form. User submits name, email and message and the site emails me the details. Very occasionally my server has a problem with it's email system and so the user gets an error and those contact details are lost. (Don't say: get a better server, any server can have email go down now and the...
[ "When we implement email sending functionality in our environment we do it in a decoupled way. So for example a user would submit their data which would get stored in a database. We then have a separate service that runs, queries the database and sends out email. That way if there are ever any email server issue...
[ 8, 4, 2 ]
[]
[]
[ "data_formats", "email", "python", "race_condition" ]
stackoverflow_0000436003_data_formats_email_python_race_condition.txt
Q: Python-Regex, what's going on here? I've got a book on python recently and it's got a chapter on Regex, there's a section of code which I can't really understand. Can someone explain exactly what's going on here (this section is on Regex groups)? >>> my_regex = r'(?P<zip>Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)' >>> a...
Python-Regex, what's going on here?
I've got a book on python recently and it's got a chapter on Regex, there's a section of code which I can't really understand. Can someone explain exactly what's going on here (this section is on Regex groups)? >>> my_regex = r'(?P<zip>Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)' >>> addrs = "Zip: 10010 State: NY" >>> y = re....
[ "regex definition:\n(?P<zip>...)\n\nCreates a named group \"zip\"\nZip:\\s*\n\nMatch \"Zip:\" and zero or more whitespace characters\n\\d\n\nMatch a digit\n\\w\n\nMatch a word character [A-Za-z0-9_]\ny.groupdict('zip')\n\nThe groupdict method returns a dictionary with named groups as keys and their matches as value...
[ 8, 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000433388_python_regex.txt
Q: What should "value_from_datadict" method of a custom form widget return? I'm trying to build my own custom django form widgets (putting them in widgets.py of my project directory). What should the value "value_from_datadict()" return? Is it returning a string or the actual expected value of the field? I'm buildi...
What should "value_from_datadict" method of a custom form widget return?
I'm trying to build my own custom django form widgets (putting them in widgets.py of my project directory). What should the value "value_from_datadict()" return? Is it returning a string or the actual expected value of the field? I'm building my own version of a split date/time widget using JQuery objects, what shoul...
[ "For value_from_datadict() you want to return the value you expect or None. The source in django/forms/widgets.py provides some examples.\nBut you should be able to build a DatePicker widget by just providing a render method:\nDATE_FORMAT = '%m/%d/%y'\n\nclass DatePickerWidget(widgets.Widget):\n def render(self...
[ 5, 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0000436944_django_django_forms_python.txt
Q: Is there a way to automatically generate a list of columns that need indexing? The beauty of ORM lulled me into a soporific sleep. I've got an existing Django app with a lack of database indexes. Is there a way to automatically generate a list of columns that need indexing? I was thinking maybe some middleware tha...
Is there a way to automatically generate a list of columns that need indexing?
The beauty of ORM lulled me into a soporific sleep. I've got an existing Django app with a lack of database indexes. Is there a way to automatically generate a list of columns that need indexing? I was thinking maybe some middleware that logs which columns are involved in WHERE clauses? but is there anything built into...
[ "Yes, there is.\nIf you take a look at the slow query log, there's an option --log-queries-not-using-indexes\n", "No.\nAdding indexes willy-nilly to all \"slow\" queries will also slow down inserts, updates and deletes.\nIndexes are a balancing act between fast queries and fast changes. There is no general or \"...
[ 4, 4 ]
[]
[]
[ "database", "django", "django_models", "mysql", "python" ]
stackoverflow_0000438559_database_django_django_models_mysql_python.txt
Q: Python data structure: SQL, XML, or .py file What is the best way to store large amounts of data in python, given one (or two) 500,000 item+ dictionary used for undirected graph searching? I've been considering a few options such as storing the data as XML: <key name="a"> <value data="1" /> <value data="2"...
Python data structure: SQL, XML, or .py file
What is the best way to store large amounts of data in python, given one (or two) 500,000 item+ dictionary used for undirected graph searching? I've been considering a few options such as storing the data as XML: <key name="a"> <value data="1" /> <value data="2" /> </key> <key name="b"> ... or in a python file...
[ "The Python source technique absolutely rules.\nXML is slow to parse, and relatively hard to read by people. That's why companies like Altova are in business -- XML isn't pleasant to edit.\nPython source db = {\"a\": [1, 2], \"b\": ...} is \n\nFast to parse.\nEasy to read by people. \n\nIf you have programs that ...
[ 6, 2, 1, 0, 0, 0 ]
[]
[]
[ "data_structures", "graph", "python", "sql", "xml" ]
stackoverflow_0000438185_data_structures_graph_python_sql_xml.txt
Q: Help in FileNotFoundException -Python This is my code: try: import clr, sys from xml.dom.minidom import parse import datetime sys.path.append("C:\\teest") clr.AddReference("TCdll") from ClassLibrary1 import Class1 cl = Class1() except ( ImportError ) : print "Module may not be exist...
Help in FileNotFoundException -Python
This is my code: try: import clr, sys from xml.dom.minidom import parse import datetime sys.path.append("C:\\teest") clr.AddReference("TCdll") from ClassLibrary1 import Class1 cl = Class1() except ( ImportError ) : print "Module may not be existing " My TCdll is in C:\test.I just gave ...
[ "You need to find out how clr.AddReference maps to a file name.\nEDIT:\nI think you're asking how to catch the exception from the AddReference call?\nReplace:\nclr.AddReference(\"TCdll\")\n\nwith:\ntry:\n clr.AddReference(\"TCdll\")\nexcept FileNotFoundException,e:\n print \"Failed to find reference\",e\n ...
[ 4 ]
[]
[]
[ "filenotfoundexception", "handler", "python" ]
stackoverflow_0000438733_filenotfoundexception_handler_python.txt
Q: How do you create a list like PHP's in Python? This is an incredibly simple question (I'm new to Python). I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it. As far as I can tell, this is not possible with Python, so I've got the maximum value I mig...
How do you create a list like PHP's in Python?
This is an incredibly simple question (I'm new to Python). I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it. As far as I can tell, this is not possible with Python, so I've got the maximum value I might want to use as an index, but I can't figure out h...
[ "Depending on how you are going to use the list, it may be that you actually want a dictionary. This will work:\nd = {}\n\nfor row in rows:\n c = list_of_categories.index(row[\"id\"])\n print c\n d[c] = row[\"name\"]\n\n... or more compactly:\nd = dict((list_of_categories.index(row['id']), row['name']) for row ...
[ 10, 4, 2, 2, 1, 1, 1, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0000438813_list_python.txt
Q: Debugging pylons in Eclipse under Ubuntu I am trying to get pylons to debug in Eclipse under Ubuntu. Specifically. I am not sure what to use for the 'Main Module' on the Run configurations dialog. (this is a similar question on stackoverflow, but I think it applies to windows as I can't find paster-script.py on my...
Debugging pylons in Eclipse under Ubuntu
I am trying to get pylons to debug in Eclipse under Ubuntu. Specifically. I am not sure what to use for the 'Main Module' on the Run configurations dialog. (this is a similar question on stackoverflow, but I think it applies to windows as I can't find paster-script.py on my system) Can anyone help?
[ "I've managed to fix this now.\nIn Window>Preferences>Pydev>Interpreter-Python remove the python interpreter and reload it (select New) after installing pylons.\nIn the Terminal cd into the projects directory. Then type sudo python setup.py develop \nNot sure what this does, but it does the trick (if any one wants ...
[ 4, 1, 1, 0 ]
[]
[]
[ "debugging", "eclipse", "pylons", "python", "ubuntu" ]
stackoverflow_0000312599_debugging_eclipse_pylons_python_ubuntu.txt
Q: Python: Problem with overloaded constructors WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions! I have written the following code, however I get the following exception: Message File Name Line Position Traceback Node 31 ...
Python: Problem with overloaded constructors
WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions! I have written the following code, however I get the following exception: Message File Name Line Position Traceback Node 31 exceptions.TypeError: this constructor takes no a...
[ "I'm going to assume you're coming from a Java-ish background, so there are a few key differences to point out.\nclass Computer(object):\n \"\"\"Docstrings are used kind of like Javadoc to document classes and\n members. They are the first thing inside a class or method.\n\n You probably want to extend ob...
[ 36, 5, 4, 2, 2, 1, 1, 1 ]
[]
[]
[ "constructor_overloading", "exception", "python" ]
stackoverflow_0000312695_constructor_overloading_exception_python.txt
Q: unicode() vs. str.decode() for a utf8 encoded byte string (python 2.x) Is there any reason to prefer unicode(somestring, 'utf8') as opposed to somestring.decode('utf8')? My only thought is that .decode() is a bound method so python may be able to resolve it more efficiently, but correct me if I'm wrong. A: It's ...
unicode() vs. str.decode() for a utf8 encoded byte string (python 2.x)
Is there any reason to prefer unicode(somestring, 'utf8') as opposed to somestring.decode('utf8')? My only thought is that .decode() is a bound method so python may be able to resolve it more efficiently, but correct me if I'm wrong.
[ "It's easy to benchmark it:\n>>> from timeit import Timer\n>>> ts = Timer(\"s.decode('utf-8')\", \"s = 'ééé'\")\n>>> ts.timeit()\n8.9185450077056885\n>>> tu = Timer(\"unicode(s, 'utf-8')\", \"s = 'ééé'\") \n>>> tu.timeit()\n2.7656929492950439\n>>> \n\nObviously, unicode() is faster.\nFWIW, I don't know where you ge...
[ 23, 23 ]
[]
[]
[ "python", "unicode", "utf_8" ]
stackoverflow_0000440320_python_unicode_utf_8.txt
Q: Extracting Embedded Images From Outlook Email I am using Microsoft's CDO (Collaboration Data Objects) to programmatically read mail from an Outlook mailbox and save embedded image attachments. I'm trying to do this from Python using the Win32 extensions, but samples in any language that uses CDO would be helpful....
Extracting Embedded Images From Outlook Email
I am using Microsoft's CDO (Collaboration Data Objects) to programmatically read mail from an Outlook mailbox and save embedded image attachments. I'm trying to do this from Python using the Win32 extensions, but samples in any language that uses CDO would be helpful. So far, I am here... The following Python code wil...
[ "Difference in versions of OS/Outlook/CDO is what might be the source of confusion, so here are the steps to get it working on WinXP/Outlook 2007/CDO 1.21:\n\ninstall CDO 1.21\ninstall win32com.client\ngoto C:\\Python25\\Lib\\site-packages\\win32com\\client\\ directory run the following:\n\npython makepy.py\n\nfrom...
[ 5 ]
[]
[]
[ "cdo.message", "email", "outlook", "python" ]
stackoverflow_0000440356_cdo.message_email_outlook_python.txt
Q: python, sorting a list by a key that's a substring of each element Part of a programme builds this list, [u'1 x Affinity for war', u'1 x Intellect', u'2 x Charisma', u'2 x Perception', u'3 x Population growth', u'4 x Affinity for the land', u'5 x Morale'] I'm currently trying to sort it alphabetically by the name...
python, sorting a list by a key that's a substring of each element
Part of a programme builds this list, [u'1 x Affinity for war', u'1 x Intellect', u'2 x Charisma', u'2 x Perception', u'3 x Population growth', u'4 x Affinity for the land', u'5 x Morale'] I'm currently trying to sort it alphabetically by the name of the evolution rather than by the number. Is there any way I can do t...
[ "You have to get the \"key\" from the string.\ndef myKeyFunc( aString ):\n stuff, x, label = aString.partition(' x ')\n return label\n\naList.sort( key= myKeyFunc )\n\n", "How about:\nlst.sort(key=lamdba s: s.split(' x ')[1])\n\n", "Not knowing if your items are standardized at 1 digit, 1 space, 1 'x', 1 ...
[ 23, 11, 2, 1 ]
[ "As you are trying to sort what is essentially custom data, I'd go with a custom sort.\nMerge sort\nBubble sort\nQuicksort\n" ]
[ -10 ]
[ "list", "python", "sorting" ]
stackoverflow_0000440541_list_python_sorting.txt
Q: Python classes from a for loop I've got a piece of code which contains a for loop to draw things from an XML file; for evoNode in node.getElementsByTagName('evolution'): evoName = getText(evoNode.getElementsByTagName( "type")[0].childNodes) evoId = getText(evoNode.getElementsByTagName...
Python classes from a for loop
I've got a piece of code which contains a for loop to draw things from an XML file; for evoNode in node.getElementsByTagName('evolution'): evoName = getText(evoNode.getElementsByTagName( "type")[0].childNodes) evoId = getText(evoNode.getElementsByTagName( "typeid")[0].childNodes) ...
[ "A list comprehension might be a little cleaner. I'd also move the parsing logic to the constructor to clean up the implemenation:\nclass Evolution:\n def __init__(self, node):\n self.node = node\n self.type = property(\"type\")\n self.typeid = property(\"typeid\")\n self.level = prop...
[ 4, 3 ]
[]
[]
[ "class", "for_loop", "python" ]
stackoverflow_0000440676_class_for_loop_python.txt
Q: Exception handling of a function in Python Suppose I have a function definiton: def test(): print 'hi' I get a TypeError whenever I gives an argument. Now, I want to put the def statement in try. How do I do this? A: try: test() except TypeError: print "error" A: In [1]: def test(): ...: ...
Exception handling of a function in Python
Suppose I have a function definiton: def test(): print 'hi' I get a TypeError whenever I gives an argument. Now, I want to put the def statement in try. How do I do this?
[ "try: \n test()\nexcept TypeError:\n print \"error\"\n\n", "In [1]: def test():\n ...: print 'hi'\n ...:\n\nIn [2]: try:\n ...: test(1)\n ...: except:\n ...: print 'exception'\n ...:\nexception\n\nHere is the relevant section in the tutorial\nBy the way. to fix this error...
[ 5, 1, 1, 1, 1, 0 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0000438401_exception_handling_python.txt
Q: Safe escape function for terminal output I'm looking for the equivalent of a urlencode for terminal output -- I need to make sure that garbage characters I (may) print from an external source don't end up doing funky things to my terminal, so a prepackaged function to escape special character sequences would be id...
Safe escape function for terminal output
I'm looking for the equivalent of a urlencode for terminal output -- I need to make sure that garbage characters I (may) print from an external source don't end up doing funky things to my terminal, so a prepackaged function to escape special character sequences would be ideal. I'm working in Python, but anything I can...
[ "Unfortunately \"terminal output\" is a very poorly defined criterion for filtering (see question 418176). I would suggest simply whitelisting the characters that you want to allow (which would be most of string.printable), and replacing all others with whatever escaped format you like (\\FF, %FF, etc), or even si...
[ 3, 2, 1 ]
[ "You could pipe it through strings\n./command | strings\n\nThis will strip out the non string characters\n" ]
[ -1 ]
[ "escaping", "python", "terminal" ]
stackoverflow_0000437476_escaping_python_terminal.txt
Q: How to add additional information to a many-to-many relation? I'm writing a program to manage orders and then print them. An order is an object containing the ordering person, the date and the products this person orders. I'd like to add the amount of a certain product one orderer. E.g. 3 eggs, 2 breads. Is there ...
How to add additional information to a many-to-many relation?
I'm writing a program to manage orders and then print them. An order is an object containing the ordering person, the date and the products this person orders. I'd like to add the amount of a certain product one orderer. E.g. 3 eggs, 2 breads. Is there a simpler way doing this with storm (the ORM I'm using) than splitt...
[ "What's wrong with adding extra columns to the intersection table of the many-to-many relationship? \nCREATE TABLE orders (\n person_id INT NOT NULL,\n product_id INT NOT NULL,\n quantity INT NOT NULL DEFAULT 1,\n PRIMARY KEY (person_id, product_id),\n FOREIGN KEY (person_id) REFERENCES persons(person_id),\n ...
[ 3 ]
[]
[]
[ "database", "orm", "python", "sqlite", "storm_orm" ]
stackoverflow_0000441114_database_orm_python_sqlite_storm_orm.txt
Q: PIL vs RMagick/ruby-gd For my next project I plan to create images with text and graphics. I'm comfortable with ruby, but interested in learning python. I figured this may be a good time because PIL looks like a great library to use. However, I don't know how it compares to what ruby has to offer (e.g. RMagick ...
PIL vs RMagick/ruby-gd
For my next project I plan to create images with text and graphics. I'm comfortable with ruby, but interested in learning python. I figured this may be a good time because PIL looks like a great library to use. However, I don't know how it compares to what ruby has to offer (e.g. RMagick and ruby-gd). From what I c...
[ "PIL is a good library, use it. ImageMagic (what RMagick wraps) is a very heavy library that should be avoided if possible. Its good for doing local processing of images, say, a batch photo editor, but way too processor inefficient for common image manipulation tasks for web.\nEDIT: In response to the question, P...
[ 7, 4, 3 ]
[]
[]
[ "python", "python_imaging_library", "rmagick", "ruby" ]
stackoverflow_0000439641_python_python_imaging_library_rmagick_ruby.txt
Q: Why am I seeing 'connection reset by peer' error? I am testing cogen on a Mac OS X 10.5 box using python 2.6.1. I have a simple echo server and client-pumper that creates 10,000 client connections as a test. 1000, 5000, etc. all work splendidly. However at around 10,000 connections, the server starts dropping r...
Why am I seeing 'connection reset by peer' error?
I am testing cogen on a Mac OS X 10.5 box using python 2.6.1. I have a simple echo server and client-pumper that creates 10,000 client connections as a test. 1000, 5000, etc. all work splendidly. However at around 10,000 connections, the server starts dropping random clients - the clients see 'connection reset by pe...
[ "Python's socket I/O sometimes suffers from connection reset by peer. It has to do with the Global Interpreter Lock and how threads are scheduled. I blogged some references on the subject.\nThe time.sleep(0.0001) appears to be the recommended solution because it adjusts thread scheduling and allows the socket I/...
[ 8 ]
[]
[]
[ "network_programming", "python", "sockets", "system" ]
stackoverflow_0000441374_network_programming_python_sockets_system.txt
Q: Efficient layout for a distributed python server? If I wanted to have Python distributed across multiple processors on multiple computers, what would my best approach be? If I have 3 eight-core servers, that would mean I would have to run 24 python processes. I would be using the multiprocessing library, and to sh...
Efficient layout for a distributed python server?
If I wanted to have Python distributed across multiple processors on multiple computers, what would my best approach be? If I have 3 eight-core servers, that would mean I would have to run 24 python processes. I would be using the multiprocessing library, and to share objects it looks like the best idea would be to use...
[ "I think more information would be helpful, on what sort of thing you are serving, what sort of database you'd use, what sort of latency/throughput requirements you have, etc. Lots of stuff depends on your requirements: eg. if your system is a typical server which has a lot of reads and not so many writes, and you ...
[ 3, 3, 0 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0000441061_multiprocessing_python.txt
Q: Generic catch for python I have some extremely weird behavior that seems to result in silent exceptions. How can I write a general try catch where I can debug all exceptions. Something along the lines of: try: # something that fails except e: print e A bit more about the problem at hand in detail: I have ...
Generic catch for python
I have some extremely weird behavior that seems to result in silent exceptions. How can I write a general try catch where I can debug all exceptions. Something along the lines of: try: # something that fails except e: print e A bit more about the problem at hand in detail: I have a Django app that on my comput...
[ "Exceptions are already printed by default before program termination. If you want to send the error somewhere else (not print it) you can do this:\ntry:\n something()\nexcept Exception as e:\n send_somewhere(traceback.format_exception(*sys.exc_info()))\n raise # reraises the exception\n\nnote that this fo...
[ 196, 5, 2 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0000442343_exception_python.txt
Q: How do I split email address/password string in two in Python? Lets say we have this string: [18] email@email.com:pwd: email@email.com is the email and pwd is the password. Also, lets say we have this variable with a value f = "[18] email@email.com:pwd:" I would like to know if there is a way to make two other va...
How do I split email address/password string in two in Python?
Lets say we have this string: [18] email@email.com:pwd: email@email.com is the email and pwd is the password. Also, lets say we have this variable with a value f = "[18] email@email.com:pwd:" I would like to know if there is a way to make two other variables named var1 and var2, where the var1 variable will take the e...
[ ">>> var1, var2, _ = \"[18] email@email.com:pwd:\"[5:].split(\":\")\n>>> var1, var2\n('email@email.com', 'pwd')\n\nOr if the \"[18]\" is not a fixed prefix:\n>>> var1, var2, _ = \"[18] email@email.com:pwd:\".split(\"] \")[1].split(\":\")\n>>> var1, var2\n('email@email.com', 'pwd')\n\n", "import re\nvar1, var2 = r...
[ 9, 7, 5, 1 ]
[]
[]
[ "parsing", "python", "split" ]
stackoverflow_0000436394_parsing_python_split.txt
Q: How do I create an HTTP server in Python using the first available port? I want to avoid hardcoding the port number as in the following: httpd = make_server('', 8000, simple_app) The reason I'm creating the server this way is that I want to use it as a 'kernel' for an Adobe AIR app so it will communicate using Py...
How do I create an HTTP server in Python using the first available port?
I want to avoid hardcoding the port number as in the following: httpd = make_server('', 8000, simple_app) The reason I'm creating the server this way is that I want to use it as a 'kernel' for an Adobe AIR app so it will communicate using PyAMF. Since I'm running this on the client side it is very possible that any po...
[ "The problem is that you need a known port for the application to use. But if you give a port number of 0, I believe the OS will provide you with the first available unused port.\n", "\nThe problem is that you need a known port for the application to use. But if you give a port number of 0, I believe the OS will...
[ 7, 7, 2 ]
[ "Firewalls allow you to permit or deny traffic on a port-by-port basis. For this reason alone, an application without a well-defined port should expect to run into all kinds of problems in a client installation. \nI say pick a random port, and make it very easy for the user to change the port if need be. \nHere's ...
[ -2 ]
[ "httpserver", "python" ]
stackoverflow_0000442062_httpserver_python.txt
Q: How to properly interact with a process using subprocess module I'm having problems redirecting stdio of another program using subprocess module. Just reading from stdout results in hanging, and Popen.communicate() works but it closes pipes after reading/writing. What's the easiest way to implement this? I was pla...
How to properly interact with a process using subprocess module
I'm having problems redirecting stdio of another program using subprocess module. Just reading from stdout results in hanging, and Popen.communicate() works but it closes pipes after reading/writing. What's the easiest way to implement this? I was playing around with this on windows: import subprocess proc = subprocess...
[ "Doesn't fit 100% to your example but helps to understand the underlying issue: Process P starts child C. Child C writes something to its stdout. stdout of C is a pipe which has a 4096 character buffer and the output is shorter than that. Now, C waits for some input. For C, everything is fine.\nP waits for the outp...
[ 21 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0000443057_python_subprocess.txt
Q: cascading forms in Django/else using any Pythonic framework Can anyone point to an example written in Python (django preferred) with ajax for cascading forms? Cascading Forms is basically forms whose field values change if and when another field value changes. Example Choose Country, and then States will change......
cascading forms in Django/else using any Pythonic framework
Can anyone point to an example written in Python (django preferred) with ajax for cascading forms? Cascading Forms is basically forms whose field values change if and when another field value changes. Example Choose Country, and then States will change...
[ "This is (mostly) front-end stuff.\nAs you may have noticed Django attempts to leave all the AJAX stuff up to you, so I don't think you'll find anything built in to do this.\nHowever, using JS (which is what you'll have to do in order to do this without submitting a billion forms manually), you could easily have a ...
[ 3, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000442596_django_python.txt
Q: Jython, Query multiple columns dynamically I am working with a oracle database and Jython. I can get data pulled from the database no problem. results = statement.executeQuery("select %s from %s where column_id = '%s'", % (column, table, id)) This works fine if I want to pull one column of data. Say I wanted to l...
Jython, Query multiple columns dynamically
I am working with a oracle database and Jython. I can get data pulled from the database no problem. results = statement.executeQuery("select %s from %s where column_id = '%s'", % (column, table, id)) This works fine if I want to pull one column of data. Say I wanted to loop threw a list like this: columns = ['column1'...
[ "You could simply substitute all the columns into your query as a single string, like this:\ncolumns = ['column1', 'column2', 'column3', 'column4', 'column5']\nresults = statement.executeQuery(\"select %s from %s where column_id = '%s'\" % (\",\".join(columns), table, id))\n\nBy the way, this isn't protecting again...
[ 3 ]
[]
[]
[ "jython", "oracle10g", "python" ]
stackoverflow_0000443224_jython_oracle10g_python.txt
Q: python, index errors I've got some code which draws data from an xml file but it seems to have randomly starting throwing; Traceback (most recent call last): File "C:\Users\mike\Documents\python\arl xml\turn 24 reader", line 52, in <module> unitCount = getText(evoNode.getElementsByTagName("count")[0].child...
python, index errors
I've got some code which draws data from an xml file but it seems to have randomly starting throwing; Traceback (most recent call last): File "C:\Users\mike\Documents\python\arl xml\turn 24 reader", line 52, in <module> unitCount = getText(evoNode.getElementsByTagName("count")[0].childNodes) IndexError: list in...
[ "A simple idea: check if evoNode.getElementsByTagName(\"count\") returns a non-empty list:\ncounts = evoNode.getElementsByTagName(\"count\")\nif counts:\n unitCount = getText(counts[0].childNodes)\n\nOf course, the check should be applied to all the lists retrieved by your code.\nOne Other thing, you iterate usi...
[ 2, 1 ]
[]
[]
[ "for_loop", "python", "xml" ]
stackoverflow_0000443813_for_loop_python_xml.txt
Q: How do I find out the path of the currently executing script? Duplicate of: In Python, how do I get the path and name of the file that is currently executing? I would like to find out the path to the currently executing script. I have tried os.getcwd() but that only returns the directory I ran the script from not ...
How do I find out the path of the currently executing script?
Duplicate of: In Python, how do I get the path and name of the file that is currently executing? I would like to find out the path to the currently executing script. I have tried os.getcwd() but that only returns the directory I ran the script from not the actual directory the script is stored.
[ "In Python, __file__ identifies the current Python file. Thus:\nprint \"I'm inside Python file %s\" % __file__\n\nwill print the current Python file. Note that this works in imported Python modules, as well as scripts.\n", "How about using sys.path[0] \nYou can do something like\n'print os.path.join(sys.path[...
[ 8, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000444376_python.txt
Q: How do I use a 2-d boolean array to select from a 1-d array on a per-row basis in numpy? Let me illustrate this question with an example: import numpy matrix = numpy.identity(5, dtype=bool) #Using identity as a convenient way to create an array with the invariant that there will only be one True value per row, th...
How do I use a 2-d boolean array to select from a 1-d array on a per-row basis in numpy?
Let me illustrate this question with an example: import numpy matrix = numpy.identity(5, dtype=bool) #Using identity as a convenient way to create an array with the invariant that there will only be one True value per row, the solution should apply to any array with this invariant base = numpy.arange(5,30,5) #This cou...
[ "If I understand your question correctly you can simply use matrix multiplication:\nresult = numpy.dot(matrix, base)\n\nIf the result must have the same shape as in your example just add a reshape:\nresult = numpy.dot(matrix, base).reshape((5,1))\n\nIf the matrix is not symmetric be careful about the order in dot.\...
[ 1, 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0000442218_numpy_python.txt
Q: pyPdf for IndirectObject extraction Following this example, I can list all elements into a pdf file import pyPdf pdf = pyPdf.PdfFileReader(open("pdffile.pdf")) list(pdf.pages) # Process all the objects. print pdf.resolvedObjects now, I need to extract a non-standard object from the pdf file. My object is the one...
pyPdf for IndirectObject extraction
Following this example, I can list all elements into a pdf file import pyPdf pdf = pyPdf.PdfFileReader(open("pdffile.pdf")) list(pdf.pages) # Process all the objects. print pdf.resolvedObjects now, I need to extract a non-standard object from the pdf file. My object is the one named MYOBJECT and it is a string. The p...
[ "each element in pdf.pages is a dictionary, so assuming it's on page 1, pdf.pages[0]['/MYOBJECT'] should be the element you want. \nYou can try to print that individually or poke at it with help and dir in a python prompt for more about how to get the string you want\nEdit:\nafter receiving a copy of the pdf, i fou...
[ 10, 6, 2 ]
[]
[]
[ "pdf", "pypdf", "python", "stream" ]
stackoverflow_0000436474_pdf_pypdf_python_stream.txt
Q: Good Python networking libraries for building a TCP server? I was just wondering what network libraries there are out there for Python for building a TCP/IP server. I know that Twisted might jump to mind but the documentation seems scarce, sloppy, and scattered to me. Also, would using Twisted even have a benefit...
Good Python networking libraries for building a TCP server?
I was just wondering what network libraries there are out there for Python for building a TCP/IP server. I know that Twisted might jump to mind but the documentation seems scarce, sloppy, and scattered to me. Also, would using Twisted even have a benefit over rolling my own server with select.select()?
[ "I must agree that the documentation is a bit terse but the tutorial gets you up and running quickly.\nhttp://twistedmatrix.com/projects/core/documentation/howto/tutorial/index.html\nThe event-based programming paradigm of Twisted and it's defereds might be a bit weird at the start (was for me) but it is worth the ...
[ 10, 6, 1, 1, 1 ]
[]
[]
[ "networking", "python", "twisted" ]
stackoverflow_0000441849_networking_python_twisted.txt
Q: How do I reverse Unicode decomposition using Python? Using Python 2.5, I have some text in stored in a unicode object: Dinis e Isabel, uma difı´cil relac¸a˜o conjugal e polı´tica This appears to be decomposed Unicode. Is there a generic way in Python to reverse the decomposition, so I end up with: Dinis e Isa...
How do I reverse Unicode decomposition using Python?
Using Python 2.5, I have some text in stored in a unicode object: Dinis e Isabel, uma difı´cil relac¸a˜o conjugal e polı´tica This appears to be decomposed Unicode. Is there a generic way in Python to reverse the decomposition, so I end up with: Dinis e Isabel, uma difícil relação conjugal e política
[ "I think you are looking for this:\n>>> import unicodedata \n>>> print unicodedata.normalize(\"NFC\",u\"c\\u0327\")\nç\n\n", "\nUnfortunately it seems I actually have (for example) \\u00B8 (cedilla) instead of \\u0327 (combining cedilla) in my text.\n\nEurgh, nasty! You can still do it automatically, though th...
[ 7, 5, 1 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0000446222_python_unicode.txt
Q: What's the best way to specify a proxy with username and password for an **https** connection in python? I read somewhere that currently urllib2 doesn't support authenticated https connection. My proxy uses a basic authentication only, but how to open an https based webpage through it . Please help me. Thanks. ...
What's the best way to specify a proxy with username and password for an **https** connection in python?
I read somewhere that currently urllib2 doesn't support authenticated https connection. My proxy uses a basic authentication only, but how to open an https based webpage through it . Please help me. Thanks.
[ "\"urllib2 doesn't support authenticated https connection\" False.\n # Build Handler to support HTTP Basic Authentication...\n basic_handler = urllib2.HTTPBasicAuthHandler()\n basic_handler.add_password(realm, self.urlBase, username, password)\n # Get cookies, also, to handle login\n self.cookies= co...
[ 2, 0 ]
[]
[]
[ "authentication", "https", "proxy", "python" ]
stackoverflow_0000446869_authentication_https_proxy_python.txt
Q: retrieving XMLHttpRequest parameters in python Client-side code submits an object (in the POST request body) or query string (if using GET method) via ajax request to a python cgi script. Please note that the object/query string parameters are not coming from a <form> or <isindex>. How can I retrieve these parame...
retrieving XMLHttpRequest parameters in python
Client-side code submits an object (in the POST request body) or query string (if using GET method) via ajax request to a python cgi script. Please note that the object/query string parameters are not coming from a <form> or <isindex>. How can I retrieve these parameters from within the server-side python script using...
[ "You use the cgi.FieldStorage class. Example CGI script:\n#! /usr/bin/python\n\nimport cgi\nfrom os import environ\nimport cgitb\ncgitb.enable()\n\nprint \"Content-type: text/plain\"\nprint\nprint \"REQUEST_METHOD:\", environ[\"REQUEST_METHOD\"]\nprint \"Values:\"\nf = cgi.FieldStorage()\nfor k in f.keys():\n pr...
[ 5, 0, 0 ]
[]
[]
[ "ajax", "cgi", "python" ]
stackoverflow_0000445942_ajax_cgi_python.txt
Q: urlsafe_b64encode always ends in '=' ?: I think this must be a stupid question, but why do the results of urlsafe_b64encode() always end with a '=' for me? '=' isn't url safe? from random import getrandbits from base64 import urlsafe_b64encode from hashlib import sha256 from time import sleep def genKey(): key...
urlsafe_b64encode always ends in '=' ?:
I think this must be a stupid question, but why do the results of urlsafe_b64encode() always end with a '=' for me? '=' isn't url safe? from random import getrandbits from base64 import urlsafe_b64encode from hashlib import sha256 from time import sleep def genKey(): keyLenBits = 64 a = str(getrandbits(keyLenBit...
[ "Base64 uses '=' for padding. Your string bit length isn't divisible by 24, so it's padded with '='. By the way, '=' should be URL safe as it's often used for parameters in URLs.\nSee this discussion, too.\n", "The '=' is for padding. If you want to pass the output as the value of a URL parameter, you'll want to...
[ 9, 3, 1 ]
[]
[]
[ "base64", "hash", "python" ]
stackoverflow_0000447875_base64_hash_python.txt
Q: Multithreaded Resource Access - Where Do I Put My Locks? I have threaded code where each thread needs to write to the same file. To prevent concurrency issues, I am using a Lock object. My question is whether I am using the Lock correctly. If I set the lock from within each thread, is that lock global or only sp...
Multithreaded Resource Access - Where Do I Put My Locks?
I have threaded code where each thread needs to write to the same file. To prevent concurrency issues, I am using a Lock object. My question is whether I am using the Lock correctly. If I set the lock from within each thread, is that lock global or only specific to that specific thread? Basically, should I create a L...
[ "For your use case one approach could be to write a file subclass that locks:\nclass LockedWrite(file):\n \"\"\" Wrapper class to a file object that locks writes \"\"\"\n def __init__(self, *args, **kwds):\n super(LockedWrite, self).__init__(*args, **kwds)\n self._lock = Lock()\n\n def write(...
[ 6, 3, 1, 1, 1, 1, 0 ]
[]
[]
[ "locking", "multithreading", "python" ]
stackoverflow_0000448034_locking_multithreading_python.txt
Q: Python - downloading a file over HTTP with progress bar and basic authentication I'm using urllib.urlretrieve to download a file, and implementing a download progress bar using the reporthook parameter. Since urlretrieve doesn't directly support authentication, I came up with import urllib def urlretrieve_with_b...
Python - downloading a file over HTTP with progress bar and basic authentication
I'm using urllib.urlretrieve to download a file, and implementing a download progress bar using the reporthook parameter. Since urlretrieve doesn't directly support authentication, I came up with import urllib def urlretrieve_with_basic_auth(url, filename=None, reporthook=None, data=None, ...
[ "urlgrabber has built-in support for progress bars, authentication, and more.\n" ]
[ 7 ]
[]
[]
[ "download", "http", "python" ]
stackoverflow_0000448207_download_http_python.txt
Q: Getting out of a function in Python I want to get out of a function when an exception occurs or so. I want to use other method than 'return' A: If you catch an exception and then want to rethrow it, this pattern is pretty simple: try: do_something_dangerous() except: do_something_to_apologize() raise...
Getting out of a function in Python
I want to get out of a function when an exception occurs or so. I want to use other method than 'return'
[ "If you catch an exception and then want to rethrow it, this pattern is pretty simple:\ntry:\n do_something_dangerous()\nexcept:\n do_something_to_apologize()\n raise\n\nOf course if you want to raise the exception in the first place, that's easy, too:\ndef do_something_dangerous(self):\n raise Exceptio...
[ 18, 4, 4, 3, 3 ]
[]
[]
[ "exception", "function", "python" ]
stackoverflow_0000446782_exception_function_python.txt
Q: decrypting pdf protected by aes-256bit using the right password Is there any way to decrypting a pdf protected by an aes-256 bit key? I have the correct password and I need a command-line tool (or library - perhaps in python :P ) for decrypting the file and then doing some operation over it. The best thing could b...
decrypting pdf protected by aes-256bit using the right password
Is there any way to decrypting a pdf protected by an aes-256 bit key? I have the correct password and I need a command-line tool (or library - perhaps in python :P ) for decrypting the file and then doing some operation over it. The best thing could be if the file could be saved decrypted, then I elaborate it and then ...
[ "import pyPdf \npdf = pyPdf.PdfFileReader(open(\"file.pdf\"))\npdf.decrypt(\"password\")\n\nYou can then do whatever you want with the contents. This will work with either the user or owner passwords.\n" ]
[ 4 ]
[]
[]
[ "aes", "command_line", "pdf", "python" ]
stackoverflow_0000447600_aes_command_line_pdf_python.txt
Q: Setting up Python on Windows/ Apache? I want to get a simple Python "hello world" web page script to run on Windows Vista/ Apache but hit different walls. I'm using WAMP. I've installed mod_python and the module shows, but I'm not quite sure what I'm supposed to do in e.g. http.conf (things like AddHandler mod_pyt...
Setting up Python on Windows/ Apache?
I want to get a simple Python "hello world" web page script to run on Windows Vista/ Apache but hit different walls. I'm using WAMP. I've installed mod_python and the module shows, but I'm not quite sure what I'm supposed to do in e.g. http.conf (things like AddHandler mod_python .py either bring me to a file not found...
[ "Stay away from mod_python. One common misleading idea is that mod_python is like mod_php, but for python. That is not true. Wsgi is the standard to run python web applications, defined by PEP 333. So use mod_wsgi instead.\nOr alternatively, use some web framework that has a server. Cherrypy's one is particulary go...
[ 25, 4, 0 ]
[]
[]
[ "mod_python", "python", "wamp" ]
stackoverflow_0000449055_mod_python_python_wamp.txt
Q: Is there a tool for converting VB to a scripting language, e.g. Python or Ruby? I've discovered VB2Py, but it's been silent for almost 5 years. Are there any other tools out there which could be used to convert VB6 projects to Python, Ruby, Tcl, whatever? A: I doubt there would be a good solution for that since ...
Is there a tool for converting VB to a scripting language, e.g. Python or Ruby?
I've discovered VB2Py, but it's been silent for almost 5 years. Are there any other tools out there which could be used to convert VB6 projects to Python, Ruby, Tcl, whatever?
[ "I doubt there would be a good solution for that since VB6 relies too much on the windows API and VBRun libraries though you could translate code that does something else besides GUI operations\nIs there something special you need to do with that code? You could compile your VB6 functionality and expose it as a COM...
[ 3, 3, 1 ]
[]
[]
[ "python", "vb6" ]
stackoverflow_0000449734_python_vb6.txt
Q: ImportError when using Google App Engine When I add the following line to Google's helloworld example: from reportlab.pdfgen import canvas I get the following error: <type 'exceptions.ImportError'>: No module named reportlab.pdfgen I can get at the reportlab.pdfgen library from the python console. Why can'...
ImportError when using Google App Engine
When I add the following line to Google's helloworld example: from reportlab.pdfgen import canvas I get the following error: <type 'exceptions.ImportError'>: No module named reportlab.pdfgen I can get at the reportlab.pdfgen library from the python console. Why can't I get at it from google's dev_appserver?
[ "Copying the module locally worked.\nFrom \nPython\\Lib\\site-packages\\reportlab\n\nto \nhelloworld\\reportlab \n\n", "I believe the google app engine does not include all the standard python modules. I know that anything that works with sockes is disabled, such as urllib.urlopen().\n" ]
[ 3, 0 ]
[]
[]
[ "google_app_engine", "import", "python" ]
stackoverflow_0000450883_google_app_engine_import_python.txt
Q: How to check if a file can be created inside given directory on MS XP/Vista? I have a code that creates file(s) in user-specified directory. User can point to a directory in which he can't create files, but he can rename it. I have created directory for test purposes, let's call it C:\foo. I have following permi...
How to check if a file can be created inside given directory on MS XP/Vista?
I have a code that creates file(s) in user-specified directory. User can point to a directory in which he can't create files, but he can rename it. I have created directory for test purposes, let's call it C:\foo. I have following permissions to C:\foo: Traversing directory/Execute file Removing subfolders and f...
[ "I wouldn't waste time and LOCs on checking for permissions. Ultimate test of file creation in Windows is the creation itself. Other factors may come into play (such as existing files (or worse, folders) with the same name, disk space, background processes. These conditions can even change between the time you make...
[ 4, 4, 3, 3 ]
[]
[]
[ "permissions", "python", "winapi", "windows", "windows_vista" ]
stackoverflow_0000450210_permissions_python_winapi_windows_windows_vista.txt
Q: Executing command line programs from within python I'm building a web application that will is going to manipulate (pad, mix, merge etc) sound files and I've found that sox does exactly what I want. Sox is a linux command line program and I'm feeling a little uncomfortable with having the python web app starting n...
Executing command line programs from within python
I'm building a web application that will is going to manipulate (pad, mix, merge etc) sound files and I've found that sox does exactly what I want. Sox is a linux command line program and I'm feeling a little uncomfortable with having the python web app starting new sox processes on my server on a per request basis. E...
[ "The subprocess module is the preferred way of running other programs from Python -- much more flexible and nicer to use than os.system. \nimport subprocess\n#subprocess.check_output(['ls', '-l']) # All that is technically needed...\nprint(subprocess.check_output(['ls', '-l']))\n\n", "\nThis whole setup seems a ...
[ 319, 28, 3, 2 ]
[]
[]
[ "command_line", "python" ]
stackoverflow_0000450285_command_line_python.txt
Q: Cookie Problem in Python I'm working on a simple HTML scraper for Hulu in python 2.6 and am having problems with logging on to my account. Here's my code so far: import urllib import urllib2 from cookielib import CookieJar #make a cookie and redirect handlers cookies = CookieJar() cookie_handler= urllib2.HTTPCoo...
Cookie Problem in Python
I'm working on a simple HTML scraper for Hulu in python 2.6 and am having problems with logging on to my account. Here's my code so far: import urllib import urllib2 from cookielib import CookieJar #make a cookie and redirect handlers cookies = CookieJar() cookie_handler= urllib2.HTTPCookieProcessor(cookies) redirect...
[ "What you're seeing is a ajax return. It is probably using javascript to set the cookie, and screwing up your attempts to authenticate.\n", "The error message you are getting back could be misleading. For example the server might be looking at user-agent and seeing that say it's not one of the supported browsers,...
[ 4, 2 ]
[]
[]
[ "cookies", "python", "urllib2" ]
stackoverflow_0000450787_cookies_python_urllib2.txt
Q: What does this Python message mean? ho-fe3fdd00-12:~ Sam$ easy_install BeautifulSoup Traceback (most recent call last): File "/usr/bin/easy_install", line 8, in <module> load_entry_point('setuptools==0.6c7', 'console_scripts', 'easy_install')() File "/System/Library/Frameworks/Python.framework/Versions/2.5...
What does this Python message mean?
ho-fe3fdd00-12:~ Sam$ easy_install BeautifulSoup Traceback (most recent call last): File "/usr/bin/easy_install", line 8, in <module> load_entry_point('setuptools==0.6c7', 'console_scripts', 'easy_install')() File "/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/setuptools/command/eas...
[ "BeautifulSoup is a pure Python module which you can install by grabbing the BeautifulSoup.py file (eg. from inside the standard .tar.gz distribution) and putting it somewhere on your PythonPath - eg. inside /Users/Sam/Library/Python/2.5/site-packages, if the paths mentioned in the error message are accurate.\nNo n...
[ 3, 2, 2 ]
[]
[]
[ "beautifulsoup", "easy_install", "installation", "macos", "python" ]
stackoverflow_0000452532_beautifulsoup_easy_install_installation_macos_python.txt
Q: What is the best way to handle a bad link given to BeautifulSoup? I'm working on something that pulls in urls from delicious and then uses those urls to discover associated feeds. However, some of the bookmarks in delicious are not html links and cause BS to barf. Basically, I want to throw away a link if BS fetc...
What is the best way to handle a bad link given to BeautifulSoup?
I'm working on something that pulls in urls from delicious and then uses those urls to discover associated feeds. However, some of the bookmarks in delicious are not html links and cause BS to barf. Basically, I want to throw away a link if BS fetches it and it does not look like html. Right now, this is what I'm gett...
[ "I simply wrap my BeautifulSoup processing and look for the HTMLParser.HTMLParseError exception\nimport HTMLParser,BeautifulSoup\ntry:\n soup = BeautifulSoup.BeautifulSoup(raw_html)\n for a in soup.findAll('a'):\n href = a.['href']\n ....\nexcept HTMLParser.HTMLParseError:\n print \"failed to...
[ 3 ]
[]
[]
[ "beautifulsoup", "parsing", "python" ]
stackoverflow_0000452884_beautifulsoup_parsing_python.txt
Q: PyQt and PyCairo I know it's possible to place a PyCairo surface inside a Gtk Drawing Area. But I think Qt is a lot better to work with, so I've been wondering if there's anyway to place a PyCairo surface inside some Qt component? A: Qt's own OpenGL based surfaces (using QPainter) are known to be much faster tha...
PyQt and PyCairo
I know it's possible to place a PyCairo surface inside a Gtk Drawing Area. But I think Qt is a lot better to work with, so I've been wondering if there's anyway to place a PyCairo surface inside some Qt component?
[ "Qt's own OpenGL based surfaces (using QPainter) are known to be much faster than Cairo. Might you explain why you want specifically Cairo in Qt?\nFor the basics of using QPainter see this excerpt from the book \"C++ GUI Programming with Qt4\", and while it's C++ code, the PyQt implementation will be parallel.\nAs ...
[ 5, 0 ]
[]
[]
[ "gtk", "pyqt", "python", "qt" ]
stackoverflow_0000082180_gtk_pyqt_python_qt.txt
Q: What is the practical difference between xml, json, rss and atom when interfacing with Twitter? I'm new to web services and as an introduction I'm playing around with the Twitter API using the Twisted framework in python. I've read up on the different formats they offer, but it's still not clear to me which one I ...
What is the practical difference between xml, json, rss and atom when interfacing with Twitter?
I'm new to web services and as an introduction I'm playing around with the Twitter API using the Twisted framework in python. I've read up on the different formats they offer, but it's still not clear to me which one I should use in my fairly simple project. Specifically the practical difference between using JSON or X...
[ "For me it boils down to convenience. Using XML, I have to parse the response in to a DOM (or more usually an ElementTree). Using JSON, one call to simplejson.loads(json_string) and I have a native Python data structure (lists, dictionaries, strings etc) which I can start iterating over and processing. Anything tha...
[ 8, 4, 1 ]
[]
[]
[ "json", "python", "twisted", "twitter", "xml" ]
stackoverflow_0000453158_json_python_twisted_twitter_xml.txt
Q: Is there a Python news site that's the near equivalent of RubyFlow? I really like the format and type of links from RubyFlow for Ruby related topics. Is there an equivalent for Python that's active? There is a PythonFlow, but I think it's pretty much dead. I don't really like http://planet.python.org/ because ther...
Is there a Python news site that's the near equivalent of RubyFlow?
I really like the format and type of links from RubyFlow for Ruby related topics. Is there an equivalent for Python that's active? There is a PythonFlow, but I think it's pretty much dead. I don't really like http://planet.python.org/ because there's lots of non-Python stuff on there and there's very little summarizati...
[ "http://www.reddit.com/r/Python is my favorite source for Python news.\n", "Possibly http://www.planetpython.org/ or http://planet.python.org/.\n", "http://planetpython.org/ (the unofficial planet) is generally better than http://planet.python.org/ (the official one) - I think the maintainers of the unofficial ...
[ 6, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0000453673_python.txt
Q: PYTHONSTARTUP doesn't seem to work I'm trying to use the PYTHONSTARTUP environmental variable. I set it to be "c:\python25\pythonstartup.py" in My Computer --> Advanced etc., and it doesn't seem to work. Opening IDLE doesn't run the script, although it recognized the variable: >>> import os >>> os.environ['PYTHONS...
PYTHONSTARTUP doesn't seem to work
I'm trying to use the PYTHONSTARTUP environmental variable. I set it to be "c:\python25\pythonstartup.py" in My Computer --> Advanced etc., and it doesn't seem to work. Opening IDLE doesn't run the script, although it recognized the variable: >>> import os >>> os.environ['PYTHONSTARTUP'] 'c:\\python25\\pythonstartup.py...
[ "The documentation says that PYTHONSTARTUP is only run for interactive sessions. I'm not sure how IDLE runs the Python interpreter, but it could be interfering.\nInstead, try running python directly from a command prompt, rather than from clicking on an icon.\n", "To add to Greg Hewgill's correct answer: If IDLE ...
[ 6, 2 ]
[]
[]
[ "python", "startup" ]
stackoverflow_0000453808_python_startup.txt
Q: How to create a controller method in Turbogears that can be called from within the controller, or rendered with a template If you have a controller method like so: @expose("json") def artists(self, action="view",artist_id=None): artists=session.query(model.Artist).all() return dict(artists=artists) How ca...
How to create a controller method in Turbogears that can be called from within the controller, or rendered with a template
If you have a controller method like so: @expose("json") def artists(self, action="view",artist_id=None): artists=session.query(model.Artist).all() return dict(artists=artists) How can you call that method from within your controller class, and get the python dict back - rather than the json-encoded string of ...
[ "I normally approach this by having a 'worker' method, which queries the database, transforms results, etc., and a separate exposing method, with all the required decorators. E.g.:\n# The _artists method can be used from any other method\ndef _artists(self, action, artist_id):\n artists = session.query(model.Art...
[ 1 ]
[]
[]
[ "json", "python", "turbogears" ]
stackoverflow_0000454223_json_python_turbogears.txt
Q: Your most unpythonic code snippet I am an experienced developer new to python, and still catching myself writing correct but unpythonic code. I thought it might be enlightening and entertaining to see small examples of python code people have written that in some way clashes with the generally preffered way of doi...
Your most unpythonic code snippet
I am an experienced developer new to python, and still catching myself writing correct but unpythonic code. I thought it might be enlightening and entertaining to see small examples of python code people have written that in some way clashes with the generally preffered way of doing things. I'm interested in code you ...
[ "I find manual type checking the most \"unpythonic\" (although bad in general too). There's two usual cases this is abused. The first is when the logic of the function differs based on the type of the argument. For instance:\ndef doStuff (myVar):\n if isinstance (myVar, str):\n # do stuff\n pass\n ...
[ 7, 5, 4, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000453967_python.txt
Q: Find an Image within an Image I am looking for the best way to detect an image within another image. I have a small image and would like to find the location that it appears within a larger image - which will actually be screen captures. Conceptually, it is like a 'Where's Waldo?' sort of search in the larger ima...
Find an Image within an Image
I am looking for the best way to detect an image within another image. I have a small image and would like to find the location that it appears within a larger image - which will actually be screen captures. Conceptually, it is like a 'Where's Waldo?' sort of search in the larger image. Are there any efficient/quick...
[ "Wikipedia has an article on Template Matching, with sample code.\n(While that page doesn't handle changed scales, it has links to other styles of matching, for example Scale invariant feature transform)\n", "If rotation also had to be catered for, the Generalised Hough Transform can be used.\n", "You can treat...
[ 6, 1, 0 ]
[]
[]
[ "image", "java", "python" ]
stackoverflow_0000454498_image_java_python.txt
Q: How can I make a list in Python like (0,6,12, .. 144)? I am not sure, whether I should use for -loop. Perhaps, like for i in range(145): by 6: //mistake here? print i A: for i in range(0,150,6): print i if you are stepping by a constant A: I would prefer: for i in xrange(25): # from 0 to 24 ...
How can I make a list in Python like (0,6,12, .. 144)?
I am not sure, whether I should use for -loop. Perhaps, like for i in range(145): by 6: //mistake here? print i
[ "for i in range(0,150,6):\n print i\n\nif you are stepping by a constant\n", "I would prefer:\nfor i in xrange(25): # from 0 to 24\n print 6*i\n\nYou can easily build a list containing the same numbers with a similar construct named list comprehension:\nnumbers = [6*i for i in xrange(25)]\nprint numbers...
[ 20, 6 ]
[ "reqlist = [i for i in range(0,150,6)]\n", "i = 1\n\nwhile i * 6 < 144:\n i = i + 1\n print i * 6\n\nThere are plenty of ways to do this\n" ]
[ -2, -5 ]
[ "list", "python" ]
stackoverflow_0000454566_list_python.txt
Q: What's the most efficient way to share large amounts of data between Python and C++ I'm writing a system that allows python scripts to be executed within a C++ application. The python scripts are used to modify values within arrays of data (typically 2048x2048x4 arrays of floats) I'm currently using numpy arrays ...
What's the most efficient way to share large amounts of data between Python and C++
I'm writing a system that allows python scripts to be executed within a C++ application. The python scripts are used to modify values within arrays of data (typically 2048x2048x4 arrays of floats) I'm currently using numpy arrays created using the array API and registered with Python. In the python scripts I'm access...
[ "You might want to have a look at Boost.Python. It focuses on making C++ code available in Python, but it also provides exec and eval functions that should allow you to efficiently interact with python code.\n", "I thought I would suggest numpy, but you're already using it. I'm afraid that leaves domain-specific ...
[ 1, 1, 0 ]
[]
[]
[ "c++", "optimization", "python" ]
stackoverflow_0000454931_c++_optimization_python.txt
Q: Efficient Image Thumbnail Control for Python? What is the best choice for a Python GUI application to display large number of thumbnails, e.g. 10000 or more? For performance reasons such thumbnail control must support virtual items, i.e. request application for those thumbnails only which are currently visible to ...
Efficient Image Thumbnail Control for Python?
What is the best choice for a Python GUI application to display large number of thumbnails, e.g. 10000 or more? For performance reasons such thumbnail control must support virtual items, i.e. request application for those thumbnails only which are currently visible to user.
[ "In wxPython you can use wxGrid for this as it supports virtual mode and custom cell renderers.\nThis is the minimal interface you have to implement for a wxGrid \"data provider\":\nclass GridData(wx.grid.PyGridTableBase):\n def GetColLabelValue(self, col):\n pass\n\n def GetNumberRows(self):\n ...
[ 2, 1, 1 ]
[]
[]
[ "image", "pyqt", "python", "thumbnails", "wxpython" ]
stackoverflow_0000215052_image_pyqt_python_thumbnails_wxpython.txt
Q: Python 3 development and distribution challenges Suppose I've developed a general-purpose end user utility written in Python. Previously, I had just one version available which was suitable for Python later than version 2.3 or so. It was sufficient to say, "download Python if you need to, then run this script". Th...
Python 3 development and distribution challenges
Suppose I've developed a general-purpose end user utility written in Python. Previously, I had just one version available which was suitable for Python later than version 2.3 or so. It was sufficient to say, "download Python if you need to, then run this script". There was just one version of the script in source contr...
[ "Edit: my original answer was based on the state of 2009, with Python 2.6 and 3.0 as the current versions. Now, with Python 2.7 and 3.3, there are other options. In particular, it is now quite feasible to use a single code base for Python 2 and Python 3.\nSee Porting Python 2 Code to Python 3\nOriginal answer:\nThe...
[ 9, 2, 2, 1, 0 ]
[]
[]
[ "python", "python_3.x", "version_control" ]
stackoverflow_0000455717_python_python_3.x_version_control.txt
Q: How do you query the set of Users in Google App Domain within your Google App Engine project? If you have a Google App Engine project you can authenticate based on either a) anyone with a google account or b) a particular google app domain. Since you can connect these two entities I would assume there is some way ...
How do you query the set of Users in Google App Domain within your Google App Engine project?
If you have a Google App Engine project you can authenticate based on either a) anyone with a google account or b) a particular google app domain. Since you can connect these two entities I would assume there is some way to query the list of users that can be authenticated. The use case is outputting a roster of all me...
[ "Querying all users that could possibly authenticate in the case of 'a' (all gmail users) would be millions and millions users, so I'm sure you don't expect to do that. \nI'm sure you actually mean query the ones who have logged into your application previously, in which case you just create a table to store their ...
[ 3, 1, 1, 0 ]
[]
[]
[ "google_app_engine", "google_apps", "gql", "gqlquery", "python" ]
stackoverflow_0000419197_google_app_engine_google_apps_gql_gqlquery_python.txt
Q: Does Django development provide a truly flexible 3 layer architecture? A few weeks ago I asked the question "Is a PHP, Python, PostgreSQL design suitable for a non-web business application?" Is a PHP, Python, PostgreSQL design suitable for a business application? A lot of the answers recommended skipping the PHP p...
Does Django development provide a truly flexible 3 layer architecture?
A few weeks ago I asked the question "Is a PHP, Python, PostgreSQL design suitable for a non-web business application?" Is a PHP, Python, PostgreSQL design suitable for a business application? A lot of the answers recommended skipping the PHP piece and using Django to build the application. As I've explored Django, I'v...
[ "You seem to be saying that choosing Django would prevent you from using a more heterogenous solution later. This isn't the case. Django provides a number of interesting connections between the layers, and using Django for all the layers lets you take advantage of those connections. For example, using the Django...
[ 9, 7, 4, 3, 3 ]
[ "There's change and there's change. Django utterly seperates domain model, business rules and presentation. You can change (almost) anything with near zero breakage. And by change I am talking about meaningful end-user focused business change.\nThe technology mix-n-match in this (and the previous) question isn't r...
[ -1 ]
[ "django", "model_view_controller", "orm", "python" ]
stackoverflow_0000454443_django_model_view_controller_orm_python.txt
Q: Is there any advantage in using a Python class? I have a Python class full of static methods. What are the advantages and disadvantages of packaging these in a class rather than raw functions? A: There are none. This is what modules are for: grouping related functions. Using a class full of static methods makes ...
Is there any advantage in using a Python class?
I have a Python class full of static methods. What are the advantages and disadvantages of packaging these in a class rather than raw functions?
[ "There are none. This is what modules are for: grouping related functions. Using a class full of static methods makes me cringe from Javaitis. The only time I would use a static function is if the function is an integral part of the class. (In fact, I'd probably want to use a class method anyway.)\n", "No. It wou...
[ 35, 17, 5, 2, 1, 0, 0 ]
[]
[]
[ "class", "python", "static_methods" ]
stackoverflow_0000456001_class_python_static_methods.txt
Q: How to use cvxopt with DSDP? I'm trying to use DSDP (semidefinite programming package) with cvxopt. I have both of them installed (matlab version for DSDP). I have Python 2.5.2. When trying to use dsp(..., solver='dsdp') I get an errors mentioning solvers.dsdp is not installed. How to I make them work together? ...
How to use cvxopt with DSDP?
I'm trying to use DSDP (semidefinite programming package) with cvxopt. I have both of them installed (matlab version for DSDP). I have Python 2.5.2. When trying to use dsp(..., solver='dsdp') I get an errors mentioning solvers.dsdp is not installed. How to I make them work together?
[ "I would suggest asking this question on the cvxopt group.\n" ]
[ 0 ]
[]
[]
[ "convex_optimization", "python" ]
stackoverflow_0000456224_convex_optimization_python.txt
Q: Throttling with urllib2 is it possible to easily cap the kbps when using urllib2? If it is, any code examples or resources you could direct me to would be greatly appreciated. A: There is the urlretrieve(url, filename=None, reporthook=None, data=None) function in the urllib module. If you implement the reporthoo...
Throttling with urllib2
is it possible to easily cap the kbps when using urllib2? If it is, any code examples or resources you could direct me to would be greatly appreciated.
[ "There is the urlretrieve(url, filename=None, reporthook=None, data=None) function in the urllib module.\nIf you implement the reporthook-function/object as either a token bucket, or a leaky bucket, you have your global rate-limit.\nEDIT: Upon closer examination I see that it isn't as easy to do global rate-limit w...
[ 19 ]
[]
[]
[ "bandwidth_throttling", "python", "urllib2" ]
stackoverflow_0000456649_bandwidth_throttling_python_urllib2.txt
Q: Evaluate my Python server structure I'm building a game server in Python and I just wanted to get some input on the architecture of the server that I was thinking up. So, as we all know, Python cannot scale across cores with a single process. Therefore, on a server with 4 cores, I would need to spawn 4 processes. ...
Evaluate my Python server structure
I'm building a game server in Python and I just wanted to get some input on the architecture of the server that I was thinking up. So, as we all know, Python cannot scale across cores with a single process. Therefore, on a server with 4 cores, I would need to spawn 4 processes. Here is the steps taken when a client wi...
[ "Sounds like you'll want to look at PyProcessing, now included in Python 2.6 and beyond as multiprocessing. It takes care of a lot of the machinery of dealing with multiple processes.\nAn alternative architectural model is to setup a work queue using something like beanstalkd and have each of the \"servers\" pull j...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0000456753_python.txt
Q: python web-services: returning a fault from the server using ZSI I'm interested in writing a python client for a web-service, and for testing purposes it would be very interesting also to have a simple stub server. I'm using python 2.3, and ZSI 2.0. My problem is that I do not manage to return an exception from th...
python web-services: returning a fault from the server using ZSI
I'm interested in writing a python client for a web-service, and for testing purposes it would be very interesting also to have a simple stub server. I'm using python 2.3, and ZSI 2.0. My problem is that I do not manage to return an exception from the server. If I raise an exception of the type used for the soap fault ...
[ "I've found the answer in this ZSI Cookbook, by Chris Hoobs, linked at the bottom of the ZSI home page: \n\n5.4 Exceptions\n A thorny question is how to generate the faults at the server. With the ZSI v2.0 code as\n it is provided, this is not possible.\n\nI assume this to be correct since the paper is linked fr...
[ 1, 0 ]
[]
[]
[ "fault", "python", "web_services", "zsi" ]
stackoverflow_0000446912_fault_python_web_services_zsi.txt
Q: How to handle the error that occurs on giving wrong number of parameters in a function call in Python? When i give wrong number of parameters in a function , i get errors. How do I handle it? I gave def fun_name(...): try: ... except TypeError: print 'Wrong no of arg' It is not working. ...
How to handle the error that occurs on giving wrong number of parameters in a function call in Python?
When i give wrong number of parameters in a function , i get errors. How do I handle it? I gave def fun_name(...): try: ... except TypeError: print 'Wrong no of arg' It is not working. Help please.
[ "The caller triggers this exception, not the receiver.\nIf you want the receiving function to explicitly check argument count you'll need to use varargs:\ndef fun_name(*args):\n if len(args) != 2:\n raise TypeError('Two arguments required')\n\n", "You need to handle it where you call the function.\ntry:\n fu...
[ 4, 4, 0 ]
[ "If you remove the try...catch parts it should show you what kind of exception it is throwing.\n" ]
[ -2 ]
[ "function_call", "python" ]
stackoverflow_0000456673_function_call_python.txt
Q: What is the correct procedure to store a utf-16 encoded rss stream into sqlite3 using python I have a python sgi script that attempts to extract an rss items that is posted to it and store the rss in a sqlite3 db. I am using flup as the WSGIServer. To obtain the posted content: postData = environ["wsgi.input"...
What is the correct procedure to store a utf-16 encoded rss stream into sqlite3 using python
I have a python sgi script that attempts to extract an rss items that is posted to it and store the rss in a sqlite3 db. I am using flup as the WSGIServer. To obtain the posted content: postData = environ["wsgi.input"].read(int(environ["CONTENT_LENGTH"])) To attempt to store in the db: from pysqlite2 import dbapi2...
[ "Regarding the insertion encoding - in any decent database API, you should insert unicode strings and unicode strings only.\nFor the reading and parsing bit, I'd recommend Mark Pilgrim's Feed Parser. It properly handles BOM, and the license allows commercial use. This may be a bit too heavy handed if you are not ...
[ 1, 1, 0 ]
[]
[]
[ "python", "sqlite", "wsgi" ]
stackoverflow_0000457641_python_sqlite_wsgi.txt
Q: wxPython is not throwing exceptions when it should, instead giving raw error messages I'm coding the menu for an application I'm writing in python, using wxPython libraries for the user interface, and I'm attempting to add icons to some of the menu items. Because I'm trying to be conscientious about it, I'm tryin...
wxPython is not throwing exceptions when it should, instead giving raw error messages
I'm coding the menu for an application I'm writing in python, using wxPython libraries for the user interface, and I'm attempting to add icons to some of the menu items. Because I'm trying to be conscientious about it, I'm trying to limit the damage done if one of the image files referenced doesn't exist, and the most...
[ "That is a known issue. Robin Dunn answered it a couple of times: just create your Logging method eg.:\ndummy_log=wx.LogNull()\n\nwhen the variable dummy_log runs out of scope, normal logging is enabled again.\n" ]
[ 3 ]
[]
[]
[ "exception", "python", "wxpython" ]
stackoverflow_0000458943_exception_python_wxpython.txt
Q: Filtering by relation count in SQLAlchemy I'm using the SQLAlchemy Python ORM in a Pylons project. I have a class "Project" which has a one to many relationship with another class "Entry". I want to do a query in SQLAlchemy that gives me all of the projects which have one or more entries associated with them. At t...
Filtering by relation count in SQLAlchemy
I'm using the SQLAlchemy Python ORM in a Pylons project. I have a class "Project" which has a one to many relationship with another class "Entry". I want to do a query in SQLAlchemy that gives me all of the projects which have one or more entries associated with them. At the moment I'm doing: [project for project in Se...
[ "Session.query(Project).filter(Project.entries.any()) should work.\nEdited credit of James Brady's comment, be sure to give him some love.\n" ]
[ 24 ]
[]
[]
[ "database", "pylons", "python", "sql", "sqlalchemy" ]
stackoverflow_0000459125_database_pylons_python_sql_sqlalchemy.txt
Q: Which new mp3 player to run old Python scripts Which mp3/media player could I buy which will allow me to run an existing set of python scripts. The existing scripts control xmms on linux: providing "next tracks" given data on ratings/last played/genre/how long since acquired/.... so that it all runs on a server up...
Which new mp3 player to run old Python scripts
Which mp3/media player could I buy which will allow me to run an existing set of python scripts. The existing scripts control xmms on linux: providing "next tracks" given data on ratings/last played/genre/how long since acquired/.... so that it all runs on a server upstairs somewhere, and I do not need to choose anythi...
[ "The only possibility I'm aware of is to use Rockbox, and then port the Python interpreter to it, or just port the functionality to some set of C programs, whichever suits you best. It might even come with the functionality you need already, so you'd just need to tweak some configuration files only.\n\nRockbox is a...
[ 3, 1 ]
[]
[]
[ "embedded", "mp3", "python" ]
stackoverflow_0000441864_embedded_mp3_python.txt
Q: Python/Twisted - Sending to a specific socket object? I have a "manager" process on a node, and several worker processes. The manager is the actual server who holds all of the connections to the clients. The manager accepts all incoming packets and puts them into a queue, and then the worker processes pull the pac...
Python/Twisted - Sending to a specific socket object?
I have a "manager" process on a node, and several worker processes. The manager is the actual server who holds all of the connections to the clients. The manager accepts all incoming packets and puts them into a queue, and then the worker processes pull the packets out of the queue, process them, and generate a result....
[ "It sounds like you might need to keep a reference to the transport (or protocol) along with the bytes the just came in on that protocol in your 'event' object. That way responses that came in on a connection go out on the same connection. \nIf things don't need to be processed serially perhaps you should think ab...
[ 3 ]
[]
[]
[ "multiprocess", "python", "sockets", "twisted" ]
stackoverflow_0000460068_multiprocess_python_sockets_twisted.txt