prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
search for host with mac address using python would like to search for given mac address on my network all from within python script already have map of all the active ip addresses in the network but cannot figure out how to glean the mac address any ideas
this article send hand crafted ethernet frames in python arp for example seems to be exactly what you are looking for
QA
how do you configure django for simple development and deployment tend to use sqlite when doing django development but on live server something more robust is often needed mysql postgresql for example invariably there are other changes to make to the django settings as well different logging locations intensities media paths etc how do you manage all these changes to make deployment simple automated process
personally use single settings py for the project just have it look up the hostname it is on my development machines have hostnames that start with gabriel so just have this import socket if socket gethostname startswith gabriel livehost false else livehost true then in other parts have things like if livehost debug false prepend www true media url http static grsites com else debug true prepend www false media url http localhost static and so on little bit less readable but it works fine and saves having to juggle multiple settings files
QA
how do verify that string only contains letters numbers underscores and dashes know how to do this if iterate through all of the characters in the string but am looking for more elegant method thanks
regular expression will do the trick with very little code import re if re match za my little string do something here
QA
how do verify that string only contains letters numbers underscores and dashes know how to do this if iterate through all of the characters in the string but am looking for more elegant method thanks
pat re compile def onlyallowed return not pat search
QA
how do verify that string only contains letters numbers underscores and dashes know how to do this if iterate through all of the characters in the string but am looking for more elegant method thanks
you could always use list comprehension and check the results with all it would be little less resource intensive than using regex all in string letters string digits for in mystring
QA
how do verify that string only contains letters numbers underscores and dashes know how to do this if iterate through all of the characters in the string but am looking for more elegant method thanks
there are variety of ways of achieving this goal some are clearer than others for each of my examples true means that the string passed is valid false means it contains invalid characters first of all there is the naive approach import string allowed string letters string digits def check naive mystring return all in allowed for in mystring then there is use of regular expression you can do this with re match note that has to be at the end of the otherwise it will be used as range delimiter also note the which means end of string other answers noted in this question use special character class always prefer using an explicit character class range using because it is easier to understand without having to look up quick reference guide and easier to special case import re check re re compile za def check re mystring return check re match mystring another solution noted that you can do an inverse match with regular expressions have included that here now note that inverts the character class because the is used check inv re re compile za def check inv re mystring return not check inv re search mystring you can also do something tricky with the set object have look at this example which removes from the original string all the characters that are allowed leaving us with set containing either nothing or the offending characters from the string def check set mystring return not set mystring set allowed
QA
issue with regular expressions in python ok so am working on regular expression to search out all the header information in site have compiled the regular expression regex re compile href za za za re when run this in python reg ex tester it works out wonderfully sample data body dog cat fancy tall cup of lemons href dog com dog thing body now in the redemo it works wonderfully when put it in my python code however it only prints href dog com here is my python code am not sure if am doing something wrong or if something is lost in translation appreciate your help stories response urllib urlopen http apricotclub org duh html html response read lower re compile href za za za stories re findall html for in stories if len print should also note that when take out the href za from the regular expression it works fine for non link hn lines
please do not manually parse html in python there are many better options available would recommend the wonderful beautifulsoup
QA
issue with regular expressions in python ok so am working on regular expression to search out all the header information in site have compiled the regular expression regex re compile href za za za re when run this in python reg ex tester it works out wonderfully sample data body dog cat fancy tall cup of lemons href dog com dog thing body now in the redemo it works wonderfully when put it in my python code however it only prints href dog com here is my python code am not sure if am doing something wrong or if something is lost in translation appreciate your help stories response urllib urlopen http apricotclub org duh html html response read lower re compile href za za za stories re findall html for in stories if len print should also note that when take out the href za from the regular expression it works fine for non link hn lines
parsing things with regular expressions works for regular languages html is not regular language and the stuff you find on web pages these days is absolute crap beautifulsoup deals with tag soup html with browser like heuristics so you get parsed html that resembles what browser would display the downside is it is not very fast there is lxml for parsing well formed html but you should really use beautifulsoup if you are not certain that your input will always be well formed
QA
what are the pros and cons of the various python implementations am relatively new to python and have always used the standard cpython implementation have been wondering about the other implementations though particularly jython and ironpython what makes them better what makes them worse what other implementations are there guess what am looking for is summary and list of pros and cons for each implementation
an additional benefit for jython at least for some is it lacks the gil the global interpreter lock and uses java native threads this means that you can run pure python code in parallel something not possible with the gil
QA
issue with regular expressions in python ok so am working on regular expression to search out all the header information in site have compiled the regular expression regex re compile href za za za re when run this in python reg ex tester it works out wonderfully sample data body dog cat fancy tall cup of lemons href dog com dog thing body now in the redemo it works wonderfully when put it in my python code however it only prints href dog com here is my python code am not sure if am doing something wrong or if something is lost in translation appreciate your help stories response urllib urlopen http apricotclub org duh html html response read lower re compile href za za za stories re findall html for in stories if len print should also note that when take out the href za from the regular expression it works fine for non link hn lines
because of the braces around the anchor tag that part is interpreted as capture group this causes only the capture group to be returned and not the whole regex match put the entire regex in braces and you will see the right matches showing up as the first element in the returned tuples but indeed you should use real parser
QA
issue with regular expressions in python ok so am working on regular expression to search out all the header information in site have compiled the regular expression regex re compile href za za za re when run this in python reg ex tester it works out wonderfully sample data body dog cat fancy tall cup of lemons href dog com dog thing body now in the redemo it works wonderfully when put it in my python code however it only prints href dog com here is my python code am not sure if am doing something wrong or if something is lost in translation appreciate your help stories response urllib urlopen http apricotclub org duh html html response read lower re compile href za za za stories re findall html for in stories if len print should also note that when take out the href za from the regular expression it works fine for non link hn lines
this question has been asked in several forms over the last few days so am going to say this very clearly how do parse html with regular expressions please do not use beautifulsoup html lib or lxml html please
QA
issue with regular expressions in python ok so am working on regular expression to search out all the header information in site have compiled the regular expression regex re compile href za za za re when run this in python reg ex tester it works out wonderfully sample data body dog cat fancy tall cup of lemons href dog com dog thing body now in the redemo it works wonderfully when put it in my python code however it only prints href dog com here is my python code am not sure if am doing something wrong or if something is lost in translation appreciate your help stories response urllib urlopen http apricotclub org duh html html response read lower re compile href za za za stories re findall html for in stories if len print should also note that when take out the href za from the regular expression it works fine for non link hn lines
as has been mentioned you should use parser instead of regex this is how you could do it with regex though import re html body dog cat fancy tall cup of lemons href dog com dog thing body re compile header store header tag for later use zero or more whitespace shref href optional link tag store href portion title title optional closing link tag header must match opening header tag re ignorecase re verbose stories finditer html for match in stories print title href match groupdict here are couple of good regular expression resources python regular expression howto regular expressions info
QA
issue with regular expressions in python ok so am working on regular expression to search out all the header information in site have compiled the regular expression regex re compile href za za za re when run this in python reg ex tester it works out wonderfully sample data body dog cat fancy tall cup of lemons href dog com dog thing body now in the redemo it works wonderfully when put it in my python code however it only prints href dog com here is my python code am not sure if am doing something wrong or if something is lost in translation appreciate your help stories response urllib urlopen http apricotclub org duh html html response read lower re compile href za za za stories re findall html for in stories if len print should also note that when take out the href za from the regular expression it works fine for non link hn lines
building on the answers so far it is best to use parsing engine it can cover lot of cases and in an elegant way have tried beautifulsoup and like it very much also easy to use with great tutorial if sometimes it feels like shooting flies with cannon you can use regular expression for quick parsing if that is what you need here is the modified code that will catch all the headers even those over multiple lines re compile re ignorecase re dotall stories re findall html for in stories print
QA
need to write code in python for comparing text of two documents using fingerprint techniques need to write code in python language for comparing the text of document using fingerprint techniques do not know to take fingerprint of document or to generate fingerprint of document am asking if anyone knows the method or has source code for generating fingerprints of documents which is stored in bits form
if you want message digests cryptographic hashes use the hashlib library here is an example ipython session in import hashlib in md hashlib sha open tmp calendar xls rb read in md hexdigest out eae de de cfd be fb
QA
how do you load an embedded icon from an exe file with pywin have an exe file generated with py exe in the setup py specify an icon to be embedded in the exe windows script my script py icon resources my icon ico tried loading the icon using hinst win api getmodulehandle none hicon win gui loadimage hinst win con image icon win con lr defaultsize but this produces an very unspecific error pywintypes error loadimage no error message is available if try specifying as string hicon win gui loadimage hinst win con image icon win con lr defaultsize then get the error pywintypes error loadimage the specified resource type cannot be found in the image file so what is the correct method syntax to load the icon also please notice that do not use any gui toolkit just the windows api via pywin
you should set the icon id to something other than icon resources my icon ico windows resource ids must be between and
QA
need to write code in python for comparing text of two documents using fingerprint techniques need to write code in python language for comparing the text of document using fingerprint techniques do not know to take fingerprint of document or to generate fingerprint of document am asking if anyone knows the method or has source code for generating fingerprints of documents which is stored in bits form
you might try the following papers to get started with the concept of fingerprinting winnowing local algorithms for document fingerprinting scalable document fingerprinting
QA
will everything in the standard library treat strings as unicode in python am little confused about how the standard library will behave now that python from is unicode based will modules such as cgi and urllib use unicode strings or will they use the new bytes type and just provide encoded data
logically lot of things like mime encoded mail messages urls xml documents and so on should be returned as bytes not strings this could cause some consternation as the libraries start to be nailed down for python and people discover that they have to be more aware of the bytes string conversions than they were for str unicode
QA
will everything in the standard library treat strings as unicode in python am little confused about how the standard library will behave now that python from is unicode based will modules such as cgi and urllib use unicode strings or will they use the new bytes type and just provide encoded data
one of the great things about this question and python in general is that you can just mess around in the interpreter python rc is currently available for download import urllib request fh urllib request urlopen http www python org print type fh read class bytes
QA
will everything in the standard library treat strings as unicode in python am little confused about how the standard library will behave now that python from is unicode based will modules such as cgi and urllib use unicode strings or will they use the new bytes type and just provide encoded data
there will be two step dance here see python and you step is to get running under step is to rethink your api to perhaps do something more sensible the most likely course is that the libraries will switch to unicode strings to remain as compatible as possible with how they used to work then perhaps some will switch to bytes to more properly implement the rfc standards for the various protocols
QA
how do verify that string only contains letters numbers underscores and dashes know how to do this if iterate through all of the characters in the string but am looking for more elegant method thanks
as an alternative to using regex you could do it in sets from sets import set allowed chars set abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz if set my little sting issubset allowed chars your action print true
QA
how do verify that string only contains letters numbers underscores and dashes know how to do this if iterate through all of the characters in the string but am looking for more elegant method thanks
if it were not for the dashes and underscores the easiest solution would be my little string isalnum section of the python library reference
QA
how do you configure django for simple development and deployment tend to use sqlite when doing django development but on live server something more robust is often needed mysql postgresql for example invariably there are other changes to make to the django settings as well different logging locations intensities media paths etc how do you manage all these changes to make deployment simple automated process
at the end of settings py have the following try from settings local import except importerror pass this way if want to override default settings need to just put settings local py right next to settings py
QA
how do you load an embedded icon from an exe file with pywin have an exe file generated with py exe in the setup py specify an icon to be embedded in the exe windows script my script py icon resources my icon ico tried loading the icon using hinst win api getmodulehandle none hicon win gui loadimage hinst win con image icon win con lr defaultsize but this produces an very unspecific error pywintypes error loadimage no error message is available if try specifying as string hicon win gui loadimage hinst win con image icon win con lr defaultsize then get the error pywintypes error loadimage the specified resource type cannot be found in the image file so what is the correct method syntax to load the icon also please notice that do not use any gui toolkit just the windows api via pywin
if you are using wxpython you can use the following simple code wx icon sys argv wx bitmap type ico usually have code that checks whether it is running from an exe or not and acts accordingly def get app icon if hasattr sys frozen and getattr sys frozen windows exe return wx icon sys argv wx bitmap type ico else return wx icon gfx myapp ico wx bitmap type ico
QA
ni cvi with python would like to integrate python idle esque command prompt interface into an existing ni cvi labwindows application have tried to follow the python org discussions but seem to get lost in the details is there resource out there for dummies like me
here is python sample code calling cvi there are daqmx python bindings too
QA
is there pretty printer for python data working with python interactively it is sometimes necessary to display result which is some arbitrarily complex data structure like lists with embedded lists etc the default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it is there something that will take any python object and display it in more rational manner instead of know that is not very good example but think you get the idea
from pprint import pprint pprint note that for short list like my example pprint will in fact print it all on one line however for more complex structures it does pretty good job of pretty printing data
QA
google app engine how can programmatically access the properties of my model class have model class class person db model first name db stringproperty required true last name db stringproperty required true have an instance of this class in and string contains the value first name would like to do something like print and new value both of which result in typeerror does anybody know how can achieve what would like
getattr setattr new value
QA
google app engine how can programmatically access the properties of my model class have model class class person db model first name db stringproperty required true last name db stringproperty required true have an instance of this class in and string contains the value first name would like to do something like print and new value both of which result in typeerror does anybody know how can achieve what would like
try model properties get value for datastore see the documentation
QA
google app engine how can programmatically access the properties of my model class have model class class person db model first name db stringproperty required true last name db stringproperty required true have an instance of this class in and string contains the value first name would like to do something like print and new value both of which result in typeerror does anybody know how can achieve what would like
if the model class is sufficiently intelligent it should recognize the standard python ways of doing this try getattr setattr new value there is also hasattr available
QA
is there pretty printer for python data working with python interactively it is sometimes necessary to display result which is some arbitrarily complex data structure like lists with embedded lists etc the default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it is there something that will take any python object and display it in more rational manner instead of know that is not very good example but think you get the idea
another good option is to use ipython which is an interactive environment with lot of extra features including automatic pretty printing tab completion of methods easy she will access and lot more it is also very easy to install ipython tutorial
QA
how do verify that string only contains letters numbers underscores and dashes know how to do this if iterate through all of the characters in the string but am looking for more elegant method thanks
edit there is another solution not mentioned yet and it seems to outperform the others given so far in most cases use string translate to replace all valid characters in the string and see if we have any invalid ones left over this is pretty fast as it uses the underlying function to do the work with very little python bytecode involved obviously performance is not everything going for the most readable solutions is probably the best approach when not in performance critical codepath but just to see how the solutions stack up here is performance comparison of all the methods proposed so far check trans is the one using the string translate method test code import string re timeit pat re compile pat inv re compile allowed chars string ascii letters string digits allowed set set allowed chars trans table string maketrans def check set diff return not set allowed set def check set all return all in allowed set for in def check set subset return set issubset allowed set def check re match return pat match def check re inverse search for non matching character return not pat inv search def check trans return not translate trans table allowed chars test long almost valid very long string that is mostly valid except for last char test long valid very long string that is completely valid test short valid short valid string test short invalid test long invalid test empty def main funcs sorted for in globals if startswith check tests sorted for in globals if startswith test for test in tests print test length test len globals test for func in funcs print func timeit timer func test from main import pat allowed set join funcs tests timeit print if name main main the results on my system are test test empty length check re inverse check re match check set all check set diff check set subset check trans test test long almost valid length check re inverse check re match check set all check set diff check set subset check trans test test long invalid length check re inverse check re match check set all check set diff check set subset check trans test test long valid length check re inverse check re match check set all check set diff check set subset check trans test test short invalid length check re inverse check re match check set all check set diff check set subset check trans test test short valid length check re inverse check re match check set all check set diff check set subset check trans the translate approach seems best in most cases dramatically so with long valid strings but is beaten out by regexes in test long invalid presumably because the regex can bail out immediately but translate always has to scan the whole string the set approaches are usually worst beating regexes only for the empty string case using all in allowed set for in performs well if it bails out early but can be bad if it has to iterate through every character issubset and set difference are comparable and are consistently proportional to the length of the string regardless of the data there is similar difference between the regex methods matching all valid characters and searching for invalid characters matching performs little better when checking for long but fully valid string but worse for invalid characters near the end of the string
QA
python beyond the basics have gotten to grips with the basics of python and have got small holiday which want to use some of to learn little more python the problem is that have no idea what to learn or where to start am primarily web development but in this case do not know how much difference it will make
would suggest writing non trivial webapp using either django or pylons something that does some number crunching no better way to learn new language than commiting yourself to problem and learning as you go
QA
is there pretty printer for python data working with python interactively it is sometimes necessary to display result which is some arbitrarily complex data structure like lists with embedded lists etc the default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it is there something that will take any python object and display it in more rational manner instead of know that is not very good example but think you get the idea
somtimes yaml can be good for this import yaml print yaml dump produces
QA
python beyond the basics have gotten to grips with the basics of python and have got small holiday which want to use some of to learn little more python the problem is that have no idea what to learn or where to start am primarily web development but in this case do not know how much difference it will make
something great to play around with though not project is the python challenge have found it quite useful in improving my python skills and it gives your brain good workout at the same time
QA
python beyond the basics have gotten to grips with the basics of python and have got small holiday which want to use some of to learn little more python the problem is that have no idea what to learn or where to start am primarily web development but in this case do not know how much difference it will make
honestly loved the book programming python it has large assortment of small projects most of which can be completed in an evening at leisurely pace they get you acquainted with most of the standard library and will likely hold your interest most importantly these small projects are actually useful in day to day sense the book pretty much only assumes you know and understand the bare essentials of python as language rather than knowledge of it is huge api library think you will find it will be well worth working through
QA
python beyond the basics have gotten to grips with the basics of python and have got small holiday which want to use some of to learn little more python the problem is that have no idea what to learn or where to start am primarily web development but in this case do not know how much difference it will make
depending on exactly what you mean by gotten to grips with the basics would suggest reading through dive into python and typing executing all the chapter code then get something like programming collective intelligence and working through it you will learn python quite well not to mention some quite excellent algorithms that will come in handy to web developer
QA
python beyond the basics have gotten to grips with the basics of python and have got small holiday which want to use some of to learn little more python the problem is that have no idea what to learn or where to start am primarily web development but in this case do not know how much difference it will make
well there are great ressources for advanced python programming dive into python read it for free online python cookbooks here and there reilly python cookbook see amazon funny riddle game python challenge here is list of subjects you must master if you want to write python on your resume list comprehensions iterators and generators decorators they are what make python such cool language with the standard library of course that keep discovering everyday
QA
python beyond the basics have gotten to grips with the basics of python and have got small holiday which want to use some of to learn little more python the problem is that have no idea what to learn or where to start am primarily web development but in this case do not know how much difference it will make
write web app likely in django the docs will teach you lot of good python style use some of the popular libraries like pygments or the universal feed parser both of these make extremely useful functions which are hard to get right available in well documented api in general would stay away from libs that are not well documented you will bang your head on the wall trying to reverse engineer them and libraries that are wrappers around libraries if you do not have any experience worked on wxpython code when was still learning python which was my first language and at the time it was little more than wrapper around wxwidgets that code was easily the ugliest have ever written did not get that much out of dive into python except for the dynamic import chapter that is not really well documented elsewhere
QA
calling an external command in python how can call an external command as if would typed it at the unix she will or windows command prompt from within python script
here is summary of the ways to call external programs and the advantages and disadvantages of each os system some command with args passes the command and arguments to your system she will this is nice because you can actually run multiple commands at once in this manner and set up pipes and input output redirection for example os system some command input file another command output file however while this is convenient you have to manually handle the escaping of she will characters such as spaces etc on the other hand this also let us you run commands which are simply she will commands and not actually external programs see the documentation stream os popen some command with args will do the same thing as os system except that it gives you file like object that you can use to access standard input output for that process there are other variants of popen that all handle the slightly differently if you pass everything as string then your command is passed to the she will if you pass them as list then you do not need to worry about escaping anything see the documentation the popen class of the subprocess module this is intended as replacement for os popen but has the downside of being slightly more complicated by virtue of being so comprehensive for example you would say print subprocess popen echo hello world she will true stdout subprocess pipe stdout read instead of print os popen echo hello world read but it is nice to have all of the options there in one unified class instead of different popen functions see the documentation the call function from the subprocess module this is basically just like the popen class and takes all of the same arguments but it simply waits until the command completes and gives you the return code for example return code subprocess call echo hello world she will true see the documentation if you are on python or later you can use the new subprocess run function which is lot like the above but even more flexible and returns completedprocess object when the command finishes executing the os module also has all of the fork exec spawn functions that you would have in program but do not recommend using them directly the subprocess module should probably be what you use finally please be aware that for all methods where you pass the final command to be executed by the she will as string and you are responsible for escaping it there are serious security implications if any part of the string that you pass can not be fully trusted for example if user is entering some any part of the string if you are unsure only use these methods with constants to give you hint of the implications consider this code print subprocess popen echo user input stdout pipe stdout read and imagine that the user enters my mama did not love me rm rf
QA
stripping non printable characters from string in python use to run print on perl to get rid of non printable characters in python there is no posix regex classes and cannot write print having it mean what want know of no way in python to detect if character is printable or not what would you do edit it has to support unicode characters as well the string printable way will happily strip them out of the output curses ascii isprint will return false for any unicode character
the best have come up with now is thanks to the python izers above def filter non printable str return join for in str if ord or ord this is the only way have found out that works with unicode characters strings any better options
QA
python beyond the basics have gotten to grips with the basics of python and have got small holiday which want to use some of to learn little more python the problem is that have no idea what to learn or where to start am primarily web development but in this case do not know how much difference it will make
people tend to say something along the lines of the best way to learn is by doing but have always found that unless you are specifically learning language to contribute to some project it is difficult to actually find little problems to tackle to keep yourself going good solution to this is project euler which has list of various programming mathematics challenges ranging from simple to quite brain taxing as an example the first challenge is if we list all the natural numbers below that are multiples of or we get and the sum of these multiples is and by problem it is already getting little tougher which prime below one million can be written as the sum of the most consecutive primes there are in total but think some new ones get added here and there while already knew python fairly well before starting project euler found that learned some cool tricks purely through using the language so much good luck
QA
stripping non printable characters from string in python use to run print on perl to get rid of non printable characters in python there is no posix regex classes and cannot write print having it mean what want know of no way in python to detect if character is printable or not what would you do edit it has to support unicode characters as well the string printable way will happily strip them out of the output curses ascii isprint will return false for any unicode character
as far as know the most pythonic efficient method would be import string filtered string filter lambda in string printable mystr
QA
python beyond the basics have gotten to grips with the basics of python and have got small holiday which want to use some of to learn little more python the problem is that have no idea what to learn or where to start am primarily web development but in this case do not know how much difference it will make
will plug building skills in python plus if you want something more challenging building skills in oo design is rather large and complex series of exercises
QA
stripping non printable characters from string in python use to run print on perl to get rid of non printable characters in python there is no posix regex classes and cannot write print having it mean what want know of no way in python to detect if character is printable or not what would you do edit it has to support unicode characters as well the string printable way will happily strip them out of the output curses ascii isprint will return false for any unicode character
this function uses list comprehensions and str join so it runs in linear time instead of from curses ascii import isprint def printable input return join char for char in input if isprint char
QA
python module functions used in unexpected ways based on split string by spaces in python which uses shlex split to split string with quotes smartly would be interested in hearing about other common tasks solved by non obvious standard library functions if this turns into module of the week that is fine too
found struct unpack to be godsend for unpacking binary data formats after learned of it
QA
how can highlight text in scintilla am writing an editor using scintilla am already using lexer to do automatic syntax highlighting but now would like to mark search results if want to mark only one hit can set the selection there however would like to mark with yellow background all the hits writing this in perl but if you have suggestions in other languages that would be cool as well
the sample editor scite uses the bookmark feature to bookmark all the lines that match the search result
QA
python beyond the basics have gotten to grips with the basics of python and have got small holiday which want to use some of to learn little more python the problem is that have no idea what to learn or where to start am primarily web development but in this case do not know how much difference it will make
the python cookbook is absolutely essential if you want to master idiomatic python besides that is the book that made me fall in love with the language
QA
how do you load an embedded icon from an exe file with pywin have an exe file generated with py exe in the setup py specify an icon to be embedded in the exe windows script my script py icon resources my icon ico tried loading the icon using hinst win api getmodulehandle none hicon win gui loadimage hinst win con image icon win con lr defaultsize but this produces an very unspecific error pywintypes error loadimage no error message is available if try specifying as string hicon win gui loadimage hinst win con image icon win con lr defaultsize then get the error pywintypes error loadimage the specified resource type cannot be found in the image file so what is the correct method syntax to load the icon also please notice that do not use any gui toolkit just the windows api via pywin
well well installed py exe and think it is bug in py exe util they should init rt icon id to instead of the way it is now it is impossible to load the first format of the first icon using loadicon loadimage will notify the developers about this if it is not already known issue workaround in the meantime would be to include the same icon twice in your setup py icon resources my icon ico my icon ico you can load the second one while windows will use the first one as the she will icon remember to use non zero ids though
QA
how can highlight text in scintilla am writing an editor using scintilla am already using lexer to do automatic syntax highlighting but now would like to mark search results if want to mark only one hit can set the selection there however would like to mark with yellow background all the hits writing this in perl but if you have suggestions in other languages that would be cool as well
have you read the markers reference in scintilla doc this reference can be bit obscure so advise to take look at the source code of scite as well this text editor was originally testbed for scintilla it grown to full fledged editor but it is still good implementation reference for all things scintilla in our particular case there is mark all button in the find dialog you can find its implementation in scitebase markall method this method only loops on search results until it loops on the first search result if any and puts bookmark on the found lines and optionally set an indicator on the found items the found line is gotten using sci linefromposition posfound the bookmark is just call to sci markeradd lineno markerbookmark note that the mark can be symbol in margin or if not associated to margin it will highlight the whole line hth
QA
django fcgid on fedora core what am missing fedora core seems to have fcgid instead of fastcgi as pre built yum managed module would rather not have to maintain module outside of yum so no manual builds for me or my sysadmins am trying to launch django through the runfastcgi interface per the fastcgi deployment docs what am seeing is the resulting page written to error log it does not come back through apache to my browser further there are bunch of messages apparently from flup and wsgiserver that indicate that the wsgi environment is not defined properly is fastcgi available for fc and just overlooked it does fcgid and flup actually create the necessary wsgi environment for django if so can you share the fcgi interface script you are using mine is copied from mysite fcgi in the django docs the fcgid documentations page drops hints that php and ruby are supported php directly and ruby through dispatch fcgi and python is not supported update the error messages are wsgiserver missing fastcgi param request method required by wsgi wsgiserver missing fastcgi param server name required by wsgi wsgiserver missing fastcgi param server port required by wsgi wsgiserver missing fastcgi param server protocol required by wsgi should abandon ship and switch to mod python and give up on this approach
why do not you try modwsgi it sounds as the preffered way these days for wsgi applications such as django if you do not wan to compile stuff for fedora core that might be trickier regarding this seems to solve the fcgid configuration problem note that you do not want to run the django application manually like this python manage py runfcgi the fcgi is run by apache automatically if the setup is correct and restarted by touch your fcgi
QA
time sleep sleeps thread or process in python for the nix does time sleep block the thread or the process
just the thread
QA
time sleep sleeps thread or process in python for the nix does time sleep block the thread or the process
it will just sleep the thread except in the case where your application has only single thread in which case it will sleep the thread and effectively the process as well the python documentation on sleep does not specify this however so can certainly understand the confusion http docs python org library time html
QA
stripping non printable characters from string in python use to run print on perl to get rid of non printable characters in python there is no posix regex classes and cannot write print having it mean what want know of no way in python to detect if character is printable or not what would you do edit it has to support unicode characters as well the string printable way will happily strip them out of the output curses ascii isprint will return false for any unicode character
iterating over strings is unfortunately rather slow in python regular expressions are over an order of magnitude faster for this kind of thing you just have to build the character class yourself the unicodedata module is quite helpful for this especially the unicodedata category function see unicode character database for descriptions of the categories import unicodedata re all chars unichr for in xrange control chars join for in all chars if unicodedata category cc or equivalently and much more efficiently control chars join map unichr range range control char re re compile re escape control chars def remove control chars return control char re sub
QA
time sleep sleeps thread or process in python for the nix does time sleep block the thread or the process
the thread will block but the process is still alive in single threaded application this means everything is blocked while you sleep in multithreaded application only the thread you explicitly sleep will block and the other threads still run within the process
QA
time sleep sleeps thread or process in python for the nix does time sleep block the thread or the process
it blocks the thread if you look in modules timemodule in the python source you will see that in the call to floatsleep the substantive part of the sleep operation is wrapped in py begin allow threads and py end allow threads block allowing other threads to continue to execute while the current one sleeps you can also test this with simple python program import time from threading import thread class worker thread def run self for in xrange print time sleep class waiter thread def run self for in xrange print time sleep def run worker start waiter start which will print thread test run
QA
is there pretty printer for python data working with python interactively it is sometimes necessary to display result which is some arbitrarily complex data structure like lists with embedded lists etc the default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it is there something that will take any python object and display it in more rational manner instead of know that is not very good example but think you get the idea
in addition to pprint pprint pprint pformat is really useful for making readable repr my complex repr usually look like so def repr self from pprint import pformat return classname pformat attrs self attrs that self that care about self care about
QA
python sockets suddenly timing out came back today to an old script had for logging into gmail via ssl the script worked fine last time ran it several months ago but now it dies immediately with urlopen error the read operation timed out if set the timeout no matter how long it dies even more immediately with urlopen error the connect operation timed out the latter is reproducible with import socket socket setdefaulttimeout sock socket socket sock connect www google com ssl socket ssl sock returning socket sslerror the connect operation timed out but cannot seem to reproduce the former and after much stepping thru the code have no clue what is causing any of this
www google com is not accessible by https it redirects to insecure http to get to mail you should be going go https mail google com
QA
python sockets suddenly timing out came back today to an old script had for logging into gmail via ssl the script worked fine last time ran it several months ago but now it dies immediately with urlopen error the read operation timed out if set the timeout no matter how long it dies even more immediately with urlopen error the connect operation timed out the latter is reproducible with import socket socket setdefaulttimeout sock socket socket sock connect www google com ssl socket ssl sock returning socket sslerror the connect operation timed out but cannot seem to reproduce the former and after much stepping thru the code have no clue what is causing any of this
import socket socket setdefaulttimeout sock socket socket sock connect www google com ssl socket ssl sock ssl server us st california mountain view google inc cn www google com it works just fine cannot reproduce your error
QA
python module functions used in unexpected ways based on split string by spaces in python which uses shlex split to split string with quotes smartly would be interested in hearing about other common tasks solved by non obvious standard library functions if this turns into module of the week that is fine too
have found sched module to be helpful in cron like activities it simplifies things lot unfortunately found it too late
QA
stripping non printable characters from string in python use to run print on perl to get rid of non printable characters in python there is no posix regex classes and cannot write print having it mean what want know of no way in python to detect if character is printable or not what would you do edit it has to support unicode characters as well the string printable way will happily strip them out of the output curses ascii isprint will return false for any unicode character
you could try setting up filter using the unicodedata category function printable set lu will def filter non printable str return join for in str if unicodedata category in printable see the unicode database character properties for the available categories
QA
what is the easiest non memory intensive way to output xml from python basically something similar to system xml xmlwriter streaming xml writer that does not incur much of memory overhead so that rules out xml dom and xml dom minidom suggestions
think have your poison http sourceforge net projects xmlite cheers
QA
sanitising user input using python what is the best way to sanitise user input for python based web application is there single function to remove html characters and any other necessary characters combinations to prevent an xss or sql injection attack
the best way to prevent xss is not to try and filter everything but rather to simply do html entity encoding for example automatically turn into lt this is the ideal solution assuming you do not need to accept any html input outside of forum comment areas where it is used as markup it should be pretty rare to need to accept html there are so many permutations via alternate encodings that anything but an ultra restrictive whitelist for example is going to let something through sql injection contrary to other opinion is still possible if you are just building out query string for example if you are just concatenating an incoming parameter onto query string you will have sql injection the best way to protect against this is also not filtering but rather to religiously use parameterized queries and never concatenate user input this is not to say that filtering is not still best practice but in terms of sql injection and xss you will be far more protected if you religiously use parameterize queries and html entity encoding
QA
python module functions used in unexpected ways based on split string by spaces in python which uses shlex split to split string with quotes smartly would be interested in hearing about other common tasks solved by non obvious standard library functions if this turns into module of the week that is fine too
oft overlooked modules uses and tricks collections defaultdict for when you want missing keys in dict to have default value functools wraps for writing decorators that play nicely with introspection posixpath the os path module for posix systems you can use it for manipulating posix paths including uri elements even on windows and other non posix systems ntpath the os path module for windows usable for manipulation of windows paths on non windows systems also macpath for macos and earlier os emxpath for os emx but am not sure if anyone still cares pprint more structured printing of the repr of containers makes debugging much easier imp all the tools you need to write your own plugin system or make python import modules from arbitrary archives rlcompleter getting tab completion in the normal interactive interpreter just do import readline rlcompleter readline parse and bind tab complete the pythonstartup environment variable can be set to the path to file that will be executed in the main namespace when entering the interactive interpreter useful for putting things in like the rlcompleter recipe above
QA
what is the easiest non memory intensive way to output xml from python basically something similar to system xml xmlwriter streaming xml writer that does not incur much of memory overhead so that rules out xml dom and xml dom minidom suggestions
some years ago used markupwriter from suite general purpose utility class for generating xml may eventually be expanded to produce more output types sample usage from ft xml import markupwriter writer markupwriter indent you yes writer startdocument writer startelement you xsa writer startelement you vendor element with simple text pcdata content writer simpleelement you name content you centigrade systems note writer text content still works writer simpleelement you email content you info centigrade bogus writer endelement you vendor element with an attribute writer startelement you product attributes you id you note writer attribute name value namespace none still works writer simpleelement you name content you server xml fragment writer xmlfragment version version last release last release empty element writer simpleelement you changes writer endelement you product writer endelement you xsa writer enddocument note on the difference between suite writers and printers writer module that exposes broad public api for building output bit by bit printer module that simply takes dom and creates output from it as whole within one api invokation recently hear lot about how lxml is great but do not have first hand experience and had some fun working with gnosis
QA
what is the easiest non memory intensive way to output xml from python basically something similar to system xml xmlwriter streaming xml writer that does not incur much of memory overhead so that rules out xml dom and xml dom minidom suggestions
think you will find xmlgenerator from xml sax saxutils is the closest thing to what you want import time from xml sax saxutils import xmlgenerator from xml sax xmlreader import attributesnsimpl log levels debug warning error class xml logger def init self output encoding set up logger object which takes sax events and outputs an xml log file logger xmlgenerator output encoding logger startdocument attrs attributesnsimpl logger startelementns none you log you log attrs self logger logger self output output self encoding encoding return def write entry self level message write log entry to the logger level the level of the entry message the text of the entry must be unicode object note in real application would use iso for the date asctime used here for simplicity now time asctime time localtime attr vals none you date now none you level log levels level attr qnames none you date you date none you level you level attrs attributesnsimpl attr vals attr qnames self logger startelementns none you entry you entry attrs self logger characters message self logger endelementns none you entry you entry return def close self clean up the logger object self logger endelementns none you log you log self logger enddocument return if name main test it out import sys xl xml logger sys stdout utf xl write entry you vanilla log entry xl close you will probably want to look at the rest of the article got that from at http www xml com pub py xml html
QA
how do persist to disk temporary file using python am attempting to use the tempfile module for manipulating and creating text files once the file is ready want to save it to disk thought it would be as simple as using shutil copy however get permission denied ioerror import tempfile shutil tempfile temporaryfile mode write foo shutil copy name bar txt traceback most recent call last file pyshell line in module shutil copy name bar txt file python lib shutil py line in copy copyfile src dst file python lib shutil py line in copyfile fsrc open src rb ioerror errno permission denied docume me locals temp tmpvqq go is this not intended when using the tempfile library is there better way to do this maybe am overlooking something very trivial
you could always use shutil copyfileobj in your example new file open bar txt rw shutil copyfileobj new file
QA
how do persist to disk temporary file using python am attempting to use the tempfile module for manipulating and creating text files once the file is ready want to save it to disk thought it would be as simple as using shutil copy however get permission denied ioerror import tempfile shutil tempfile temporaryfile mode write foo shutil copy name bar txt traceback most recent call last file pyshell line in module shutil copy name bar txt file python lib shutil py line in copy copyfile src dst file python lib shutil py line in copyfile fsrc open src rb ioerror errno permission denied docume me locals temp tmpvqq go is this not intended when using the tempfile library is there better way to do this maybe am overlooking something very trivial
the file you create with temporaryfile or namedtemporaryfile is automatically removed when it is closed which is why you get an error if you do not want this you can use mkstemp instead see the docs for tempfile import tempfile shutil os fd path tempfile mkstemp os write fd foo os close fd shutil copy path bar txt os remove path
QA
distributed python what is the best python framework to create distributed applications for example to build app
you could download the source of bittorrent for starters and see how they did it http download bittorrent com dl
QA
distributed python what is the best python framework to create distributed applications for example to build app
if it is something where you are going to need tons of threads and need better concurrent performance check out stackless python otherwise you could just use the soap or xml rpc protocols in response to ben post if you do not want to look over the bittorrent source you could just look at the article on the bittorrent protocol
QA
how do read selected files from remote zip archive over http using python need to read selected files matching on the file name from remote zip archive using python do not want to save the full zip to temporary file it is not that large so can handle everything in memory have already written the code and it works and am answering this myself so can search for it later but since evidence suggests that am one of the dumber participants on stackoverflow am sure there is room for improvement
here is how did it grabbing all files ending in ranks import urllib cstringio zipfile try remotezip urllib urlopen url zipinmemory cstringio stringio remotezip read zip zipfile zipfile zipinmemory for fn in zip namelist if fn endswith ranks ranks data zip read fn for line in ranks data split do something with each line except urllib httperror handle exception
QA
distributed python what is the best python framework to create distributed applications for example to build app
you could checkout pyprocessing which will be included in the standard library as of it allows you to run tasks on multiple processes using an api similar to threading
QA
how do read selected files from remote zip archive over http using python need to read selected files matching on the file name from remote zip archive using python do not want to save the full zip to temporary file it is not that large so can handle everything in memory have already written the code and it works and am answering this myself so can search for it later but since evidence suggests that am one of the dumber participants on stackoverflow am sure there is room for improvement
bear in mind that merely decompressing zip file may result in security vulnerability
QA
python module functions used in unexpected ways based on split string by spaces in python which uses shlex split to split string with quotes smartly would be interested in hearing about other common tasks solved by non obvious standard library functions if this turns into module of the week that is fine too
getpass is useful for determining the login name of the current user grp allows you to lookup unix group ids by name and vice versa dircache might be useful in situations where you are repeatedly polling the contents of directory glob can find filenames matching wildcards like unix she will does shutil is useful when you need to copy delete or rename file csv can simplify parsing of delimited text files optparse provides reliable way to parse command line options bz comes in handy when you need to manipulate bzip compressed file urlparse will save you the hassle of breaking up url into component parts
QA
distributed python what is the best python framework to create distributed applications for example to build app
think you mean networked apps distributed means an app that can split its workload among multiple worker clients over the network you probably want twisted
QA
python reportlab use of splitfirst splitlast am trying to use python with reportlab to create pdf report according to the user guide special tablestyle indeces sic in any style command the first row index may be set to one of the special strings splitlast or splitfirst to indicate that the style should be used only for the last row of split table or the first row of continuation this allows splitting tables with nicer effects around the split have tried using several style elements including textcolor splitfirst splitfirst colors black textcolor splitfirst colors black textcolor splitfirst colors black and none of these seems to work the first generates typeerror with the message typeerror cannot concatenate str and int objects and the latter two generate typeerrors with the message typeerror an integer is required is this functionality simply broken or am doing something wrong if the latter what am doing wrong
well it looks as if will be answering my own question first the documentation flat out lies where it reads in any style command the first row index may be set to one of the special strings splitlast or splitfirst to indicate that the style should be used only for the last row of split table or the first row of continuation in the current release the splitlast and splitfirst row indices break with the aforementioned typeerrors on the textcolor and background commnds my suspicion based on reading the source code is that only the tablestyle line commands grid box lineabove and linebelow are currently compatible with the splitfirst and splitlast row indices suspect that all cell commands break with the aforementioned typeerrors however was able to do what wanted by subclassing the table class and overriding the onsplit method here is my code class xtable table def onsplit self byrow setstyle tablestyle textcolor colors black what this does is apply the text color black to the first and second cell of the second row of each page the first row is header repeated by the repeatrows parameter of the table more precisely it is doing this to the first and second cell of each frame but since am using the simpledoctemplate frames and pages are identical
QA
what is the difference between range and xrange functions in python apparently xrange is faster but have no idea why it is faster and no proof besides the anecdotal so far that it is faster or what besides that is different about for in range for in xrange
see this post to find difference between range and xrange to quote range returns exactly what you think list of consecutive integers of defined length beginning with xrange however returns an xrange object which acts great deal like an iterator
QA
what is the difference between range and xrange functions in python apparently xrange is faster but have no idea why it is faster and no proof besides the anecdotal so far that it is faster or what besides that is different about for in range for in xrange
xrange returns an iterator and only keeps one number in memory at time range keeps the entire list of numbers in memory
QA
what is the difference between range and xrange functions in python apparently xrange is faster but have no idea why it is faster and no proof besides the anecdotal so far that it is faster or what besides that is different about for in range for in xrange
range creates list so if you do range it creates list in memory with elements xrange is sequence object that evaluates lazily
QA
what is the difference between range and xrange functions in python apparently xrange is faster but have no idea why it is faster and no proof besides the anecdotal so far that it is faster or what besides that is different about for in range for in xrange
range generates the entire list and returns it xrange does not it generates the numbers in the list on demand
QA
what is the difference between range and xrange functions in python apparently xrange is faster but have no idea why it is faster and no proof besides the anecdotal so far that it is faster or what besides that is different about for in range for in xrange
xrange uses an iterator generates values on the fly range returns list
QA
what is the difference between range and xrange functions in python apparently xrange is faster but have no idea why it is faster and no proof besides the anecdotal so far that it is faster or what besides that is different about for in range for in xrange
do spend some time with the library reference the more familiar you are with it the faster you can find answers to questions like this especially important are the first few chapters about builtin objects and types the advantage of the xrange type is that an xrange object will always take the same amount of memory no matter the size of the range it represents there are no consistent performance advantages another way to find quick information about python construct is the docstring and the help function print xrange doc def doc print doc is super useful help xrange
QA
python module functions used in unexpected ways based on split string by spaces in python which uses shlex split to split string with quotes smartly would be interested in hearing about other common tasks solved by non obvious standard library functions if this turns into module of the week that is fine too
most of the other examples are merely overlooked not unexpected uses for module fnmatch like shlex can be applied in unexpected ways fnmatch is kind of poor person re and can be used for more than matching files it can compare strings with the simplified wild card patterns
QA
what is the difference between range and xrange functions in python apparently xrange is faster but have no idea why it is faster and no proof besides the anecdotal so far that it is faster or what besides that is different about for in range for in xrange
it is for optimization reasons range will create list of values from start to end in your example this will become an expensive operation on very large ranges xrange on the other hand is much more optimised it will only compute the next value when needed via an xrange sequence object and does not create list of all values like range does
QA
python implementation of parsec recently wrote parser in python using ply it is python reimplementation of yacc when was almost done with the parser discovered that the grammar need to parse requires me to do some look up during parsing to inform the lexer without doing look up to inform the lexer cannot correctly parse the strings in the language given than can control the state of the lexer from the grammar rules think will be solving my use case using look up table in the parser module but it may become too difficult to maintain test so want to know about some of the other options in haskell would use parsec library of parsing functions known as combinators is there python implementation of parsec or perhaps some other production quality library full of parsing functionality so can build context sensitive parser in python edit all my attempts at context free parsing have failed for this reason do not expect antlr to be useful here
an option you may consider if an ll parser is ok to you is to give antlr try it can generate python too actually it is ll as they name it stands for the quantity of lookahead it can cope with
QA
python implementation of parsec recently wrote parser in python using ply it is python reimplementation of yacc when was almost done with the parser discovered that the grammar need to parse requires me to do some look up during parsing to inform the lexer without doing look up to inform the lexer cannot correctly parse the strings in the language given than can control the state of the lexer from the grammar rules think will be solving my use case using look up table in the parser module but it may become too difficult to maintain test so want to know about some of the other options in haskell would use parsec library of parsing functions known as combinators is there python implementation of parsec or perhaps some other production quality library full of parsing functionality so can build context sensitive parser in python edit all my attempts at context free parsing have failed for this reason do not expect antlr to be useful here
there is antlr which is ll there is pyparsing which is more object friendly and is sort of like dsl and then there is parsing which is like ocaml menhir
QA
what is the difference between range and xrange functions in python apparently xrange is faster but have no idea why it is faster and no proof besides the anecdotal so far that it is faster or what besides that is different about for in range for in xrange
range creates list so if you do range it creates list in memory with elements xrange is generator so it is sequence object is that evaluates lazily this is true but in python range will be implemented by the python xrange if you need to actually generate the list you will need to do list range
QA
python implementation of parsec recently wrote parser in python using ply it is python reimplementation of yacc when was almost done with the parser discovered that the grammar need to parse requires me to do some look up during parsing to inform the lexer without doing look up to inform the lexer cannot correctly parse the strings in the language given than can control the state of the lexer from the grammar rules think will be solving my use case using look up table in the parser module but it may become too difficult to maintain test so want to know about some of the other options in haskell would use parsec library of parsing functions known as combinators is there python implementation of parsec or perhaps some other production quality library full of parsing functionality so can build context sensitive parser in python edit all my attempts at context free parsing have failed for this reason do not expect antlr to be useful here
antlr is great and has the added benefit of working across multiple languages
QA
python module functions used in unexpected ways based on split string by spaces in python which uses shlex split to split string with quotes smartly would be interested in hearing about other common tasks solved by non obvious standard library functions if this turns into module of the week that is fine too
use itertools especially cycle repeat chain to make python behave more like and in other functional vector applications often this let us me avoid the overhead and complication of numpy in shorter iterables are automatically cycled and all functions apply in map like way over lists python normal python in range range out this code is terrible but it demos the idea from itertools import cycle def addr max len len out none gen gen cycle cycle ii while ii out ii gen next gen next ii return out in addr range range out
QA
what is the difference between range and xrange functions in python apparently xrange is faster but have no idea why it is faster and no proof besides the anecdotal so far that it is faster or what besides that is different about for in range for in xrange
xrange only stores the range params and generates the numbers on demand however the implementation of python currently restricts its args to longs xrange when long is bits overflowerror python int too large to convert to long range ok note that in python there is only range and it behaves like the xrange but without the limitations on minimum and maximum end points
QA
calling an external command in python how can call an external command as if would typed it at the unix she will or windows command prompt from within python script
typically use import subprocess subprocess popen ls she will true stdout subprocess pipe stderr subprocess stdout for line in stdout readlines print line retval wait you are free to do what you want with the stdout data in the pipe in fact you can simply omit those parameters stdout and stderr and it will behave like os system
QA
python implementation of parsec recently wrote parser in python using ply it is python reimplementation of yacc when was almost done with the parser discovered that the grammar need to parse requires me to do some look up during parsing to inform the lexer without doing look up to inform the lexer cannot correctly parse the strings in the language given than can control the state of the lexer from the grammar rules think will be solving my use case using look up table in the parser module but it may become too difficult to maintain test so want to know about some of the other options in haskell would use parsec library of parsing functions known as combinators is there python implementation of parsec or perhaps some other production quality library full of parsing functionality so can build context sensitive parser in python edit all my attempts at context free parsing have failed for this reason do not expect antlr to be useful here
pysec is another monadic parser do not know much about it but it is worth looking at here
QA
what is the difference between range and xrange functions in python apparently xrange is faster but have no idea why it is faster and no proof besides the anecdotal so far that it is faster or what besides that is different about for in range for in xrange
range creates list so if you do range it creates list in memory with elements xrange is generator so it evaluates lazily this brings you two advantages you can iterate longer lists without getting memoryerror as it resolves each number lazily if you stop iteration early you will not waste time creating the whole list
QA
does an application wide exception handler make sense long story short have substantial python application that among other things does outcalls to losetup mount etc on linux essentially consuming system resources that must be released when complete if my application crashes want to ensure these system resources are properly released does it make sense to do something like the following def main todo main application entry point pass def cleanup todo release system resources here pass if name main try main except cleanup raise is this something that is typically done is there better way perhaps the destructor in singleton class
application wide handler is fine they are great for logging just make sure that the application wide one is durable and is unlikely to crash itself
QA
does an application wide exception handler make sense long story short have substantial python application that among other things does outcalls to losetup mount etc on linux essentially consuming system resources that must be released when complete if my application crashes want to ensure these system resources are properly released does it make sense to do something like the following def main todo main application entry point pass def cleanup todo release system resources here pass if name main try main except cleanup raise is this something that is typically done is there better way perhaps the destructor in singleton class
like top level exception handlers in general regardless of language they are great place to cleanup resources that may not be immediately related to resources consumed inside the method that throws the exception it is also fantastic place to log those exceptions if you have such framework in place top level handlers will catch those bizarre exceptions you did not plan on and let you correct them in the future otherwise you may never know about them at all just be careful that your top level handler does not throw exceptions
QA
does an application wide exception handler make sense long story short have substantial python application that among other things does outcalls to losetup mount etc on linux essentially consuming system resources that must be released when complete if my application crashes want to ensure these system resources are properly released does it make sense to do something like the following def main todo main application entry point pass def cleanup todo release system resources here pass if name main try main except cleanup raise is this something that is typically done is there better way perhaps the destructor in singleton class
destructor as in del method is bad idea as these are not guaranteed to be called the atexit module is safer approach although these will still not fire if the python interpreter crashes rather than the python application or if os exit is used or the process is killed aggressively or the machine reboots of course the last item is not an issue in your case if your process is crash prone it uses fickle third party extension modules for instance you may want to do the cleanup in simple parent process for more isolation if you are not really worried use the atexit module
QA
does an application wide exception handler make sense long story short have substantial python application that among other things does outcalls to losetup mount etc on linux essentially consuming system resources that must be released when complete if my application crashes want to ensure these system resources are properly released does it make sense to do something like the following def main todo main application entry point pass def cleanup todo release system resources here pass if name main try main except cleanup raise is this something that is typically done is there better way perhaps the destructor in singleton class
that seems like reasonable approach and more straightforward and reliable than destructor on singleton class you might also look at the atexit module pronounced at exit not tex it or something like that confused that for long while
QA
python implementation of parsec recently wrote parser in python using ply it is python reimplementation of yacc when was almost done with the parser discovered that the grammar need to parse requires me to do some look up during parsing to inform the lexer without doing look up to inform the lexer cannot correctly parse the strings in the language given than can control the state of the lexer from the grammar rules think will be solving my use case using look up table in the parser module but it may become too difficult to maintain test so want to know about some of the other options in haskell would use parsec library of parsing functions known as combinators is there python implementation of parsec or perhaps some other production quality library full of parsing functionality so can build context sensitive parser in python edit all my attempts at context free parsing have failed for this reason do not expect antlr to be useful here
believe that pyparsing is based on the same principles as parsec
QA
python module functions used in unexpected ways based on split string by spaces in python which uses shlex split to split string with quotes smartly would be interested in hearing about other common tasks solved by non obvious standard library functions if this turns into module of the week that is fine too
was quite surprised to learn that you could use the bisect module to do very fast binary search in sequence it is documentation does not say anything about it this module provides support for maintaining list in sorted order without having to sort the list after each insertion the usage is very simple import bisect lst bisect bisect left lst you have to remember though that it is quicker to linearly look for something in list goes item by item than sorting the list and then doing binary search on it the first option is the second is nlogn
QA
python reading oracle path on my desktop have written small pylons app that connects to oracle am now trying to deploy it to my server which is running win my desktop is bit xp the oracle installation on the server is also bit was getting errors about loading the oci dll so installed the bit client into oracle if add this to the path environment variable it works great but also want to run the pylons app as service using this recipe and do not want to put this bit library on the path for all other applications tried using sys path append oracle bin but that does not seem to work
sys path is python internal representation of the pythonpath it sounds to me like you want to modify the path am not sure that this will work but you can try import os os environ path os pathsep oracle bin
QA
python sockets suddenly timing out came back today to an old script had for logging into gmail via ssl the script worked fine last time ran it several months ago but now it dies immediately with urlopen error the read operation timed out if set the timeout no matter how long it dies even more immediately with urlopen error the connect operation timed out the latter is reproducible with import socket socket setdefaulttimeout sock socket socket sock connect www google com ssl socket ssl sock returning socket sslerror the connect operation timed out but cannot seem to reproduce the former and after much stepping thru the code have no clue what is causing any of this
the first thing would check is whether you need to connect via an http proxy in which case direct connections bypassing the proxy will likely time out run wireshark and see what happens
QA
how to associated the cn in an ssl cert of pyopenssl verify cb to generated socket am little new to pyopenssl am trying to figure out how to associate the generated socket to an ssl cert verify cb gets called which give me access to the cert and conn but how do associate those things when this happens cli addr self server accept
after the handshake is complete you can get the client certificate while the client certificate is also available in the verify callback verify cb there is not really any reason to try to do anything aside from verify the certificate in that callback setting up an application specific mapping is better done after the handshake has completely successfully so consider using the openssl ssl connection instance returned by the accept method to get the certificate and from there the commonname and associate it with the connection object at that point for example client clientaddress self server accept client do handshake commonnamestoconnections client get peer certificate commonname client you might want to check the mapping to make sure you are not overwriting any existing connection perhaps using list of connections instead of just mapping each common name to one and of course you need to remove entries when connections are lost the do handshake call forces the handshake to actually happen without this the handshake will happen when application data is first transferred over the connection that is fine but it would make setting up this mapping slightly more complicated