prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
python regular expression for html parsing beautifulsoup want to grab the value of hidden input field in html input type hidden name fooid value want to write regular expression in python that will return the value of fooid given that know the line in the html follows the format input type hidden name fooid value id is here can someone provide an example in python to parse the html for the value
|
for this particular case beautifulsoup is harder to write than regex but it is much more robust am just contributing with the beautifulsoup example given that you already know which regexp to use from beautifulsoup import beautifulsoup or retrieve it from the web etc html data open yourwebsite page html read create the soup object from the html data soup beautifulsoup html data fooid soup find input name fooid type hidden find the proper tag value fooid attrs the value of the third attribute of the desired tag or index it directly via fooid value
|
QA
|
how can get emacs key bindings in python idle use emacs primarily for coding python but sometimes use idle is there way to change the key bindings easily in idle to match emacs
|
there is program for windows called xkeymacs that allows you to specify emacs keybindings for different programs it should work with idle http www cam hi ho ne jp oishi indexen html mark
|
QA
|
embedding remote python she will in an application you can embed the ipython she will inside of your application so that it launches the she will in the foreground is there way to embed telnet server in python app so that you can telnet to certain port and launch remote ipython she will any tips for redirecting the input output streams for ipython or how to hook it up to telnet server library or recommendations for other libraries that could be used to implement this are much appreciated
|
use twisted manhole docs are bit lacking but it is easy enough to set up telnet based remote server and it comes with gtk based gui main twisted site twisted manhole api docs
|
QA
|
how to generate urls in django in django template language you can use url viewname args to generate url to specific view with parameters how can you programatically do the same in python code what need is to create list of menu items where each item has name url and an active flag whether it is the current page or not this is because it will be lot cleaner to do this in python than the template language
|
am using two different approaches in my models py the first is the permalink decorator from django db models import permalink def get absolute url self construct the absolute url for this item return project app views view name str self id get absolute url permalink get absolute url you can also call reverse directly from django core urlresolvers import reverse def get absolute url self construct the absolute url for this item return reverse project app views view name none str self id
|
QA
|
how can get emacs key bindings in python idle use emacs primarily for coding python but sometimes use idle is there way to change the key bindings easily in idle to match emacs
|
idle provides emacs keybindings without having to install other software open up the menu item options configure idle go to keys tab in the drop down menu on the right side of the dialog change the select to idle classic unix it is not the true emacs key bindings but you get the basics like movement saving opening
|
QA
|
how do generate histogram for given probability distribution for functional testing server am trying to automate functional testing of server using realistic frequency distribution of requests sort of load testing sort of simulation have chosen the weibull distribution as it sort of matches the distribution have observed ramps up quickly drops off quickly but not instantly use this distribution to generate the number of requests that should be sent each day between given start and end date have hacked together an algorithm in python that sort of works but it feels kludgy how many days end date start date days freqs defaultdict int for in xrange how many responses freqs int how many days weibullvariate timeline day start date for freq in sorted freqs iteritems timeline append day freq day timedelta days return timeline what better ways are there to do this
|
instead of giving the number of requests as fixed value why not use scaling factor instead at the moment you are treating requests as limited quantity and randomising the days on which those requests fall it would seem more reasonable to treat your requests per day as independent from datetime import from random import timeline scaling start date date end date date num days end date start date days days start date timedelta for in range num days requests int scaling weibullvariate for in range num days timeline zip days requests timeline
|
QA
|
how do generate histogram for given probability distribution for functional testing server am trying to automate functional testing of server using realistic frequency distribution of requests sort of load testing sort of simulation have chosen the weibull distribution as it sort of matches the distribution have observed ramps up quickly drops off quickly but not instantly use this distribution to generate the number of requests that should be sent each day between given start and end date have hacked together an algorithm in python that sort of works but it feels kludgy how many days end date start date days freqs defaultdict int for in xrange how many responses freqs int how many days weibullvariate timeline day start date for freq in sorted freqs iteritems timeline append day freq day timedelta days return timeline what better ways are there to do this
|
rewrote the code above to be shorter but maybe it is too obfuscated now timeline start date timedelta days days for days in count how many days end date start date days pick day lambda int how many days weibullvariate days sorted imap pick day xrange how many responses histogram zip timeline len list responses for day responses in groupby days print join strftime for in histogram
|
QA
|
in python how can you easily retrieve sorted items from dictionary dictionaries unlike lists are not ordered and do not have the sort attribute therefore you can not rely on getting the items in the same order when first added what is the easiest way to loop through dictionary containing strings as the key value and retrieving them in ascending order by key for example you had this this is this is this is want to print the associated values in the following sequence sorted by key this is this is this is
|
for key in sorted print key
|
QA
|
python regular expression for html parsing beautifulsoup want to grab the value of hidden input field in html input type hidden name fooid value want to write regular expression in python that will return the value of fooid given that know the line in the html follows the format input type hidden name fooid value id is here can someone provide an example in python to parse the html for the value
|
input type hidden name za value za import re input type hidden name fooid value re match input type hidden name za value za groups fooid
|
QA
|
how do generate histogram for given probability distribution for functional testing server am trying to automate functional testing of server using realistic frequency distribution of requests sort of load testing sort of simulation have chosen the weibull distribution as it sort of matches the distribution have observed ramps up quickly drops off quickly but not instantly use this distribution to generate the number of requests that should be sent each day between given start and end date have hacked together an algorithm in python that sort of works but it feels kludgy how many days end date start date days freqs defaultdict int for in xrange how many responses freqs int how many days weibullvariate timeline day start date for freq in sorted freqs iteritems timeline append day freq day timedelta days return timeline what better ways are there to do this
|
slightly longer but probably more readable rework of your last four lines samples for in xrange how many days for in xrange how many responses samples min int how many days weibullvariate how many days histogram zip timeline samples print join strftime for in histogram this always drops the samples within the date range but you get corresponding bump at the end of the timeline from all of the samples that are above the range
|
QA
|
xml writing tools for python am currently trying elementtree and it looks fine it escapes html entities and so on and so forth am missing something truly wonderful have not heard of this is similar to what am actually doing import xml etree elementtree as et root et element html head et subelement root head script et subelement head script script set type text javascript script text var love aacute letters body et subelement root body et subelement body text and like the fact that tree et elementtree root tree write foo xhtml more foo xhtml html head script type text javascript var love amp aacute letters script head body and like the fact that gt body html
|
do not you actually want something like html head script type text javascript content var body and like the fact that just some paragraph think saw something like that somewhere this would be wonderful edit actually went and wrote library today to do just that magictree you can use it like this from magictree import html head script body root html head script var love amp aacute letters type text javascript body and like the fact that root is plain element object like those created with et element so you can write it out using elementtree tree et elementtree root tree write foo xhtml the magic in magictree lies in how the importing works the element factories are created when needed have look at the source it is based on an answer to another stackoverflow question
|
QA
|
xml writing tools for python am currently trying elementtree and it looks fine it escapes html entities and so on and so forth am missing something truly wonderful have not heard of this is similar to what am actually doing import xml etree elementtree as et root et element html head et subelement root head script et subelement head script script set type text javascript script text var love aacute letters body et subelement root body et subelement body text and like the fact that tree et elementtree root tree write foo xhtml more foo xhtml html head script type text javascript var love amp aacute letters script head body and like the fact that gt body html
|
another way is using the factory builder from lxml available in elementtree too from lxml import etree from lxml builder import def class args class is reserved word in python return class join args html page html create an element called html head title this is sample document body hello class title this is paragraph with bold text in it this is another paragraph with link href http www python org here are some reserved characters spam egg etree xml and finally an embedded xhtml fragment print etree tostring page pretty print true html head title this is sample document title head body class title hello this is paragraph with bold text in it this is another paragraph with href http www python org link here are some reservered characters lt spam amp egg gt and finally an embedded xhtml fragment body html
|
QA
|
xml writing tools for python am currently trying elementtree and it looks fine it escapes html entities and so on and so forth am missing something truly wonderful have not heard of this is similar to what am actually doing import xml etree elementtree as et root et element html head et subelement root head script et subelement head script script set type text javascript script text var love aacute letters body et subelement root body et subelement body text and like the fact that tree et elementtree root tree write foo xhtml more foo xhtml html head script type text javascript var love amp aacute letters script head body and like the fact that gt body html
|
assume that you are actually creating an xml dom tree because you want to validate that what goes into this file is valid xml since otherwise you would just write static string to file if validating your output is indeed your goal then would suggest from xml dom minidom import parsestring doc parsestring html head script type text javascript var love amp aacute letters script head body and like the fact that gt body html with open foo xhtml as write doc toxml this let us you just write the xml you want to output validate that it is correct since parsestring will raise an exception if it is invalid and have your code look much nicer presumably you are not just writing the same static xml every time and want some substitution in this case would have lines like var message and then use the operator to do the substitution like html message love amp aacute letters
|
QA
|
is there way to attach debugger to multi threaded python process am trying to debug deadlock in multi threaded python application after it has locked up is there way to attach debugger to inspect the state of the process edit am attempting this on linux but it would be great if there were cross platform solution it is python after all
|
yeah gdb is good for lower level debugging you can change threads with the thread command gdb thr switching to thread process thread gdb backtrace you could also check out python specific debuggers like winpdb or pydb both platform independent
|
QA
|
how do generate histogram for given probability distribution for functional testing server am trying to automate functional testing of server using realistic frequency distribution of requests sort of load testing sort of simulation have chosen the weibull distribution as it sort of matches the distribution have observed ramps up quickly drops off quickly but not instantly use this distribution to generate the number of requests that should be sent each day between given start and end date have hacked together an algorithm in python that sort of works but it feels kludgy how many days end date start date days freqs defaultdict int for in xrange how many responses freqs int how many days weibullvariate timeline day start date for freq in sorted freqs iteritems timeline append day freq day timedelta days return timeline what better ways are there to do this
|
this is quick and probably not that accurate but if you calculate the pdf yourself then at least you make it easier to lay several smaller larger ones on single timeline dev is the std deviation in the guassian noise which controls the roughness note that this is not the right way to generate what you want but it is easy import math from datetime import datetime timedelta date from random import gauss how many responses start date date end date date num days end date start date days timeline start date timedelta for in xrange num days def weibull return math dev samples num days for in range num days probs weibull for in samples noise gauss dev for in samples simdata max for in zip probs noise events int how many responses sum probs for in simdata histogram zip timeline events print join strftime for in histogram
|
QA
|
round in python does not seem to be rounding properly the documentation for the round function states that you pass it number and the positions past the decimal to round thus it should do this round but in actuality good old floating point weirdness creeps in and you get for the purposes of ui need to display poked around the internet and found some documentation that this is dependent on my implementation of python unfortunately this occurs on both my windows dev machine and each linux server have tried see here also short of creating my own round library is there any way around this
|
cannot help the way it is stored but at least formatting works correctly round gives you
|
QA
|
round in python does not seem to be rounding properly the documentation for the round function states that you pass it number and the positions past the decimal to round thus it should do this round but in actuality good old floating point weirdness creeps in and you get for the purposes of ui need to display poked around the internet and found some documentation that this is dependent on my implementation of python unfortunately this occurs on both my windows dev machine and each linux server have tried see here also short of creating my own round library is there any way around this
|
you can switch the data type to integer int int and then display the number by inserting the locale decimal separator however jimmy answer is better
|
QA
|
round in python does not seem to be rounding properly the documentation for the round function states that you pass it number and the positions past the decimal to round thus it should do this round but in actuality good old floating point weirdness creeps in and you get for the purposes of ui need to display poked around the internet and found some documentation that this is dependent on my implementation of python unfortunately this occurs on both my windows dev machine and each linux server have tried see here also short of creating my own round library is there any way around this
|
you can use the string format operator similar to sprintf mystring
|
QA
|
round in python does not seem to be rounding properly the documentation for the round function states that you pass it number and the positions past the decimal to round thus it should do this round but in actuality good old floating point weirdness creeps in and you get for the purposes of ui need to display poked around the internet and found some documentation that this is dependent on my implementation of python unfortunately this occurs on both my windows dev machine and each linux server have tried see here also short of creating my own round library is there any way around this
|
you get if you do str round instead of just round
|
QA
|
round in python does not seem to be rounding properly the documentation for the round function states that you pass it number and the positions past the decimal to round thus it should do this round but in actuality good old floating point weirdness creeps in and you get for the purposes of ui need to display poked around the internet and found some documentation that this is dependent on my implementation of python unfortunately this occurs on both my windows dev machine and each linux server have tried see here also short of creating my own round library is there any way around this
|
floating point math is vulnerable to slight but annoying precision inaccuracies if you can work with integer or fixed point you will be guaranteed precision
|
QA
|
round in python does not seem to be rounding properly the documentation for the round function states that you pass it number and the positions past the decimal to round thus it should do this round but in actuality good old floating point weirdness creeps in and you get for the purposes of ui need to display poked around the internet and found some documentation that this is dependent on my implementation of python unfortunately this occurs on both my windows dev machine and each linux server have tried see here also short of creating my own round library is there any way around this
|
printf the sucker print returns
|
QA
|
round in python does not seem to be rounding properly the documentation for the round function states that you pass it number and the positions past the decimal to round thus it should do this round but in actuality good old floating point weirdness creeps in and you get for the purposes of ui need to display poked around the internet and found some documentation that this is dependent on my implementation of python unfortunately this occurs on both my windows dev machine and each linux server have tried see here also short of creating my own round library is there any way around this
|
formatting works correctly even without having to round
|
QA
|
round in python does not seem to be rounding properly the documentation for the round function states that you pass it number and the positions past the decimal to round thus it should do this round but in actuality good old floating point weirdness creeps in and you get for the purposes of ui need to display poked around the internet and found some documentation that this is dependent on my implementation of python unfortunately this occurs on both my windows dev machine and each linux server have tried see here also short of creating my own round library is there any way around this
|
round is working fine the problem is that cannot be represented exactly in binary floating point as vinko says you can use string formatting to do rounding for display python has module for decimal arithmetic if you need that
|
QA
|
convert xml html entities into unicode string in python am doing some web scraping and sites frequently use html entities to represent non ascii characters does python have utility that takes string with html entities and returns unicode type for example get back ce which represents an with tone mark in binary this is represented as the bit ce want to convert the html entity into the value you ce
|
you could find an answer here getting international characters from web page edit it seems like beautifulsoup does not convert entities written in hexadecimal form it can be fixed import copy re from beautifulsoup import beautifulsoup hexentitymassage copy copy beautifulsoup markup massage replace hexadecimal character reference by decimal one hexentitymassage re compile lambda int group def convert html return beautifulsoup html convertentities beautifulsoup html entities markupmassage hexentitymassage contents string html html ce html print repr convert html you ce ce edit unescape function mentioned by df which uses htmlentitydefs standard module and unichr might be more appropriate in this case
|
QA
|
using in to match an attribute of python objects in an array do not remember whether was dreaming or not but seem to recall there being function which allowed something like foo in iter attr array of python objects attribute name have looked over the docs but this kind of thing does not fall under any obvious listed headers
|
using list comprehension would build temporary list which could eat all your memory if the sequence being searched is large even if the sequence is not large building the list means iterating over the whole of the sequence before in could start its search the temporary list can be avoiding by using generator expression foo foo in obj id for obj in bar now as long as obj id near the start of bar the search will be fast even if bar is infinitely long as matt suggested it is good idea to use hasattr if any of the objects in bar can be missing an id attribute foo foo in obj id for obj in bar if hasattr obj id
|
QA
|
convert xml html entities into unicode string in python am doing some web scraping and sites frequently use html entities to represent non ascii characters does python have utility that takes string with html entities and returns unicode type for example get back ce which represents an with tone mark in binary this is represented as the bit ce want to convert the html entity into the value you ce
|
use the builtin unichr beautifulsoup is not necessary entity ce unichr int entity you ce
|
QA
|
convert xml html entities into unicode string in python am doing some web scraping and sites frequently use html entities to represent non ascii characters does python have utility that takes string with html entities and returns unicode type for example get back ce which represents an with tone mark in binary this is represented as the bit ce want to convert the html entity into the value you ce
|
python has the htmlentitydefs module but this does not include function to unescape html entities python developer fredrik lundh author of elementtree among other things has such function on his website which works with decimal hex and named entities import re htmlentitydefs removes html or xml character references and entities from text string param text the html or xml source text return the plain text as unicode string if necessary def unescape text def fixup text group if text character reference try if text return unichr int text else return unichr int text except valueerror pass else named entity try text unichr htmlentitydefs name codepoint text except keyerror pass return text leave as is return re sub fixup text
|
QA
|
does re compile or any given python library call throw an exception cannot tell from the python documentation whether the re compile function may throw an exception assuming you pass in string imagine there is something that could be considered an invalid regular expression the larger question is where do go to find if given python library call may throw exception and what those are
|
well re compile certainly may import re re compile he lo traceback most recent call last file stdin line in module file python lib re py line in compile return compile pattern flags file python lib re py line in compile raise error invalid expression sre constants error unbalanced parenthesis the documentation does support this in roundabout way check the bottom of the module contents page for brief description of the error exception unfortunately do not have any answer to the general question suppose the documentation for the various modules varies in quality and thoroughness if there were particular modules you were interested in you might be able to decompile them if written in python or even look at the source if they are in the standard library
|
QA
|
does re compile or any given python library call throw an exception cannot tell from the python documentation whether the re compile function may throw an exception assuming you pass in string imagine there is something that could be considered an invalid regular expression the larger question is where do go to find if given python library call may throw exception and what those are
|
unlike java where there are exceptions that must be declared to be raised and some that do not have to be but that is another story any python code may raise any exception at any time there are list of built in exceptions which generally has some description of when these exceptions might be raised its up to you as to how much exception handling you will do and if you will handle stuff gracefully or just fail with traceback
|
QA
|
how do get the external ip of socket in python when call socket getsockname on socket object it returns tuple of my machine internal ip and the port however would like to retrieve my external ip what is the cheapest most efficient manner of doing this
|
this is not possible without cooperation from an external server because there could be any number of nats between you and the other computer if it is custom protocol you could ask the other system to report what address it is connected to
|
QA
|
how do get the external ip of socket in python when call socket getsockname on socket object it returns tuple of my machine internal ip and the port however would like to retrieve my external ip what is the cheapest most efficient manner of doing this
|
the only way can think of that is guaranteed to give it to you is to hit service like http whatismyip com to get it
|
QA
|
how to get an absolute file path in python given path such as mydir myfile txt how do find the absolute filepath relative to the current working directory in python on windows might end up with example cwd mydir myfile txt
|
better still install the path py module it wraps all the os path functions and other related functions into methods on an object that can be used wherever strings are used from path import path path mydir myfile txt abspath example cwd mydir myfile txt
|
QA
|
xml writing tools for python am currently trying elementtree and it looks fine it escapes html entities and so on and so forth am missing something truly wonderful have not heard of this is similar to what am actually doing import xml etree elementtree as et root et element html head et subelement root head script et subelement head script script set type text javascript script text var love aacute letters body et subelement root body et subelement body text and like the fact that tree et elementtree root tree write foo xhtml more foo xhtml html head script type text javascript var love amp aacute letters script head body and like the fact that gt body html
|
try http uche ogbuji net tech suite amara it is quite complete and has straight forward set of access tools normal unicode support etc output the xml entry def genfileold out label term idval filename entrytime html writer markupwriter out indent you yes writer startdocument test element and attribute writing ans namespace you http www org atom xns namespace you http www org xhtml writer startelement you entry ans extranss you you http www org xhtml you dc you http purl org dc elements you you http www org atom writer attribute you xml lang unicode en uk writer simpleelement you title ans content unicode label writer simpleelement you subtitle ans content you id unicode http www dpawson co uk nodesets afn split writer simpleelement you id ans content id writer simpleelement you updated ans content unicode dtime writer startelement you author ans writer simpleelement you name ans content you dave writer simpleelement you uri ans content you http www dpawson co uk nodesets afn xml writer endelement you author writer startelement you category ans if prompt label unicode raw input enter label writer attribute you label unicode label if prompt term unicode raw input enter term to use writer attribute you term unicode term writer endelement you category writer simpleelement you rights ans content you dave writer startelement you link ans writer attribute you href unicode http www dpawson co uk nodesets entries afn html writer attribute you rel unicode alternate writer endelement you link writer startelement you published ans dt dtime dtu unicode dt writer text dtu writer endelement you published writer simpleelement you summary ans content unicode label writer startelement you content ans writer attribute you type unicode xhtml writer startelement you div xns writer simpleelement you xns content unicode label writer endelement you div writer endelement you content writer endelement you entry
|
QA
|
can document python code with doxygen and does it make sense like doxygen to create documentation of or php code have an upcoming python project and think remember that python does not have comments and also has its own self documentation facility which seems to be the pythonic way to document can just use doxygen anything particular to be aware of have done some coding in python but so far only on small projects where was to lazy to document at all yeah know but let us just pretend that is ok for now
|
this is documented on the doxygen website but to summarize here you can use doxygen to document your python code you can either use the python documentation string syntax package docstring documentation for this module more details def func documentation for function more details pass in which case the comments will be extracted by doxygen but you will not be able to use any of the special doxygen commands or you can similar to style languages under doxygen double up the comment marker on the first line before the member package pyexample documentation for this module more details documentation for function more details def func pass in that case you can use the special doxygen commands there is no particular python output mode but you can apparently improve the results by setting optmize output java to yes honestly am little surprised at the difference it seems like once doxygen can detect the comments in blocks or blocks most of the work would be done and you would be able to use the special commands in either case maybe they expect people using to adhere to more pythonic documentation practices and that would interfere with the special doxygen commands
|
QA
|
how would you design very pythonic ui framework have been playing with the ruby library shoes basically you can write gui application in the following way shoes app do para not clicked button the label do alert you clicked the button when clicked make an alert replace clicked and replace the label text end end this made me think how would design similarly nice to use gui framework in python one that does not have the usual tyings of basically being wrappers to library in the case of gtk tk wx qt etc etc shoes takes things from web devlopment like style colour notation css layout techniques like margin and from ruby extensively using blocks in sensible ways python lack of rubyish blocks makes metaphorically direct port impossible def shoeless shoes app self para not clicked def on click func self alert you clicked the button self replace clicked button the label click self on click func no where near as clean and would not be nearly as flexible and am not even sure if it would be implementable using decorators seems like an interesting way to map blocks of code to specific action class basecontrol def init self self func none def clicked self func self func func def call self if self func is not none self func class button basecontrol pass class label basecontrol pass the actual applications code that the end user would write class myapp ok button la label ok clicked def clickeryhappened print ok clicked if name main myapp ok trigger the clicked action basically the decorator function stores the function then when the action occurred say click the appropriate function would be executed the scope of various stuff say the la label in the above example could be rather complicated but it seems doable in fairly neat manner
|
you could actually pull this off but it would require using metaclasses which are deep magic there be dragons if you want an intro to metaclasses there is series of articles from ibm which manage to introduce the ideas without melting your brain the source code from an orm like sqlobject might help too since it uses this same kind of declarative syntax
|
QA
|
how would you design very pythonic ui framework have been playing with the ruby library shoes basically you can write gui application in the following way shoes app do para not clicked button the label do alert you clicked the button when clicked make an alert replace clicked and replace the label text end end this made me think how would design similarly nice to use gui framework in python one that does not have the usual tyings of basically being wrappers to library in the case of gtk tk wx qt etc etc shoes takes things from web devlopment like style colour notation css layout techniques like margin and from ruby extensively using blocks in sensible ways python lack of rubyish blocks makes metaphorically direct port impossible def shoeless shoes app self para not clicked def on click func self alert you clicked the button self replace clicked button the label click self on click func no where near as clean and would not be nearly as flexible and am not even sure if it would be implementable using decorators seems like an interesting way to map blocks of code to specific action class basecontrol def init self self func none def clicked self func self func func def call self if self func is not none self func class button basecontrol pass class label basecontrol pass the actual applications code that the end user would write class myapp ok button la label ok clicked def clickeryhappened print ok clicked if name main myapp ok trigger the clicked action basically the decorator function stores the function then when the action occurred say click the appropriate function would be executed the scope of various stuff say the la label in the above example could be rather complicated but it seems doable in fairly neat manner
|
maybe not as slick as the ruby version but how about something like this from boots import app para button alert def shoeless app para text not clicked button label the label def on clicked self alert you clicked the button self text clicked like justin said to implement this you would need to use custom metaclass on class app and bunch of properties on para and button this actually would not be too hard the problem you run into next is how do you keep track of the order that things appear in the class definition in python there is no way to know if should be above or the other way around since you receive the contents of the class definition as python dict however in python metaclasses are being changed in couple of minor ways one of them is the prepare method which allows you to supply your own custom dictionary like object to be used instead this means you will be able to track the order in which items are defined and position them accordingly in the window
|
QA
|
can document python code with doxygen and does it make sense like doxygen to create documentation of or php code have an upcoming python project and think remember that python does not have comments and also has its own self documentation facility which seems to be the pythonic way to document can just use doxygen anything particular to be aware of have done some coding in python but so far only on small projects where was to lazy to document at all yeah know but let us just pretend that is ok for now
|
an other very good documentation tool is sphinx it will be used for the upcoming python documentation and is used by django and lot of other python projects from the sphinx website output formats html including windows html help and latex for printable pdf versions extensive cross references semantic markup and automatic links for functions classes glossary terms and similar pieces of information hierarchical structure easy definition of document tree with automatic links to siblings parents and children automatic indices general index as well as module index code handling automatic highlighting using the pygments highlighter extensions automatic testing of code snippets inclusion of docstrings from python modules and more
|
QA
|
is there way to attach debugger to multi threaded python process am trying to debug deadlock in multi threaded python application after it has locked up is there way to attach debugger to inspect the state of the process edit am attempting this on linux but it would be great if there were cross platform solution it is python after all
|
if you mean the pydb there is no way to do it there was some effort in that direction see the svn commit but it was abandoned supposedly winpdb supports it
|
QA
|
in python how can you easily retrieve sorted items from dictionary dictionaries unlike lists are not ordered and do not have the sort attribute therefore you can not rely on getting the items in the same order when first added what is the easiest way to loop through dictionary containing strings as the key value and retrieving them in ascending order by key for example you had this this is this is this is want to print the associated values in the following sequence sorted by key this is this is this is
|
you can also sort dictionary by value and control the sort order import operator this is this is this is for key value in sorted iteritems key operator itemgetter reverse true print key value output this is this is this is
|
QA
|
storing multiple arrays in python am writing program to simulate the actual polling data companies like gallup or rasmussen publish daily www gallup com and www rassmussenreports com am using brute force method where the computer generates some random daily polling data and then calculates three day averages to see if the average of the random data matches pollsters numbers most companies poll numbers are three day averages currently it works well for one iteration but my goal is to have it produce the most common simulation that matches the average polling data could then change the code of anywhere from to iterations and this is my problem at the end of the test have an array in single variable that looks something like this the program currently produces one array for each correct simulation can store each array in single variable but then have to have program that could generate to variables depending on how many iterations requested how do avoid this know there is an intelligent way of doing this that does not require the program to generate variables to store arrays depending on how many simulations want code testing for mccain test while test round random random mctest append test mctestavg mctest mctest mctest mcavg is real data if mctestavg mcavg mcwork mctest how do repeat without creating multiple mcwork vars
|
are you talking about doing this would would would
|
QA
|
storing multiple arrays in python am writing program to simulate the actual polling data companies like gallup or rasmussen publish daily www gallup com and www rassmussenreports com am using brute force method where the computer generates some random daily polling data and then calculates three day averages to see if the average of the random data matches pollsters numbers most companies poll numbers are three day averages currently it works well for one iteration but my goal is to have it produce the most common simulation that matches the average polling data could then change the code of anywhere from to iterations and this is my problem at the end of the test have an array in single variable that looks something like this the program currently produces one array for each correct simulation can store each array in single variable but then have to have program that could generate to variables depending on how many iterations requested how do avoid this know there is an intelligent way of doing this that does not require the program to generate variables to store arrays depending on how many simulations want code testing for mccain test while test round random random mctest append test mctestavg mctest mctest mctest mcavg is real data if mctestavg mcavg mcwork mctest how do repeat without creating multiple mcwork vars
|
lists in python can contain any type of object if understand the question correctly will list of lists do the job something like this assuming you have function generate poll data which creates your data data for in xrange num iterations data append generate poll data then data will be the list of data from the th run
|
QA
|
storing multiple arrays in python am writing program to simulate the actual polling data companies like gallup or rasmussen publish daily www gallup com and www rassmussenreports com am using brute force method where the computer generates some random daily polling data and then calculates three day averages to see if the average of the random data matches pollsters numbers most companies poll numbers are three day averages currently it works well for one iteration but my goal is to have it produce the most common simulation that matches the average polling data could then change the code of anywhere from to iterations and this is my problem at the end of the test have an array in single variable that looks something like this the program currently produces one array for each correct simulation can store each array in single variable but then have to have program that could generate to variables depending on how many iterations requested how do avoid this know there is an intelligent way of doing this that does not require the program to generate variables to store arrays depending on how many simulations want code testing for mccain test while test round random random mctest append test mctestavg mctest mctest mctest mcavg is real data if mctestavg mcavg mcwork mctest how do repeat without creating multiple mcwork vars
|
since you are thinking in variables you might prefer dictionary over list of lists data data generate poll data data generate poll data etc
|
QA
|
storing multiple arrays in python am writing program to simulate the actual polling data companies like gallup or rasmussen publish daily www gallup com and www rassmussenreports com am using brute force method where the computer generates some random daily polling data and then calculates three day averages to see if the average of the random data matches pollsters numbers most companies poll numbers are three day averages currently it works well for one iteration but my goal is to have it produce the most common simulation that matches the average polling data could then change the code of anywhere from to iterations and this is my problem at the end of the test have an array in single variable that looks something like this the program currently produces one array for each correct simulation can store each array in single variable but then have to have program that could generate to variables depending on how many iterations requested how do avoid this know there is an intelligent way of doing this that does not require the program to generate variables to store arrays depending on how many simulations want code testing for mccain test while test round random random mctest append test mctestavg mctest mctest mctest mcavg is real data if mctestavg mcavg mcwork mctest how do repeat without creating multiple mcwork vars
|
would strongly consider using numpy to do this you get efficient dimensional arrays that you can quickly and easily process
|
QA
|
storing multiple arrays in python am writing program to simulate the actual polling data companies like gallup or rasmussen publish daily www gallup com and www rassmussenreports com am using brute force method where the computer generates some random daily polling data and then calculates three day averages to see if the average of the random data matches pollsters numbers most companies poll numbers are three day averages currently it works well for one iteration but my goal is to have it produce the most common simulation that matches the average polling data could then change the code of anywhere from to iterations and this is my problem at the end of the test have an array in single variable that looks something like this the program currently produces one array for each correct simulation can store each array in single variable but then have to have program that could generate to variables depending on how many iterations requested how do avoid this know there is an intelligent way of doing this that does not require the program to generate variables to store arrays depending on how many simulations want code testing for mccain test while test round random random mctest append test mctestavg mctest mctest mctest mcavg is real data if mctestavg mcavg mcwork mctest how do repeat without creating multiple mcwork vars
|
would something like this work from random import randint mcworks for in xrange num iterations mctest randint for in xrange if sum mctest mcavg mcworks append mctest mcavg is real data in the end you are left with list of valid mctest lists what changed used list comprehension to build the data instead of for loop used random randint to get random integers used slices and sum to calculate the average of the first three items to answer your actual question put the results in list mcworks instead of creating new variable for every iteration
|
QA
|
how to retrieve an element from set without removing it suppose the following set how do get value any value out of without doing pop want to leave the item in the set until am sure can remove it something can only be sure of after an asynchronous call to another host quick and dirty elem pop add elem but do you know of better way ideally in constant time
|
two options that do not require copying the whole set for in break is now an element from or next iter but in general sets do not support indexing or slicing
|
QA
|
how to retrieve an element from set without removing it suppose the following set how do get value any value out of without doing pop want to leave the item in the set until am sure can remove it something can only be sure of after an asynchronous call to another host quick and dirty elem pop add elem but do you know of better way ideally in constant time
|
another option is to use dictionary with values you do not care about poor man set poor man set none poor man set none poor man set none you can treat the keys as set except that they are just an array keys poor man set keys print some key keys side effect of this choice is that your code will be backwards compatible with older pre set versions of python it is maybe not the best answer but it is another option edit you can even do something like this to hide the fact that you used dict instead of an array or set poor man set poor man set none poor man set none poor man set none poor man set poor man set keys
|
QA
|
can document python code with doxygen and does it make sense like doxygen to create documentation of or php code have an upcoming python project and think remember that python does not have comments and also has its own self documentation facility which seems to be the pythonic way to document can just use doxygen anything particular to be aware of have done some coding in python but so far only on small projects where was to lazy to document at all yeah know but let us just pretend that is ok for now
|
sphinx is mainly tool for formatting docs written independently from the source code as understand it for generating api docs from python docstrings the leading tools are pdoc and pydoctor here is pydoctor generated api docs for twisted and bazaar of course if you just want to have look at the docstrings while you are working on stuff there is the pydoc command line tool and as well as the help function available in the interactive interpreter
|
QA
|
how to retrieve an element from set without removing it suppose the following set how do get value any value out of without doing pop want to leave the item in the set until am sure can remove it something can only be sure of after an asynchronous call to another host quick and dirty elem pop add elem but do you know of better way ideally in constant time
|
since you want random element this will also work import random set random sample the documentation does not seem to mention performance of random sample from really quick empirical test with huge list and huge set it seems to be constant time for list but not for the set also iteration over set is not random the order is undefined but predictable list set range range true if randomness is important and you need bunch of elements in constant time large sets would use random sample and convert to list first lst list once len random sample lst constant time
|
QA
|
replacements for switch statement in python want to write function in python that returns different fixed values based on the value of an input index in other languages would use switch or case statement but python does not appear to have switch statement what are the recommended python solutions in this scenario
|
you could use dictionary def return
|
QA
|
replacements for switch statement in python want to write function in python that returns different fixed values based on the value of an input index in other languages would use switch or case statement but python does not appear to have switch statement what are the recommended python solutions in this scenario
|
have always liked doing it this way result lambda lambda lambda value from here
|
QA
|
replacements for switch statement in python want to write function in python that returns different fixed values based on the value of an input index in other languages would use switch or case statement but python does not appear to have switch statement what are the recommended python solutions in this scenario
|
if you are really just returning predetermined fixed value you could create dictionary with all possible input indexes as the keys along with their corresponding values also you might not really want function to do this unless you are computing the return value somehow oh and if you feel like doing something switch like see here
|
QA
|
automate firefox with python been scouring the net for something like firewatir but for python am trying to automate firefox on linux any suggestions
|
the languages of choice of firefox is javascript unless you have specific requirement that requires python would advice you to use that
|
QA
|
automate firefox with python been scouring the net for something like firewatir but for python am trying to automate firefox on linux any suggestions
|
you could try selenium
|
QA
|
how to retrieve an element from set without removing it suppose the following set how do get value any value out of without doing pop want to leave the item in the set until am sure can remove it something can only be sure of after an asynchronous call to another host quick and dirty elem pop add elem but do you know of better way ideally in constant time
|
least code would be set list obviously this would create new list which contains each member of the set so not great if your set is very large
|
QA
|
replacements for switch statement in python want to write function in python that returns different fixed values based on the value of an input index in other languages would use switch or case statement but python does not appear to have switch statement what are the recommended python solutions in this scenario
|
in addition to the dictionary methods which really like by the way you can also use if elif else to obtain the switch case default functionality if do the thing elif do the other thing if in because fall through by not using elif but now the default case includes case elif in xyz do yet another thing else do the default this of course is not identical to switch case you cannot have fall through as easily as leaving off the break statement but you can have more complicated test its formatting is nicer than series of nested ifs even though functionally that is what it is closer to
|
QA
|
replacements for switch statement in python want to write function in python that returns different fixed values based on the value of an input index in other languages would use switch or case statement but python does not appear to have switch statement what are the recommended python solutions in this scenario
|
there is pattern that learned from twisted python code class smtp def lookupmethod self command return getattr self do command upper none def do helo self rest return how do you rest def do quit self rest return bye smtp lookupmethod helo foo bar com how do you foo bar com smtp lookupmethod quit bye you can use it any time you need to dispatch on token and execute extended piece of code in state machine you would have state methods and dispatch on self state this switch can be cleanly extended by inheriting from base class and defining your own do methods often times you will not even have do methods in the base class edit how exactly is that used in case of smtp you will receive helo from the wire the relevant code from twisted mail smtp py modified for our case looks like this class smtp def do unknown self rest raise notimplementederror received unknown command def state command self line line line strip parts line split none if parts method self lookupmethod parts or self do unknown if len parts return method parts else return method else raise syntaxerror bad syntax smtp state command helo foo bar com how do you foo bar com you will receive helo foo bar com or you might get quit or rcpt to foo this is tokenized into parts as helo foo bar com the actual method lookup name is taken from parts the original method is also called state command because it uses the same pattern to implement state machine getattr self state self mode
|
QA
|
can distutils create empty init py files if all of my init py files are empty do have to store them into version control or is there way to make distutils create empty init py files during installation
|
in python init py files actually have meaning they mean that the folder they are in is python module as such they have real role in your code and should most probably be stored in version control you could well imagine folder in your source tree that is not python module for example folder containing only resources images and no code that folder would not need to have init py file in it now how do you make the difference between folders where distutils should create those files and folders where it should not
|
QA
|
windows mobile development in python what is the best way to start developing windows mobile professional applications in python is there reasonable sdk including an emulator is it even possible without doing excessive amount of underlaying windows api calls for ui for instance
|
python ce python port for windows ce pocket pc devices intended to be as close to desktop version as possible console current directory support testsuite passed
|
QA
|
windows mobile development in python what is the best way to start developing windows mobile professional applications in python is there reasonable sdk including an emulator is it even possible without doing excessive amount of underlaying windows api calls for ui for instance
|
if the ironpython and net compact framework teams work together visual studio may one day support python for windows mobile development out of the box unfortunately this feature request has been sitting on their issue tracker for ages
|
QA
|
can distutils create empty init py files if all of my init py files are empty do have to store them into version control or is there way to make distutils create empty init py files during installation
|
is there reason you want to avoid putting empty init py files in version control if you do this you will not be able to import your packages from the source directory wihout first running distutils if you really want to suppose you can create init py in setup py it has to be before running distutils setup so setup itself is able to find your packages from distutils import setup import os for path in my package directories filename os path join pagh init py if not os path exists filename init open filename init close setup but what would you gain from this compared to having the empty init py files there in the first place
|
QA
|
automate firefox with python been scouring the net for something like firewatir but for python am trying to automate firefox on linux any suggestions
|
see if twill can help you it can be used as command line tool or as python library
|
QA
|
automate firefox with python been scouring the net for something like firewatir but for python am trying to automate firefox on linux any suggestions
|
install mozlab in firefox and enable the telnet server then open socket
|
QA
|
how would you design very pythonic ui framework have been playing with the ruby library shoes basically you can write gui application in the following way shoes app do para not clicked button the label do alert you clicked the button when clicked make an alert replace clicked and replace the label text end end this made me think how would design similarly nice to use gui framework in python one that does not have the usual tyings of basically being wrappers to library in the case of gtk tk wx qt etc etc shoes takes things from web devlopment like style colour notation css layout techniques like margin and from ruby extensively using blocks in sensible ways python lack of rubyish blocks makes metaphorically direct port impossible def shoeless shoes app self para not clicked def on click func self alert you clicked the button self replace clicked button the label click self on click func no where near as clean and would not be nearly as flexible and am not even sure if it would be implementable using decorators seems like an interesting way to map blocks of code to specific action class basecontrol def init self self func none def clicked self func self func func def call self if self func is not none self func class button basecontrol pass class label basecontrol pass the actual applications code that the end user would write class myapp ok button la label ok clicked def clickeryhappened print ok clicked if name main myapp ok trigger the clicked action basically the decorator function stores the function then when the action occurred say click the appropriate function would be executed the scope of various stuff say the la label in the above example could be rather complicated but it seems doable in fairly neat manner
|
this could be an oversimplification do not think it would be good idea to try to make general purpose ui library this way on the other hand you could use this approach metaclasses and friends to simplify the definition of certain classes of user interfaces for an existing ui library and depending of the application that could actually save you significant amount of time and code lines
|
QA
|
automate firefox with python been scouring the net for something like firewatir but for python am trying to automate firefox on linux any suggestions
|
use selenium rc all my tests are written in python and are run with test suite one minor thing is that you either have to start selenium manually and point your tests to it or start selenium from test suite which requires little bit of coding but it is doable generally am very pleased with this solution
|
QA
|
cross platform ipc am looking for suggestions on possible ipc mechanisms that are cross platform win and linux at least simple to implement in as well as the most common scripting languages perl ruby python etc finally simple to use from programming point of view what are my options am programming under linux but would like what write to be portable to other oses in the future have thought about using sockets named pipes or something like dbus does anyone have any advice
|
for check out boost ipc you can probably create or find some bindings for the scripting languages as well otherwise if it is really important to be able to interface with scripting languages your best bet is simply to use files pipes or sockets or even higher level abstraction like http
|
QA
|
cross platform ipc am looking for suggestions on possible ipc mechanisms that are cross platform win and linux at least simple to implement in as well as the most common scripting languages perl ruby python etc finally simple to use from programming point of view what are my options am programming under linux but would like what write to be portable to other oses in the future have thought about using sockets named pipes or something like dbus does anyone have any advice
|
how about facebook thrift thrift is software framework for scalable cross language services development it combines software stack with code generation engine to build services that work efficiently and seamlessly between java python php ruby erlang perl haskell cocoa smalltalk and ocaml
|
QA
|
cross platform ipc am looking for suggestions on possible ipc mechanisms that are cross platform win and linux at least simple to implement in as well as the most common scripting languages perl ruby python etc finally simple to use from programming point of view what are my options am programming under linux but would like what write to be portable to other oses in the future have thought about using sockets named pipes or something like dbus does anyone have any advice
|
it does not get more simple than using pipes which are supported on every os know of and can be accessed in pretty much every language check out this tutorial
|
QA
|
cross platform ipc am looking for suggestions on possible ipc mechanisms that are cross platform win and linux at least simple to implement in as well as the most common scripting languages perl ruby python etc finally simple to use from programming point of view what are my options am programming under linux but would like what write to be portable to other oses in the future have thought about using sockets named pipes or something like dbus does anyone have any advice
|
tcp sockets to localhost ftw
|
QA
|
cross platform ipc am looking for suggestions on possible ipc mechanisms that are cross platform win and linux at least simple to implement in as well as the most common scripting languages perl ruby python etc finally simple to use from programming point of view what are my options am programming under linux but would like what write to be portable to other oses in the future have thought about using sockets named pipes or something like dbus does anyone have any advice
|
think you will want something based on sockets if you want rpc rather than just ipc would suggest something like xml rpc soap which runs over http and can be used from any language
|
QA
|
python regex to match multi line preprocessor macro what follows is regular expression have written to match multi line pre processor macros in code am by no means regular expressions guru so would welcome any advice on how can make this better here is the regex define it should match all of this define foo if dosomething but only some of this should not match the next line of code define foo if dosomething normalcode and also should not match single line preprocessor macros am pretty sure that the regex above works but as said there probably better way of doing it and imagine that there are ways of breaking it can anyone suggest any
|
this is simple test program knocked up usr bin env python test include foo define bar foo include bar test define bar foo define foobar test define foo if dosomething test define foo if dosomething normalcode import re matcher re compile define re multiline def extractdefines mo matcher search if not mo print mo return print mo group extractdefines test extractdefines test extractdefines test extractdefines test the re used define is very similar to the one use used the changes to avoid newlines at the start of the define rely on being greedy so can use simple at the end to get the first line of the define that does not end with
|
QA
|
python regex to match multi line preprocessor macro what follows is regular expression have written to match multi line pre processor macros in code am by no means regular expressions guru so would welcome any advice on how can make this better here is the regex define it should match all of this define foo if dosomething but only some of this should not match the next line of code define foo if dosomething normalcode and also should not match single line preprocessor macros am pretty sure that the regex above works but as said there probably better way of doing it and imagine that there are ways of breaking it can anyone suggest any
|
start define continuation lastline re multiline macros re compile start continuation lastline re multiline
|
QA
|
how do write python http server to listen on multiple ports am writing small web server in python using basehttpserver and custom subclass of basehttpserver basehttprequesthandler is it possible to make this listen on more than one port what am doing now class myrequesthandler basehttpserver basehttprequesthandler def doget class threadinghttpserver threadingmixin httpserver pass server threadinghttpserver localhost myrequesthandler server serve forever
|
sure just start two different servers on two different ports in two different threads that each use the same handler here is complete working example that just wrote and tested if you run this code then you will be able to get hello world webpage at both http localhost and http localhost from threading import thread from socketserver import threadingmixin from basehttpserver import httpserver basehttprequesthandler class handler basehttprequesthandler def do get self self send response self send header content type text plain self end headers self wfile write hello world class threadinghttpserver threadingmixin httpserver pass def serve on port port server threadinghttpserver localhost port handler server serve forever thread target serve on port args start serve on port
|
QA
|
how do write python http server to listen on multiple ports am writing small web server in python using basehttpserver and custom subclass of basehttpserver basehttprequesthandler is it possible to make this listen on more than one port what am doing now class myrequesthandler basehttpserver basehttprequesthandler def doget class threadinghttpserver threadingmixin httpserver pass server threadinghttpserver localhost myrequesthandler server serve forever
|
not easily you could have two threadinghttpserver instances write your own serve forever function do not worry it is not complicated function the existing function def serve forever self poll interval handle one request at time until shutdown polls for shutdown every poll interval seconds ignores self timeout if you need to do periodic tasks do them in another thread self serving true self is shut down clear while self serving xxx consider using another file descriptor or connecting to the socket to wake this up instead of polling polling reduces our responsiveness to shutdown request and wastes cpu at all other times select select self poll interval if self handle request noblock self is shut down set so our replacement would be something like def serve forever server server while true select select server server if server in server handle request if server in server handle request
|
QA
|
getting random row through sqlalchemy how do select or some random row from table using sqlalchemy
|
this is very much database specific issue know that postgresql and mysql have the ability to order by random function so you can use this in sqlalchemy from sqlalchemy sql expression import func select select order by func random for postgresql sqlite select order by func rand for mysql select order by dbms random value for oracle next you need to limit the query by the number of records you need for example using limit bear in mind that at least in postgresql selecting random record has severe perfomance issues here is good article about it
|
QA
|
how do you retrieve items from dictionary in the order that they are inserted is it possible to retrieve items from python dictionary in the order that they were inserted
|
you cannot do this with the base dict class it is ordered by hash you could build your own dictionary that is really list of key value pairs or somesuch which would be ordered
|
QA
|
how do you retrieve items from dictionary in the order that they are inserted is it possible to retrieve items from python dictionary in the order that they were inserted
|
the standard python dict is not able to do this there is proposal pep to add an ordered dictionary that keeps track of the order of insertion to the collections module in the standard library it includes links to various implementations of ordered dictionaries see also these two recipes in the python cookbook you might want to stick with the reference implementation in the pep if you want your code to be compatible with the official version if the proposal is eventually accepted edit the pep was accepted and added in python and see the docs
|
QA
|
windows mobile development in python what is the best way to start developing windows mobile professional applications in python is there reasonable sdk including an emulator is it even possible without doing excessive amount of underlaying windows api calls for ui for instance
|
used to write customer apps for windows mobile forget about python even if it is technically possible your app will be big you will have to bundle the whole python runtime with your app your app will use lots of memory python is memory hog relative to your app will be slow you will not find any documentation or discussion groups to help you when you inevitably encounter problems go with or visual studio have decent tools for those sdk for winmo built in debugging on the emulator or device connected through usb the best documentation is for those technologies plus there are active forums discussion groups mailing lists where you can ask for help
|
QA
|
how do you retrieve items from dictionary in the order that they are inserted is it possible to retrieve items from python dictionary in the order that they were inserted
|
the other answers are correct it is not possible but you could write this yourself however in case you are unsure how to actually implement something like this here is complete and working implementation that subclasses dict which have just written and tested note that the order of values passed to the constructor is undefined but will come before values passed later and you could always just not allow ordered dicts to be initialized with values class ordered dict dict def init self args kwargs dict init self args kwargs self order self keys def setitem self key value dict setitem self key value if key in self order self order remove key self order append key def delitem self key dict delitem self key self order remove key def order self return self order def ordered items self return key self key for key in self order od ordered dict od hello world od goodbye cruel world print od order prints hello goodbye del od hello od monty python print od order prints goodbye monty od hello kitty print od order prints goodbye monty hello print od ordered items prints goodbye cruel world monty python hello kitty
|
QA
|
how to retrieve an element from set without removing it suppose the following set how do get value any value out of without doing pop want to leave the item in the set until am sure can remove it something can only be sure of after an asynchronous call to another host quick and dirty elem pop add elem but do you know of better way ideally in constant time
|
use utility function wrote its name is somewhat misleading because it kind of implies it might be random item or something like that def anyitem iterable try return iter iterable next except stopiteration return none
|
QA
|
where do the python unit tests go if you are writing library or an app where do the unit test files go it is nice to separate the test files from the main app code but it is awkward to put them into tests subdirectory inside of the app root directory because it makes it harder to import the modules that you will be testing is there best practice here
|
do not believe there is an established best practice put my tests in another directory outside of the app code then add the main app directory to sys path allowing you to import the modules from anywhere in my test runner script which does some other stuff as well before running all the tests this way never have to remove the tests directory from the main code when release it saving me time and effort if an ever so tiny amount
|
QA
|
where do the python unit tests go if you are writing library or an app where do the unit test files go it is nice to separate the test files from the main app code but it is awkward to put them into tests subdirectory inside of the app root directory because it makes it harder to import the modules that you will be testing is there best practice here
|
common practice is to put the tests directory in the same parent directory as your module package so if your module was called foo py your directory layout would look like parent dir foo py tests of course there is no one way of doing it you could also make tests subdirectory and import the module using absolute import wherever you put your tests would recommend you use nose to run them nose searches through your directories for tests this way you can put tests wherever they make the most sense organizationally
|
QA
|
how do write python http server to listen on multiple ports am writing small web server in python using basehttpserver and custom subclass of basehttpserver basehttprequesthandler is it possible to make this listen on more than one port what am doing now class myrequesthandler basehttpserver basehttprequesthandler def doget class threadinghttpserver threadingmixin httpserver pass server threadinghttpserver localhost myrequesthandler server serve forever
|
would say that threading for something this simple is overkill you are better off using some form of asynchronous programming here is an example using twisted from twisted internet import reactor from twisted web import resource server class myresource resource resource isleaf true def render get self request return gotten site server site myresource reactor listentcp site reactor listentcp site reactor run also thinks it looks lot cleaner to have each port be handled in the same way instead of having the main thread handle one port and an additional thread handle the other arguably that can be fixed in the thread example but then you are using three threads
|
QA
|
python dictionary from an object fields do you know if there is built in function to build dictionary from an arbitrary object would like to do something like this class foo bar hello baz world foo props bar hello baz world note it should not include methods only fields thanks
|
the dir builtin will give you all the object attributes including special methods like str dict and whole bunch of others which you probably do not want but you can do something like class foo object bar hello baz world foo name for name in dir if not name startswith bar baz dict name getattr name for name in dir if not name startswith bar hello baz world so can extend this to only return data attributes and not methods by defining your props function like this import inspect def props obj pr for name in dir obj value getattr obj name if not name startswith and not inspect ismethod value pr name value return pr
|
QA
|
where do the python unit tests go if you are writing library or an app where do the unit test files go it is nice to separate the test files from the main app code but it is awkward to put them into tests subdirectory inside of the app root directory because it makes it harder to import the modules that you will be testing is there best practice here
|
use tests directory and then import the main application modules using relative imports so in myapp tests foo py there might be from import foo to import the myapp foo module
|
QA
|
python dictionary from an object fields do you know if there is built in function to build dictionary from an arbitrary object would like to do something like this class foo bar hello baz world foo props bar hello baz world note it should not include methods only fields thanks
|
have settled with combination of both answers dict key value for key value in dict iteritems if not callable value and not key startswith
|
QA
|
user authentication in pylons authkit am trying to create web application using pylons and the resources on the web point to the pylonsbook page which is not of much help want authentication and authorisation and is there anyway to setup authkit to work easily with pylons tried downloading the simplesitetemplate from the cheeseshop but was not able to run the setup app command it throws up an error file home cnu env lib python site packages sqlalchemy py egg sqlalchemy schema py line in call table metadata tables key attributeerror module object has no attribute tables use pylons rc sqlalchemy authkit
|
this actually got me interested check out this mailing on the pylons list so authkit is being developed and will follow the book and get back on the results
|
QA
|
is it pythonic for function to return multiple values in python you can have function return multiple values here is contrived example def divide quotient remainder return quotient remainder divide this seems very useful but it looks like it can also be abused well function already computes what we need as an intermediate value let us have return that value also when should you draw the line and define different method
|
firstly note that python allows for the following no need for the parenthesis are divide regarding your question there is no hard and fast rule either way for simple and usually contrived examples it may seem that it is always possible for given function to have single purpose resulting in single value however when using python for real world applications you quickly run into many cases where returning multiple values is necessary and results in cleaner code so would say do whatever makes sense and do not try to conform to an artificial convention python supports multiple return values so use it when appropriate
|
QA
|
is it pythonic for function to return multiple values in python you can have function return multiple values here is contrived example def divide quotient remainder return quotient remainder divide this seems very useful but it looks like it can also be abused well function already computes what we need as an intermediate value let us have return that value also when should you draw the line and define different method
|
absolutely for the example you provided tuples are first class citizens in python there is builtin function divmod that does exactly that are divmod invariant div mod there are other examples zip enumerate dict items for in enumerate print index element reverse keys and values in dictionary dict for in adict items or dict zip adict values adict keys by the way parentheses are not necessary most of the time citation from python library reference tuples are constructed by the comma operator not within square brackets with or without enclosing parentheses but an empty tuple must have the enclosing parentheses such as or single item tuple must have trailing comma such as functions should serve single purpose therefore they should return single object in your case this object is tuple consider tuple as an ad hoc compound data structure there are languages where almost every single function returns multiple values list in lisp sometimes it is sufficient to return instead of point named tuples with the introduction of named tuples in python it is preferable in many cases to return named tuples instead of plain tuples import collections point collections namedtuple point point point point for in print
|
QA
|
is it pythonic for function to return multiple values in python you can have function return multiple values here is contrived example def divide quotient remainder return quotient remainder divide this seems very useful but it looks like it can also be abused well function already computes what we need as an intermediate value let us have return that value also when should you draw the line and define different method
|
the example you give is actually python builtin function called divmod so someone at some point in time thought that it was pythonic enough to include in the core functionality to me if it makes the code cleaner it is pythonic compare these two code blocks seconds minutes seconds divmod seconds hours minutes divmod minutes seconds minutes seconds seconds seconds hours minutes minutes minutes
|
QA
|
continuous integration system for python codebase am starting work on hobby project with python codebase and would like to set up some form of continuous integration running battery of test cases each time check in is made and sending nag mails to responsible persons when the tests fail similar to cruisecontrol or teamcity realize could do this with hooks in most vcses but that requires that the tests run on the same machine as the version control server which is not as elegant as would like does anyone have any suggestions for small user friendly open source continuous integration system suitable for python codebase
|
we use both buildbot and hudson for jython development both are useful but have different strengths and weaknesses buildbot configuration is pure python and quite simple once you get the hang of it look at the epydoc generated api docs for the most current info buildbot makes it easier to define non testing tasks and distribute the testers however it really has no concept of individual tests just textual html and summary output so if you want to have multi level browsable test output and so forth you will have to build it yourself or just use hudson hudson has terrific support for drilling down from overall results into test suites and individual tests it also is great for comparing test output between builds but the distributed master slave stuff is comparatively more complicated because you need java environment on the slaves too also hudson is less tolerant of flaky network links between the master and slaves so to get the benefits of both tools we run single instance of hudson which catches the common test failures then we do multi platform regression with buildbot here are our instances jython hudson jython buildbot
|
QA
|
where do the python unit tests go if you are writing library or an app where do the unit test files go it is nice to separate the test files from the main app code but it is awkward to put them into tests subdirectory inside of the app root directory because it makes it harder to import the modules that you will be testing is there best practice here
|
in have generally separated the tests into separate assembly in python so far have tended to either write doctests where the test is in the docstring of function or put them in the if name main block at the bottom of the module
|
QA
|
python cgi on iis how do you set up iis so that you can call python scripts from asp pages ok so found the answer to that question here http support microsoft com kb so on to my next question how do you call cgi script from within classic asp vb code particularly one which is not in the web root directory
|
you could also do it this way
|
QA
|
best way to check if list is empty for example if passed the following how do check to see if is empty
|
len is an operation for python lists strings dicts and sets python internally keeps track of the number of elements in these containers javascript has similar notion of truthy falsy
|
QA
|
how can do line break line continuation in python have long line of code that want to break up among multiple lines what do use and what is the syntax for example adding bunch of strings would and have it like this would
|
the danger in using backslash to end line is that if whitespace is added after the backslash which of course is very hard to see the backslash is no longer doing what you thought it was see python idioms and anti idioms for python or python for more
|
QA
|
comparing runtimes am trying to get some accurate runtime comparisons of php vs python and potentially any other language that have to include timing within script is not my problem but timing within script does not account for everything from the moment the request is made to run the script to output is it actually worth taking such things into account assuming it is worth taking it into account how do do this am using mac so have got access to linux commands and am not afraid to compile create command to help me just do not know how to write such command
|
if your idea is to compare the languages would say anything outside them is not relevant for comparison purposes nonetheless you can use the time command to measure everything and can compare it with the timing within script like this time script php hi real user sys it will give you clock time user time php interpreter and sys time os time if you are thinking web then it gets lot harder because you would be mixing webserver overhead and that is not always easy to compare if say you are using wsgi mod php then you would have to hook probes into the webserving parts of the chain as well
|
QA
|
comparing runtimes am trying to get some accurate runtime comparisons of php vs python and potentially any other language that have to include timing within script is not my problem but timing within script does not account for everything from the moment the request is made to run the script to output is it actually worth taking such things into account assuming it is worth taking it into account how do do this am using mac so have got access to linux commands and am not afraid to compile create command to help me just do not know how to write such command
|
it is worth taking speed into account if you are optimizing code you should generally know why you are optimizing code as in specific task in your existing codebase is taking too long not heard php is slower than python it is not worth taking speed into account if you do not actually plan on switching languages just because one tiny module does something slightly faster does not mean rewriting your app in another language is good idea there are many other factors to choosing language besides speed you benchmark of course run the two codebases multiple times and compare the timing you can use the time command if both scripts are executable from the she will or use respective benchmarking functionality from each language the latter case depends heavily on the actual language naturally
|
QA
|
comparing runtimes am trying to get some accurate runtime comparisons of php vs python and potentially any other language that have to include timing within script is not my problem but timing within script does not account for everything from the moment the request is made to run the script to output is it actually worth taking such things into account assuming it is worth taking it into account how do do this am using mac so have got access to linux commands and am not afraid to compile create command to help me just do not know how to write such command
|
well you can use the time command to help you yourmachine time echo hello world hello world real user sys you yourmachine and this will get around timing outside of the environment as for whether you need to actually time that extra work that entirely depends on what you are doing assume this is for some kind of web application of some sort so it depends on how the framework you use actually works does it cache some kind of compiled or parsed version of the script if so then startup time will be totally irrelevant since the first hit will be the only one that startup time exists in also make sure to run your tests in loop so you can discount the first run and include the cost on the first run in your report if you want have done some tests in java and the first run is always slowest due to the jit doing its job and the same sort of hit may exist in php python and any other languages you try
|
QA
|
what is good way to find relative paths in google app engine so have done the trivial warmup apps with gae now would like to build something with more complex directory structure something along the lines of siteroot models controllers controller controller templates template template etc the controllers will be python modules handling requests they would then need to locate django style templates in associated folders most of the demo apps have seen resolve template paths like this path os path join os path dirname file mypage html the file property resolves to the currently executing script so in my above example if python script were running in controllers controller then the mypage html would resolve to that same directory controllers controller mypage html and would rather cleanly separate my python code and templates the solution have hacked together feels hacky base paths os path split os path dirname file template dir os path join base paths templates so am just snipping off the last element of the path for the currently running script and appending the template directory to the new path the other non gae specific solutions have seen for resolving python paths seem pretty heavyweight such as splitting paths into lists and manipulating accordingly django seems to have an answer for this but would rather stick to the gae api vs creating full django app and modifying it for gae am assuming anything hard coded would be non starter since the apps live on google infinite server farm so what is better way
|
the dirname function returns an absolute path use relative paths see what is the current directory when your controllers are executed with os path abspath os path curdir and build path to the templates relative to that location without the os path abspath part of course this will only work if the current directory is somewhere inside siteroot else you could do something like this template dir os path join os path dirname file os path pardir templates
|
QA
|
xml writing tools for python am currently trying elementtree and it looks fine it escapes html entities and so on and so forth am missing something truly wonderful have not heard of this is similar to what am actually doing import xml etree elementtree as et root et element html head et subelement root head script et subelement head script script set type text javascript script text var love aacute letters body et subelement root body et subelement body text and like the fact that tree et elementtree root tree write foo xhtml more foo xhtml html head script type text javascript var love amp aacute letters script head body and like the fact that gt body html
|
ended up using saxutils escape str to generate valid xml strings and then validating it with eli approach to be sure did not miss any tag from xml sax import saxutils from xml dom minidom import parsestring from xml parsers expat import expaterror xml xml version encoding contents title crawl date in text date url main post main post contents self encoding saxutils escape title saxutils escape time saxutils escape date saxutils escape url saxutils escape contents try minidoc parsestring xml catch expaterror print invalid xml
|
QA
|
where do the python unit tests go if you are writing library or an app where do the unit test files go it is nice to separate the test files from the main app code but it is awkward to put them into tests subdirectory inside of the app root directory because it makes it harder to import the modules that you will be testing is there best practice here
|
for file module py the unit test should normally be called test module py following pythonic naming conventions there are several commonly accepted places to put test module py in the same directory as module py in tests test module py at the same level as the code directory in tests test module py one level under the code directory prefer for its simplicity of finding the tests and importing them whatever build system you are using can easily be configured to run files starting with test actually the default unittest pattern used for test discovery is test py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.