prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
glade or no glade what is the best way to use pygtk have been learning python for while now with some success even managed to create one or two simple programs using pygtk glade the thing is am not sure if the best way to use gtk with python is by building the interfaces using glade was wondering if the more experienced ones among us remember am just beginner could point out the benefits and caveats of using glade as opposed to creating everything in the code itself assuming that learning the correct gtk bindings would not exactly be problem
|
would say that it depends if you find that using glade you can build the apps you want or need to make than that is absolutely fine if however you actually want to learn how gtk works or you have some non standard ui requirements you will have to dig into gtk internals which are not that complicated personally am usually about minutes into rich client when need some feature or customization that is simply impossible through designer such as glade or stetic perhaps it is just me nevertheless it is still useful for me to bootstrap window design using graphical tool my recommendation if making rich clients using gtk is going to be significant part of your job hobby then learn gtk as well since you will need to write that code someday personally find stetic to be superior to glade for design work if little bit more unstable
|
QA
|
python no module named core exceptions am trying to get google appengine to work on my debian box and am getting the following error when try to access my page type exceptions importerror no module named core exceptions the same app works fine for me when run it on my other ubuntu box so know it is not problem with the app itself however need to get it working on this debian box it originally had python but after appengine complained about it installed the python and python dev packages to no avail saw on this google group post that it may be due to the version of appengine and just to reinstall it but that did not work any ideas edit also tried uninstalling python and then reinstalling which also did not work edit turns out when made appengine into cvs project it did not add the core directory into my project so when checked it out there literally was no module named core exceptions re downloading that folder resolved the problem
|
core exceptions is part of django what version of django do you have installed the appengine comes with the appropriate version for whatever release you have downloaded in the lib django directory it can be installed by going to that directory and running python setup py install
|
QA
|
python descriptor protocol analog in other languages is there something like the python descriptor protocol implemented in other languages it seems like nice way to increase modularity encapsulation without bloating your containing class implementation but have never heard of similar thing in any other languages is it likely absent from other languages because of the lookup overhead
|
ruby and both easily let you create accessors by specifying getter setter methods for an attribute much like in python however this is not designed to naturally let you write the code for these methods in another class the way that python allows in practice am not sure how much this matters since every time have seen an attribute defined through the descriptor protocol its been implemented in the same class edit darn my dyslexia by which mean careless reading for some reason have always read descriptor as decorator and vice versa even when am the one typing both of them will leave my post intact since it has valid information albeit information which has absolutely nothing to do with the question the term decorator itself is actually the name of design pattern described in the famous design patterns book the wikipedia article contains many examples in different programming languages of decorator usage http en wikipedia org wiki decorator pattern however the decorators in that article object oriented they have classes implementing predefined interface which let us another existing class behave differently somehow etc python decorators act in functional way by replacing function at runtime with another function allowing you to effectively modify replace that function insert code etc this is known in the java world as aspect oriented programming and the aspectj java compiler let us you do these kinds of things and compile your aspectj code which is superset of java into java bytecode am not familiar enough with or ruby to know what their version of decorators would be
|
QA
|
calling python from program for distribution would like to call python script files from my program am not sure that the people will distribute to will have python installed basically am looking for lib file that can use that has an apache like distribution license
|
boost has python interface library which could help you boost python
|
QA
|
how do turn python program into an egg file how do turn python program into an egg file
|
setuptools is the software that creates egg files it is an extension of the distutils package in the standard library the process involves creating setup py file then python setup py bdist egg creates an egg package
|
QA
|
how do turn python program into an egg file how do turn python program into an egg file
|
also if you need to get an egg package off single py file app check this link easyinstall packaging others projects as eggs
|
QA
|
calling python from program for distribution would like to call python script files from my program am not sure that the people will distribute to will have python installed basically am looking for lib file that can use that has an apache like distribution license
|
embeding the python interpreter inside your app will let you run python programs using your application run python scripts it will also make it easier possible for those scripts to call functions in your application if this is what you want then the boost library mentioned previously may be what you want to make it easier to create the link in the past have used swig to generate python interfaces to code it was not clear from your question whether you wanted the python scripts to call your program or whether you just wanted the to call python many of the python functions use modules which are not built into the python interpreter if your python scripts call these functions then you will either need to have your users install python or include the python runtime files with your application it will depend on what modules you import in you python scripts
|
QA
|
calling python from program for distribution would like to call python script files from my program am not sure that the people will distribute to will have python installed basically am looking for lib file that can use that has an apache like distribution license
|
boost is probably the best choice however if you are wanting something that is more standalone and if this is for use with windows which seems feasible given that they are the people least likely to have python installed then you can use py exe to create dll with entry points suitable for com objects you can then interface with the library via com obviously this is not at all useful as cross platform solution
|
QA
|
how does one decrypt pdf with an owner password but no user password although the pdf specification is available from adobe it is not exactly the simplest document to read through pdf allows documents to be encrypted so that either user password and or an owner password is required to do various things with the document display print etc common use is to lock pdf so that end users can read it without entering any password but password is required to do anything else am trying to parse pdfs that are locked in this way to get the same privileges as you would get opening them in any reader using an empty string as the user password does not work but it seems section of the spec that there has to be user password to create the hash for the admin password what would like is either an explanation of how to do this or any code that can read ideally python or but anything readable will do that does this so that can understand what am meant to be doing standalone code rather than reading through the gsview source would be best
|
plugin for gsview for viewing encrypted pdfs is here if this works for you you may be able to look at the source
|
QA
|
how to merge two python dictionaries in single expression have two python dictionaries and want to write single expression that returns these two dictionaries merged the update method would be what need if it returned its result instead of modifying dict in place update print none how can get that final merged dict in not to be extra clear the last one wins conflict handling of dict update is what am looking for as well
|
this probably will not be popular answer but you almost certainly do not want to do this if you want copy that is merge then use copy or deepcopy depending on what you want and then update the two lines of code are much more readable more pythonic than the single line creation with items items explicit is better than implicit in addition when you use items pre python you are creating new list that contains the items from the dict if your dictionaries are large then that is quite lot of overhead two large lists that will be thrown away as soon as the merged dict is created update can work more efficiently because it can run through the second dict item by item in terms of time timeit timer dict dict zip range range ny dict zip range range timeit timeit timer temp copy ntemp update dict zip range range ny dict zip range range timeit timeit timer dict items items dict zip range range ny dict zip range range timeit am going to the tiny slowdown between the first two is worth it for the readability in addition keyword arguments for dictionary creation was only added in python whereas copy and update will work in older versions
|
QA
|
can parallel traversals be done in matlab just as in python using the zip function python allows for loops to traverse multiple sequences in parallel for in zip list list does matlab have an equivalent syntax if not what is the best way to iterate over two parallel arrays at the same time using matlab
|
if am not mistaken the zip function you use in python creates pair of the items found in list and list basically it still is for loop with the addition that it will retrieve the data from the two seperate lists for you instead that you have to do it yourself so maybe your best option is to use standard for loop like this for length end or whatever you have to do with the data if you really are talking about parallel computing then you should take look at the parallel computing toolbox for matlab and more specifically at parfor
|
QA
|
java python besides the dynamic nature of python and the syntax what are some of the major features of the python language that java does not have and vice versa
|
think this pair of articles by philip eby does great job discussing the differences between the two languages mostly about philosophy mentality rather than specific language features python is not java java is not python either
|
QA
|
java python besides the dynamic nature of python and the syntax what are some of the major features of the python language that java does not have and vice versa
|
one key difference in python is significant whitespace this puts lot of people off me too for long time but once you get going it seems natural and makes much more sense than everywhere from personal perspective python has the following benefits over java no checked exceptions optional arguments much less boilerplate and less verbose generally other than those this page on the python wiki is good place to look with lots of links to interesting articles
|
QA
|
java python besides the dynamic nature of python and the syntax what are some of the major features of the python language that java does not have and vice versa
|
with jython you can have both it is only at python but still very useful if you need an embedded interpreter that has access to the java runtime
|
QA
|
open source alternative to matlab fmincon function is there an open source alternative to matlab fmincon function for constrained linear optimization am rewriting matlab program to use python numpy scipy and this is the only function have not found an equivalent to numpy based solution would be ideal but any language will do
|
there is program called scilab that is matlab clone have not used it at all but it is open source and might have the function you are looking for
|
QA
|
open source alternative to matlab fmincon function is there an open source alternative to matlab fmincon function for constrained linear optimization am rewriting matlab program to use python numpy scipy and this is the only function have not found an equivalent to numpy based solution would be ideal but any language will do
|
gnu octave is another matlab clone that might have what you need
|
QA
|
java python besides the dynamic nature of python and the syntax what are some of the major features of the python language that java does not have and vice versa
|
list comprehensions often find myself filtering mapping lists and being able to say line replace spam eggs for line in open somefile txt if line startswith nee is really nice functions are first class objects they can be passed as parameters to other functions defined inside other function and have lexical scope this makes it really easy to say things like people sort key lambda age and thus sort bunch of people on their age without having to define custom comparator class or something equally verbose everything is an object java has basic types which are not objects which is why many classes in the standard library define different versions of functions for boolean byte char double float int long object short array sort is good example autoboxing helps although it makes things awkward when something turns out to be null properties python let us you create classes with read only fields lazily generated fields as well as fields which are checked upon assignment to make sure they are never or null or whatever you want to guard against etc default and keyword arguments in java if you want constructor that can take up to optional arguments you must define different versions of that constructor and there is no way at all to say student name eli age functions can only return thing in python you have tuple assignment so you can say spam eggs nee but in java you would need to either resort to mutable out parameters or have custom class with fields and then have two additional lines of code to extract those fields built in syntax for lists and dictionaries operator overloading generally better designed libraries for example to parse an xml document in java you say document doc documentbuilderfactory newinstance newdocumentbuilder parse test xml and in python you say doc parse test xml anyway could go on and on with further examples but python is just overall much more flexible and expressive language it is also dynamically typed which really like but which comes with some disadvantages java has much better performance than python and has way better tool support sometimes those things matter lot and java is the better language than python for task continue to use java for some new projects despite liking python lot more but as language think python is superior for most things find myself needing to accomplish
|
QA
|
open source alternative to matlab fmincon function is there an open source alternative to matlab fmincon function for constrained linear optimization am rewriting matlab program to use python numpy scipy and this is the only function have not found an equivalent to numpy based solution would be ideal but any language will do
|
do not know if it is in there but there is python distribution called enthought that might have what you are looking for it was designed specifically for data analysis has over additional libraries
|
QA
|
what python way would you suggest to check whois database records am trying to get webservice up and running that actually requires to check whois databases what am doing right now is ugly and would like to avoid it as much as can call gwhois command and parse its output ugly did some search to try to find pythonic way to do this task generally got quite much nothing this old discussion list link has way to check if domain exist quite not what was looking for but still it was best anwser google gave me everything else is just bunch of unanwsered questions any of you have succeeded to get some method up and running would very much appreciate some tips or should just do it the opensource way sit down and code something by myself
|
another way to do it is to use urllib module to parse some other page whois service many sites like that exist but that seems like even more of hack that what you do now and would give you dependency on whatever whois site you chose which is bad hate to say it but unless you want to re implement whois in your program which would be re inventing the wheel running whois on the os and parsing the output ie what you are doing now seems like the right way to do it
|
QA
|
what python way would you suggest to check whois database records am trying to get webservice up and running that actually requires to check whois databases what am doing right now is ugly and would like to avoid it as much as can call gwhois command and parse its output ugly did some search to try to find pythonic way to do this task generally got quite much nothing this old discussion list link has way to check if domain exist quite not what was looking for but still it was best anwser google gave me everything else is just bunch of unanwsered questions any of you have succeeded to get some method up and running would very much appreciate some tips or should just do it the opensource way sit down and code something by myself
|
parsing another webpage woulnd be as bad assuming their html woulnd be very bad but it would actually tie me to them if they are down am down actually found some old project on sourceforge rwhois py what scares me bit is that their last update is from but it might seem as good place to start reimplementation of what do right now well felt obligued to post the link to this project anyway just for further reference
|
QA
|
django templates and variable attributes am using google app engine and django templates have table that want to display the objects look something like object result items item item users name username item item the django template is table tr align center th user th for item in result items th item th endfor tr for user in result users tr align center td user name td for item in result items td user item td endfor tr endfor table now the django documention states that when it sees in variables it tries several things to get the data one of which is dictionary lookup which is exactly what want but does not seem to happen
|
found nicer better solution for getting variables inside its not the nicest way but it works you install custom filter into django which gets the key of your dict as parameter to make it work in google app engine you need to add file to your main directory called mine django hack py which contains this little piece of code from google appengine ext import webapp register webapp template create template register def hash key if key in return key else return none register filter hash now that we have this file all we need to do is tell the app engine to use it we do that by adding this little line to your main file webapp template register template library django hack and in your template view add this template instead of the usual code user hash item and its should work perfectly
|
QA
|
how do get the path and name of the file that is currently executing have scripts calling other script files but need to get the filepath of the file that is currently running within the process for example let us say have three files using execfile script py calls script py in turn script py calls script py how can get the file name and path of script py from code within script py without having to pass that information as arguments from script py executing os getcwd returns the original starting script filepath not the current file
|
it is not entirely clear what you mean by the filepath of the file that is currently running within the process sys argv usually contains the location of the script that was invoked by the python interpreter check the sys documentation for more details as tim and pat notz have pointed out the file attribute provides access to the file from which the module was loaded if it was loaded from file
|
QA
|
how do get the path and name of the file that is currently executing have scripts calling other script files but need to get the filepath of the file that is currently running within the process for example let us say have three files using execfile script py calls script py in turn script py calls script py how can get the file name and path of script py from code within script py without having to pass that information as arguments from script py executing os getcwd returns the original starting script filepath not the current file
|
think it is just file sounds like you may also want to checkout the inspect module
|
QA
|
how do implement pre commit hook script in svn that calls dos unix to validate checked in file was wondering if anyone here had some experience writing this type of script and if they could give me some pointers would like to modify this script to validate that the check in file does not have carriage return in the eol formatting the eol format is cr lf in windows and lf in unix when user checks in code with the windows format it does not compile in unix anymore know this can be done on the client side but need to have this validation done on the server side to achieve this need to do the following make sure the file check is not binary do not know how to do this with svnlook should check the mime type of the file the red book does not indicate this clearly or must have not seen it would like to run the dos unix command to validate that the file has the correct eol format would compare the output of the dos unix command against the original file if there is different between both give an error message to the client and cancel the check in would like your comments feedback on this approach
|
think you can avoid commit hook script in this case by using the svn eol style property as described in the svnbook end of line character sequences subversion properties this way svn can worry about your line endings for you good luck
|
QA
|
how do get the path and name of the file that is currently executing have scripts calling other script files but need to get the filepath of the file that is currently running within the process for example let us say have three files using execfile script py calls script py in turn script py calls script py how can get the file name and path of script py from code within script py without having to pass that information as arguments from script py executing os getcwd returns the original starting script filepath not the current file
|
the file attribute works for both the file containing the main execution code as well as imported modules see https web archive org web http pyref infogami com file
|
QA
|
django sessions am looking at sessions in django and by default they are stored in the database what are the benefits of filesystem and cache sessions and when should use them
|
the filesystem backend is only worth looking at if you are not going to use database for any other part of your system if you are using database then the filesystem backend has nothing to recommend it the memcache backend is much quicker than the database backend but you run the risk of session being purged and some of your session data being lost if you are really really high traffic website and code carefully so you can cope with losing session then use memcache if you are not using database use the file system cache but the default database backend is the best safest and simplest option in almost all cases
|
QA
|
how do get the path and name of the file that is currently executing have scripts calling other script files but need to get the filepath of the file that is currently running within the process for example let us say have three files using execfile script py calls script py in turn script py calls script py how can get the file name and path of script py from code within script py without having to pass that information as arguments from script py executing os getcwd returns the original starting script filepath not the current file
|
py execfile py py import inspect os print inspect getfile inspect currentframe script filename usually with path print os path dirname os path abspath inspect getfile inspect currentframe script directory
|
QA
|
how do you create weak reference to an object in python how do you create weak reference to an object in python
|
import weakref class object pass object are weakref ref if the reference is still active will be otherwise none do something with see the wearkref module docs for more details you can also use weakref proxy to create an object that proxies will throw referenceerror if used when the referent is no longer referenced
|
QA
|
how do get the path and name of the file that is currently executing have scripts calling other script files but need to get the filepath of the file that is currently running within the process for example let us say have three files using execfile script py calls script py in turn script py calls script py how can get the file name and path of script py from code within script py without having to pass that information as arguments from script py executing os getcwd returns the original starting script filepath not the current file
|
you can use inspect stack import inspect os inspect stack frame object at ac ac python test getcurrentprogram py module print inspect stack os path abspath inspect stack python test getcurrentprogram py
|
QA
|
what is the simplest way to find the difference between times in python have time values which have the type datetime time want to find their difference the obvious thing to do is but this does not work it works for objects of type datetime datetime but not for datetime time so what is the best way to do this
|
it seems that this is not supported since there would not be good way to deal with overflows in datetime time know this is not an answer directly but maybe someone with more python experience than me can take this little further for more info see this http bugs python org issue
|
QA
|
what is the simplest way to find the difference between times in python have time values which have the type datetime time want to find their difference the obvious thing to do is but this does not work it works for objects of type datetime datetime but not for datetime time so what is the best way to do this
|
you could transform both into timedelta objects and subtract these from each other which will take care to of the carry overs for example import datetime as dt dt time dt time dt dt timedelta hours hour minutes minute seconds second microseconds microsecond dt dt timedelta hours hour minutes minute seconds second microseconds microsecond print dt dt print dt dt day print abs dt dt negative timedelta objects in python get negative day field with the other fields positive you could check beforehand comparison works on both time objects and timedelta objects dt dt true true
|
QA
|
what is the simplest way to find the difference between times in python have time values which have the type datetime time want to find their difference the obvious thing to do is but this does not work it works for objects of type datetime datetime but not for datetime time so what is the best way to do this
|
also little silly but you could try picking an arbitrary day and embedding each time in it using datetime datetime combine then subtracting import datetime datetime time datetime time dummydate datetime date datetime datetime combine dummydate datetime datetime combine dummydate datetime timedelta
|
QA
|
best way to extract data from filemaker pro database in script my job would be easier or at least less tedious if could come up with an automated way preferably in python script to extract useful information from filemaker pro database am working on linux machine and the filemaker database is on the same lan running on an os machine can log into the webby interface from my machine am quite handy with sql and if somebody could point me to some filemaker plug in that could give me sql access to the data within filemaker would be pleased as punch everything have found only goes the other way having filemaker get data from sql sources not useful it is not my first choice but would use perl instead of python if there was perl solution at hand note xml xslt services as suggested by some folks are only available on fm server not fm pro otherwise that would probably be the best solution odbc is turning out to be extremely difficult to even get working there is absolutely zero feedback from fm when you set it up so you have to dig through var log system log and parse obscure error messages conclusion got it working by running python script locally on the machine that queries the fm database through the odbc connections the script is actually tcpserver that accepts socket connections from other systems on the lan runs the queries and returns the data through the socket connection had to do this to bypass the fact that fm pro only accepts odbc connections locally fm server is required for external connections
|
if your leaning is to python you may be interested in checking out the python wrapper for filemaker it provides two way access to the filemaker data via filemaker built in xml services you can find some quite thorough information on this at http code google com pyfilemaker
|
QA
|
can parallel traversals be done in matlab just as in python using the zip function python allows for loops to traverse multiple sequences in parallel for in zip list list does matlab have an equivalent syntax if not what is the best way to iterate over two parallel arrays at the same time using matlab
|
tested only in octave no matlab license variations of arrayfun exist check the documentation usr bin octave qf function result dostuff my ten my one result my ten my one endfunction tens ones arrayfun dostuff tens ones yields
|
QA
|
what is tuple useful for am learning python for class now and we just covered tuples as one of the data types read the wikipedia page on it but could not figure out where such data type would be useful in practice can have some examples perhaps in python where an immutable set of numbers would be needed how is this different from list
|
in addition to the places where they are syntactically required like the string operation and for multiple return values use tuples as form of lightweight classes for example suppose you have an object that passes out an opaque cookie to caller from one method which is then passed into another method tuple is good way to pack multiple values into that cookie without having to define separate class to contain them try to be judicious about this particular use though if the cookies are used liberally throughout the code it is better to create class because it helps document their use if they are only used in one place one pair of methods then might use tuple in any case because it is python you can start with tuple and then change it to an instance of custom class without having to change any code in the caller
|
QA
|
how to write download progress indicator in python am writing little application to download files over http as for example described here also want to include little download progress indicator showing the percentage of the download progress here is what came up with sys stdout write rem file urllib urlretrieve rem file loc file reporthook dlprogress def dlprogress count blocksize totalsize percent int count blocksize totalsize sys stdout write percent sys stdout write sys stdout flush output myfilename any other ideas or recommendations to do this one thing that is somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage is there way to prevent this is there way to hide the cursor edit here better alternative using global variable for the filename in dlprogress and the code global rem file global variable to be used in dlprogress urllib urlretrieve rem file loc file reporthook dlprogress def dlprogress count blocksize totalsize percent int count blocksize totalsize sys stdout write rem file percent sys stdout flush output myfilename and the cursor shows up at the end of the line much better
|
if you use the curses package you have much greater control of the console it also comes at higher cost in code complexity and is probably unnecessary unless you are developing large console based app for simple solution you can always put the spinning wheel at the end of the status messge the sequence of characters which actually looks nice under blinking cursor
|
QA
|
how to write download progress indicator in python am writing little application to download files over http as for example described here also want to include little download progress indicator showing the percentage of the download progress here is what came up with sys stdout write rem file urllib urlretrieve rem file loc file reporthook dlprogress def dlprogress count blocksize totalsize percent int count blocksize totalsize sys stdout write percent sys stdout write sys stdout flush output myfilename any other ideas or recommendations to do this one thing that is somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage is there way to prevent this is there way to hide the cursor edit here better alternative using global variable for the filename in dlprogress and the code global rem file global variable to be used in dlprogress urllib urlretrieve rem file loc file reporthook dlprogress def dlprogress count blocksize totalsize percent int count blocksize totalsize sys stdout write rem file percent sys stdout flush output myfilename and the cursor shows up at the end of the line much better
|
you might also try sys stdout write percent sys stdout flush using single carriage return at the beginning of your string rather than several backspaces your cursor will still blink but it will blink after the percent sign rather than under the first digit and with one control character instead of three you may get less flicker
|
QA
|
how to write download progress indicator in python am writing little application to download files over http as for example described here also want to include little download progress indicator showing the percentage of the download progress here is what came up with sys stdout write rem file urllib urlretrieve rem file loc file reporthook dlprogress def dlprogress count blocksize totalsize percent int count blocksize totalsize sys stdout write percent sys stdout write sys stdout flush output myfilename any other ideas or recommendations to do this one thing that is somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage is there way to prevent this is there way to hide the cursor edit here better alternative using global variable for the filename in dlprogress and the code global rem file global variable to be used in dlprogress urllib urlretrieve rem file loc file reporthook dlprogress def dlprogress count blocksize totalsize percent int count blocksize totalsize sys stdout write rem file percent sys stdout flush output myfilename and the cursor shows up at the end of the line much better
|
there is text progress bar library for python at http pypi python org pypi progressbar that you might find useful this library provides text mode progressbar this is tipically used to display the progress of long running operation providing visual clue that processing is underway the progressbar class manages the progress and the format of the line is given by number of widgets widget is an object that may display diferently depending on the state of the progress there are three types of widget string which always shows itself progressbarwidget which may return diferent value every time it is update method is called and progressbarwidgethfill which is like progressbarwidget except it expands to fill the remaining width of the line the progressbar module is very easy to use yet very powerful and automatically supports features like auto resizing when available
|
QA
|
how can retrieve the page title of webpage using python how can retrieve the page title of webpage title html tag using python
|
will always use lxml for such tasks you could use beautifulsoup as well import lxml html lxml html parse url print find title text
|
QA
|
how can retrieve the page title of webpage using python how can retrieve the page title of webpage title html tag using python
|
this is probably overkill for such simple task but if you plan to do more than that then it is saner to start from these tools mechanize beautifulsoup because they are much easier to use than the alternatives urllib to get content and regexen or some other parser to parse html links beautifulsoup mechanize usr bin env python coding utf from beautifulsoup import beautifulsoup from mechanize import browser this retrieves the webpage content br browser res br open https www google com data res get data this parses the content soup beautifulsoup data title soup find title this outputs the content print title rendercontents
|
QA
|
how can retrieve the page title of webpage using python how can retrieve the page title of webpage title html tag using python
|
the mechanize browser object has title method so the code from this post can be rewritten as from mechanize import browser br browser br open http www google com print br title
|
QA
|
passing on named variable arguments in python say have the following methods def methoda arg kwargs pass def methodb arg args kwargs pass in methoda wish to call methodb passing on the kwargs however it seems that if define methoda as follows the second argument will be passed on as positional rather than named variable arguments def methoda arg kwargs methodb argvalue kwargs how do make sure that the kwargs in methoda gets passed as kwargs to methodb
|
some experimentation and figured this one out def methoda arg kwargs methodb argvalue kwargs seems obvious now
|
QA
|
passing on named variable arguments in python say have the following methods def methoda arg kwargs pass def methodb arg args kwargs pass in methoda wish to call methodb passing on the kwargs however it seems that if define methoda as follows the second argument will be passed on as positional rather than named variable arguments def methoda arg kwargs methodb argvalue kwargs how do make sure that the kwargs in methoda gets passed as kwargs to methodb
|
put the asterisks before the kwargs variable this makes python pass the variable which is assumed to be dictionary as keyword arguments methodb argvalue kwargs
|
QA
|
improving python readability have been really enjoying python programming lately come from background of strong love for based coding where everything is perhaps more complicated than it should be but puts hair on your chest at least so switching from to python for more complex things that do not require tons of speed has been more of boon than bane in writing projects however coming from this land of brackets and parentheses and structs as far as the naked eye can see come across small problem find python difficult to read for example the following block of text is hard for me to decipher unless stare at it which dislike doing if foo bar baz while bar not biz bar am going to find you biz swear on my life did not warn you biz my father is avenged the problem occurs at the end of that if block all the tabbing and then suddenly returning to jarring block feels almost disturbing as solution have started coding my python like this if foo bar baz while bar not biz bar am going to find you biz swear on my life while if did not warn you biz my father is avenged and this for some odd reason makes me more able to read my own code but am curious has anyone else with my strange problem found easier ways to make their tabbed out code more readable would love to find out if there is better way to do this before this becomes huge habit for me
|
you could try increasing the indent size but in general would just say relax it will come with time do not think trying to make python look like is very good idea
|
QA
|
django sessions am looking at sessions in django and by default they are stored in the database what are the benefits of filesystem and cache sessions and when should use them
|
am no django expert so this answer is about session stores generally downvote if am wrong performance and scalability choice of session store has an effect on performance and scalability this should only be big problem if you have very popular application both database and filesystem session stores are usually backed by disks so you can have lot of sessions cheaply because disks are cheap but requests will often have to wait for the data to be read because disks are slow memcached sessions use ram so will cost more to support the same number of concurrent sessions because ram is expensive but may be faster because ram is fast filesystem sessions are tied to the box where your application is running so you cannot load balance between multiple application servers if your site gets huge database and memcached sessions let you have multiple application servers talking to shared session store simplicity choice of session store will also impact how easy it is to deploy your site changing away from the default will cost some complexity memcached and rdbmss both have their own complexities but your application is probably going to be using an rdbms anyway unless you have very popular application simplicity should be the larger concern bonus another approach is to store session data in cookies all of it not just an id this has the advantage that the session store automatically scales with the number of users but it has disadvantages too you or your framework need to be careful to stop users forging session data you also need to keep each session small because the whole thing will be sent with every request
|
QA
|
java python besides the dynamic nature of python and the syntax what are some of the major features of the python language that java does not have and vice versa
|
apart from what eli courtwright said find iterators in python more concise you can use for in something and it works with pretty much everything yeah java has gotten better since but for example you can iterate through string in python with this same construct introspection in python you can get at runtime information about an object or module about its symbols methods or even its docstrings you can also instantiate them dynamically java has some of this but usually in java it takes half page of code to get an instance of class whereas in python it is about lines and as far as know the docstrings thing is not available in java
|
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
|
import os os path abspath mydir myfile txt
|
QA
|
improving python readability have been really enjoying python programming lately come from background of strong love for based coding where everything is perhaps more complicated than it should be but puts hair on your chest at least so switching from to python for more complex things that do not require tons of speed has been more of boon than bane in writing projects however coming from this land of brackets and parentheses and structs as far as the naked eye can see come across small problem find python difficult to read for example the following block of text is hard for me to decipher unless stare at it which dislike doing if foo bar baz while bar not biz bar am going to find you biz swear on my life did not warn you biz my father is avenged the problem occurs at the end of that if block all the tabbing and then suddenly returning to jarring block feels almost disturbing as solution have started coding my python like this if foo bar baz while bar not biz bar am going to find you biz swear on my life while if did not warn you biz my father is avenged and this for some odd reason makes me more able to read my own code but am curious has anyone else with my strange problem found easier ways to make their tabbed out code more readable would love to find out if there is better way to do this before this becomes huge habit for me
|
perhaps the best thing would be to turn on show whitespace in your editor then you would have visual indication of how far in each line is tabbed usually bunch of dots and it will be more apparent when that changes
|
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
|
import os os path abspath mydir myfile txt example cwd mydir myfile txt
|
QA
|
how can retrieve the page title of webpage using python how can retrieve the page title of webpage title html tag using python
|
here is simplified version of vinko vrsalovic answer import urllib from beautifulsoup import beautifulsoup soup beautifulsoup urllib urlopen https www google com print soup title string note soup title finds the first title element anywhere in the html document title string assumes it has only one child node and that child node is string for beautifulsoup use different import from bs import beautifulsoup
|
QA
|
improving python readability have been really enjoying python programming lately come from background of strong love for based coding where everything is perhaps more complicated than it should be but puts hair on your chest at least so switching from to python for more complex things that do not require tons of speed has been more of boon than bane in writing projects however coming from this land of brackets and parentheses and structs as far as the naked eye can see come across small problem find python difficult to read for example the following block of text is hard for me to decipher unless stare at it which dislike doing if foo bar baz while bar not biz bar am going to find you biz swear on my life did not warn you biz my father is avenged the problem occurs at the end of that if block all the tabbing and then suddenly returning to jarring block feels almost disturbing as solution have started coding my python like this if foo bar baz while bar not biz bar am going to find you biz swear on my life while if did not warn you biz my father is avenged and this for some odd reason makes me more able to read my own code but am curious has anyone else with my strange problem found easier ways to make their tabbed out code more readable would love to find out if there is better way to do this before this becomes huge habit for me
|
like to put blank lines around blocks to make control flow more obvious for example if foo bar baz while bar not biz bar am going to find you biz swear on my life did not warn you biz my father is avenged
|
QA
|
improving python readability have been really enjoying python programming lately come from background of strong love for based coding where everything is perhaps more complicated than it should be but puts hair on your chest at least so switching from to python for more complex things that do not require tons of speed has been more of boon than bane in writing projects however coming from this land of brackets and parentheses and structs as far as the naked eye can see come across small problem find python difficult to read for example the following block of text is hard for me to decipher unless stare at it which dislike doing if foo bar baz while bar not biz bar am going to find you biz swear on my life did not warn you biz my father is avenged the problem occurs at the end of that if block all the tabbing and then suddenly returning to jarring block feels almost disturbing as solution have started coding my python like this if foo bar baz while bar not biz bar am going to find you biz swear on my life while if did not warn you biz my father is avenged and this for some odd reason makes me more able to read my own code but am curious has anyone else with my strange problem found easier ways to make their tabbed out code more readable would love to find out if there is better way to do this before this becomes huge habit for me
|
rather than focusing on making your existing structures more readable you should focus on making more logical structures make smaller blocks try not to nest blocks excessively make smaller functions and try to think through your code flow more if you come to point where you cannot quickly determine the structure of your code you should probably consider refactoring and adding some comments code flow should always be immediately apparent the more you have to think about it the less maintainable your code becomes
|
QA
|
cross platform space remaining on volume using python need way to determine the space remaining on disk volume using python on linux windows and os am currently parsing the output of the various system calls df dir to accomplish this is there better way
|
the os statvfs function is better way to get that information for unix like platforms including os the python documentation says availability unix but it is worth checking whether it works on windows too in your build of python ie the docs might not be up to date otherwise you can use the pywin library to directly call the getdiskfreespaceex function
|
QA
|
why are sql aggregate functions so much slower than python and java or poor man olap need real dba opinion postgres takes ms to execute this query on my macbook pro while java and python perform the same calculation in under ms rows select count id average average average average from tuples is this normal behaviour when using sql database the schema the table holds responses to survey create table tuples id integer primary key integer integer integer integer copy tuples from responses csv delimiter as wrote some tests in java and python for context and they crush sql except for pure python java threads ms java ms python numpy ms python ms even sqlite is competitive with postgres despite it assumping all columns are strings for contrast even using just switching to numeric columns instead of integers in postgres results in slowdown tunings have tried without success include blindly following some web advice increased the shared memory available to postgres to mb increased the working memory to mb disabled connection and statement logging used stored procedure via create function language sql so my question is is my experience here normal and this is what can expect when using sql database can understand that acid must come with costs but this is kind of crazy in my opinion am not asking for realtime game speed but since java can process millions of doubles in under ms feel bit jealous is there better way to do simple olap on the cheap both in terms of money and server complexity have looked into mondrian and pig hadoop but not super excited about maintaining yet another server application and not sure if they would even help no the python code and java code do all the work in house so to speak just generate arrays with random values each then take the average do not include the generation in the timings only the averaging step the java threads timing uses threads one per array average overkill but it is definitely the fastest the sqlite timing is driven by the python program and is running from disk not memory realize postgres is doing much more behind the scenes but most of that work does not matter to me since this is read only data the postgres query does not change timing on subsequent runs have rerun the python tests to include spooling it off the disk the timing slows down considerably to nearly secs but am guessing that python file handling code is pretty much in though maybe not the csv lib so this indicates to me that postgres is not streaming from the disk either or that you are correct and should bow down before whoever wrote their storage layer
|
do not think that your results are all that surprising if anything it is that postgres is so fast does the postgres query run faster second time once it has had chance to cache the data to be little fairer your test for java and python should cover the cost of acquiring the data in the first place ideally loading it off disk if this performance level is problem for your application in practice but you need rdbms for other reasons then you could look at memcached you would then have faster cached access to raw data and could do the calculations in code
|
QA
|
cross platform space remaining on volume using python need way to determine the space remaining on disk volume using python on linux windows and os am currently parsing the output of the various system calls df dir to accomplish this is there better way
|
do not know of any cross platform way to achieve this but maybe good workaround for you would be to write wrapper class that checks the operating system and uses the best method for each for windows there is the getdiskfreespaceex method in the win extensions
|
QA
|
why are sql aggregate functions so much slower than python and java or poor man olap need real dba opinion postgres takes ms to execute this query on my macbook pro while java and python perform the same calculation in under ms rows select count id average average average average from tuples is this normal behaviour when using sql database the schema the table holds responses to survey create table tuples id integer primary key integer integer integer integer copy tuples from responses csv delimiter as wrote some tests in java and python for context and they crush sql except for pure python java threads ms java ms python numpy ms python ms even sqlite is competitive with postgres despite it assumping all columns are strings for contrast even using just switching to numeric columns instead of integers in postgres results in slowdown tunings have tried without success include blindly following some web advice increased the shared memory available to postgres to mb increased the working memory to mb disabled connection and statement logging used stored procedure via create function language sql so my question is is my experience here normal and this is what can expect when using sql database can understand that acid must come with costs but this is kind of crazy in my opinion am not asking for realtime game speed but since java can process millions of doubles in under ms feel bit jealous is there better way to do simple olap on the cheap both in terms of money and server complexity have looked into mondrian and pig hadoop but not super excited about maintaining yet another server application and not sure if they would even help no the python code and java code do all the work in house so to speak just generate arrays with random values each then take the average do not include the generation in the timings only the averaging step the java threads timing uses threads one per array average overkill but it is definitely the fastest the sqlite timing is driven by the python program and is running from disk not memory realize postgres is doing much more behind the scenes but most of that work does not matter to me since this is read only data the postgres query does not change timing on subsequent runs have rerun the python tests to include spooling it off the disk the timing slows down considerably to nearly secs but am guessing that python file handling code is pretty much in though maybe not the csv lib so this indicates to me that postgres is not streaming from the disk either or that you are correct and should bow down before whoever wrote their storage layer
|
would say your test scheme is not really useful to fulfill the db query the db server goes through several steps parse the sql work up query plan decide on which indices to use if any optimize etc if an index is used search it for the pointers to the actual data then go to the appropriate location in the data or if no index is used scan the whole table to determine which rows are needed load the data from disk into temporary location hopefully but not necessarily memory perform the count and average calculations so creating an array in python and getting the average basically skips all these steps save the last one as disk is among the most expensive operations program has to perform this is major flaw in the test see also the answers to this question asked here before even if you read the data from disk in your other test the process is completely different and it is hard to tell how relevant the results are to obtain more information about where postgres spends its time would suggest the following tests compare the execution time of your query to select without the aggregating functions cut step if you find that the aggregation leads to significant slowdown try if python does it faster obtaining the raw data through the plain select from the comparison to speed up your query reduce disk access first doubt very much that it is the aggregation that takes the time there is several ways to do that cache data in memory for subsequent access either via the db engine own capabilities or with tools like memcached reduce the size of your stored data optimize the use of indices sometimes this can mean to skip index use altogether after all it is disk access too for mysql seem to remember that it is recommended to skip indices if you assume that the query fetches more than of all the data in the table if your query makes good use of indices know that for mysql databases it helps to put indices and data on separate physical disks however do not know whether that is applicable for postgres there also might be more sophisticated problems such as swapping rows to disk if for some reason the result set cannot be completely processed in memory but would leave that kind of research until run into serious performance problems that cannot find another way to fix as it requires knowledge about lot of little under the hood details in your process update just realized that you seem to have no use for indices for the above query and most likely are not using any too so my advice on indices probably was not helpful sorry still would say that the aggregation is not the problem but disk access is will leave the index stuff in anyway it might still have some use
|
QA
|
why are sql aggregate functions so much slower than python and java or poor man olap need real dba opinion postgres takes ms to execute this query on my macbook pro while java and python perform the same calculation in under ms rows select count id average average average average from tuples is this normal behaviour when using sql database the schema the table holds responses to survey create table tuples id integer primary key integer integer integer integer copy tuples from responses csv delimiter as wrote some tests in java and python for context and they crush sql except for pure python java threads ms java ms python numpy ms python ms even sqlite is competitive with postgres despite it assumping all columns are strings for contrast even using just switching to numeric columns instead of integers in postgres results in slowdown tunings have tried without success include blindly following some web advice increased the shared memory available to postgres to mb increased the working memory to mb disabled connection and statement logging used stored procedure via create function language sql so my question is is my experience here normal and this is what can expect when using sql database can understand that acid must come with costs but this is kind of crazy in my opinion am not asking for realtime game speed but since java can process millions of doubles in under ms feel bit jealous is there better way to do simple olap on the cheap both in terms of money and server complexity have looked into mondrian and pig hadoop but not super excited about maintaining yet another server application and not sure if they would even help no the python code and java code do all the work in house so to speak just generate arrays with random values each then take the average do not include the generation in the timings only the averaging step the java threads timing uses threads one per array average overkill but it is definitely the fastest the sqlite timing is driven by the python program and is running from disk not memory realize postgres is doing much more behind the scenes but most of that work does not matter to me since this is read only data the postgres query does not change timing on subsequent runs have rerun the python tests to include spooling it off the disk the timing slows down considerably to nearly secs but am guessing that python file handling code is pretty much in though maybe not the csv lib so this indicates to me that postgres is not streaming from the disk either or that you are correct and should bow down before whoever wrote their storage layer
|
one other thing that an rdbms generally does for you is to provide concurrency by protecting you from simultaneous access by another process this is done by placing locks and there is some overhead from that if you are dealing with entirely static data that never changes and especially if you are in basically single user scenario then using relational database does not necessarily gain you much benefit
|
QA
|
why are sql aggregate functions so much slower than python and java or poor man olap need real dba opinion postgres takes ms to execute this query on my macbook pro while java and python perform the same calculation in under ms rows select count id average average average average from tuples is this normal behaviour when using sql database the schema the table holds responses to survey create table tuples id integer primary key integer integer integer integer copy tuples from responses csv delimiter as wrote some tests in java and python for context and they crush sql except for pure python java threads ms java ms python numpy ms python ms even sqlite is competitive with postgres despite it assumping all columns are strings for contrast even using just switching to numeric columns instead of integers in postgres results in slowdown tunings have tried without success include blindly following some web advice increased the shared memory available to postgres to mb increased the working memory to mb disabled connection and statement logging used stored procedure via create function language sql so my question is is my experience here normal and this is what can expect when using sql database can understand that acid must come with costs but this is kind of crazy in my opinion am not asking for realtime game speed but since java can process millions of doubles in under ms feel bit jealous is there better way to do simple olap on the cheap both in terms of money and server complexity have looked into mondrian and pig hadoop but not super excited about maintaining yet another server application and not sure if they would even help no the python code and java code do all the work in house so to speak just generate arrays with random values each then take the average do not include the generation in the timings only the averaging step the java threads timing uses threads one per array average overkill but it is definitely the fastest the sqlite timing is driven by the python program and is running from disk not memory realize postgres is doing much more behind the scenes but most of that work does not matter to me since this is read only data the postgres query does not change timing on subsequent runs have rerun the python tests to include spooling it off the disk the timing slows down considerably to nearly secs but am guessing that python file handling code is pretty much in though maybe not the csv lib so this indicates to me that postgres is not streaming from the disk either or that you are correct and should bow down before whoever wrote their storage layer
|
those are very detailed answers but they mostly beg the question how do get these benefits without leaving postgres given that the data easily fits into memory requires concurrent reads but no writes and is queried with the same query over and over again is it possible to precompile the query and optimization plan would have thought the stored procedure would do this but it does not really help to avoid disk access it is necessary to cache the whole table in memory can force postgres to do that think it is already doing this though since the query executes in just ms after repeated runs can tell postgres that the table is read only so it can optimize any locking code think it is possible to estimate the query construction costs with an empty table timings range from ms still cannot see why the java python tests are invalid postgres just is not doing that much more work though still have not addressed the concurrency aspect just the caching and query construction update do not think it is fair to compare the selects as suggested by pulling through the driver and serialization steps into python to run the aggregation nor even to omit the aggregation as the overhead in formatting and displaying is hard to separate from the timing if both engines are operating on in memory data it should be an apples to apples comparison am not sure how to guarantee that is already happening though cannot figure out how to add comments maybe do not have enough reputation
|
QA
|
why are sql aggregate functions so much slower than python and java or poor man olap need real dba opinion postgres takes ms to execute this query on my macbook pro while java and python perform the same calculation in under ms rows select count id average average average average from tuples is this normal behaviour when using sql database the schema the table holds responses to survey create table tuples id integer primary key integer integer integer integer copy tuples from responses csv delimiter as wrote some tests in java and python for context and they crush sql except for pure python java threads ms java ms python numpy ms python ms even sqlite is competitive with postgres despite it assumping all columns are strings for contrast even using just switching to numeric columns instead of integers in postgres results in slowdown tunings have tried without success include blindly following some web advice increased the shared memory available to postgres to mb increased the working memory to mb disabled connection and statement logging used stored procedure via create function language sql so my question is is my experience here normal and this is what can expect when using sql database can understand that acid must come with costs but this is kind of crazy in my opinion am not asking for realtime game speed but since java can process millions of doubles in under ms feel bit jealous is there better way to do simple olap on the cheap both in terms of money and server complexity have looked into mondrian and pig hadoop but not super excited about maintaining yet another server application and not sure if they would even help no the python code and java code do all the work in house so to speak just generate arrays with random values each then take the average do not include the generation in the timings only the averaging step the java threads timing uses threads one per array average overkill but it is definitely the fastest the sqlite timing is driven by the python program and is running from disk not memory realize postgres is doing much more behind the scenes but most of that work does not matter to me since this is read only data the postgres query does not change timing on subsequent runs have rerun the python tests to include spooling it off the disk the timing slows down considerably to nearly secs but am guessing that python file handling code is pretty much in though maybe not the csv lib so this indicates to me that postgres is not streaming from the disk either or that you are correct and should bow down before whoever wrote their storage layer
|
you need to increase postgres caches to the point where the whole working set fits into memory before you can expect to see perfomance comparable to doing it in memory with program
|
QA
|
why are sql aggregate functions so much slower than python and java or poor man olap need real dba opinion postgres takes ms to execute this query on my macbook pro while java and python perform the same calculation in under ms rows select count id average average average average from tuples is this normal behaviour when using sql database the schema the table holds responses to survey create table tuples id integer primary key integer integer integer integer copy tuples from responses csv delimiter as wrote some tests in java and python for context and they crush sql except for pure python java threads ms java ms python numpy ms python ms even sqlite is competitive with postgres despite it assumping all columns are strings for contrast even using just switching to numeric columns instead of integers in postgres results in slowdown tunings have tried without success include blindly following some web advice increased the shared memory available to postgres to mb increased the working memory to mb disabled connection and statement logging used stored procedure via create function language sql so my question is is my experience here normal and this is what can expect when using sql database can understand that acid must come with costs but this is kind of crazy in my opinion am not asking for realtime game speed but since java can process millions of doubles in under ms feel bit jealous is there better way to do simple olap on the cheap both in terms of money and server complexity have looked into mondrian and pig hadoop but not super excited about maintaining yet another server application and not sure if they would even help no the python code and java code do all the work in house so to speak just generate arrays with random values each then take the average do not include the generation in the timings only the averaging step the java threads timing uses threads one per array average overkill but it is definitely the fastest the sqlite timing is driven by the python program and is running from disk not memory realize postgres is doing much more behind the scenes but most of that work does not matter to me since this is read only data the postgres query does not change timing on subsequent runs have rerun the python tests to include spooling it off the disk the timing slows down considerably to nearly secs but am guessing that python file handling code is pretty much in though maybe not the csv lib so this indicates to me that postgres is not streaming from the disk either or that you are correct and should bow down before whoever wrote their storage layer
|
postgres is doing lot more than it looks like maintaining data consistency for start if the values do not have to be spot on or if the table is updated rarely but you are running this calculation often you might want to look into materialized views to speed it up note have not used materialized views in postgres they look at little hacky but might suite your situation materialized views also consider the overhead of actually connecting to the server and the round trip required to send the request to the server and back would consider ms for something like this to be pretty good quick test on my oracle server the same table structure with about rows and no indexes takes about seconds which is almost all just oracle sucking the data off disk the real question is is ms fast enough more was interested in solving this using materialized views since have never really played with them this is in oracle first created mv which refreshes every minute create materialized view mv so build immediate refresh complete start with sysdate next sysdate as select count average average average average from so while its refreshing there is no rows returned sql select from mv so no rows selected elapsed once it refreshes its much faster than doing the raw query sql select count average average average average from so count average average average average elapsed sql select from mv so count average average average average elapsed sql if we insert into the base table the result is not immediately viewable view the mv sql insert into so values row created elapsed sql commit commit complete elapsed sql select from mv so count average average average average elapsed sql but wait minute or so and the mv will update behind the scenes and the result is returned fast as you could want sql count average average average average elapsed sql this is not ideal for start its not realtime inserts updates will not be immediately visible also you have got query running to update the mv whether you need it or not this can be tune to whatever time frame or on demand but this does show how much faster an mv can make it seem to the end user if you can live with values which are not quite upto the second accurate
|
QA
|
improving python readability have been really enjoying python programming lately come from background of strong love for based coding where everything is perhaps more complicated than it should be but puts hair on your chest at least so switching from to python for more complex things that do not require tons of speed has been more of boon than bane in writing projects however coming from this land of brackets and parentheses and structs as far as the naked eye can see come across small problem find python difficult to read for example the following block of text is hard for me to decipher unless stare at it which dislike doing if foo bar baz while bar not biz bar am going to find you biz swear on my life did not warn you biz my father is avenged the problem occurs at the end of that if block all the tabbing and then suddenly returning to jarring block feels almost disturbing as solution have started coding my python like this if foo bar baz while bar not biz bar am going to find you biz swear on my life while if did not warn you biz my father is avenged and this for some odd reason makes me more able to read my own code but am curious has anyone else with my strange problem found easier ways to make their tabbed out code more readable would love to find out if there is better way to do this before this becomes huge habit for me
|
part of learning new programming language is learning to read code in that language crutch like this may make it easier to read your own code but it is going to impede the process of learning how to read anyone else python code really think you would be better off getting rid of the end of block comments and getting used to normal python
|
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
|
do not think authkit is actively maintained anymore it does use the paste http pythonpaste org libs though for things like http basic digest authentication would probably go ahead and take look at the source for some inspiration and then use the paste tools if you want to use http authentication there is also openid which is very easy to setup the python openid libs have an excellent example that is easy to translate to wsgi for wrapping pylons app you can look at an example http ionrock org hg brightcontent main file dcc brightcontent plugins openidauth py
|
QA
|
why are sql aggregate functions so much slower than python and java or poor man olap need real dba opinion postgres takes ms to execute this query on my macbook pro while java and python perform the same calculation in under ms rows select count id average average average average from tuples is this normal behaviour when using sql database the schema the table holds responses to survey create table tuples id integer primary key integer integer integer integer copy tuples from responses csv delimiter as wrote some tests in java and python for context and they crush sql except for pure python java threads ms java ms python numpy ms python ms even sqlite is competitive with postgres despite it assumping all columns are strings for contrast even using just switching to numeric columns instead of integers in postgres results in slowdown tunings have tried without success include blindly following some web advice increased the shared memory available to postgres to mb increased the working memory to mb disabled connection and statement logging used stored procedure via create function language sql so my question is is my experience here normal and this is what can expect when using sql database can understand that acid must come with costs but this is kind of crazy in my opinion am not asking for realtime game speed but since java can process millions of doubles in under ms feel bit jealous is there better way to do simple olap on the cheap both in terms of money and server complexity have looked into mondrian and pig hadoop but not super excited about maintaining yet another server application and not sure if they would even help no the python code and java code do all the work in house so to speak just generate arrays with random values each then take the average do not include the generation in the timings only the averaging step the java threads timing uses threads one per array average overkill but it is definitely the fastest the sqlite timing is driven by the python program and is running from disk not memory realize postgres is doing much more behind the scenes but most of that work does not matter to me since this is read only data the postgres query does not change timing on subsequent runs have rerun the python tests to include spooling it off the disk the timing slows down considerably to nearly secs but am guessing that python file handling code is pretty much in though maybe not the csv lib so this indicates to me that postgres is not streaming from the disk either or that you are correct and should bow down before whoever wrote their storage layer
|
thanks for the oracle timings that is the kind of stuff am looking for disappointing though materialized views are probably worth considering as think can precompute the most interesting forms of this query for most users do not think query round trip time should be very high as am running the the queries on the same machine that runs postgres so it cannot add much latency have also done some checking into the cache sizes and it seems postgres relies on the os to handle caching they specifically mention bsd as the ideal os for this so thinking mac os ought to be pretty smart about bringing the table into memory unless someone has more specific params in mind think more specific caching is out of my control in the end can probably put up with ms response times but knowing that ms is possible target makes me feel unsatisfied as even ms times would enable more users to have more up to date queries and get rid of lots of caching and precomputed hacks just checked the timings using mysql and they are slightly worse than postgres so barring some major caching breakthroughs guess this is what can expect going the relational db route wish could up vote some of your answers but do not have enough points yet
|
QA
|
what is the best way to duplicate fork in windows how do implement some logic that will allow me to reproduce on windows the functionality that have on linux with the fork system call using python am specifically trying to execute method on the sapi com component while continuing the other logic in the main thread without blocking or waiting
|
the threading example from eli will run the thread but not do any of the work after that line am going to look into the processing module and the subprocess module think the com method am running needs to be in another process not just in another thread
|
QA
|
large python includes have file that want to include in python but the included file is fairly long and it would be much neater to be able to split them into several files but then have to use several include statements is there some way to group together several files and include them all at once
|
yes take look at the packages section in http docs python org tut node html basically you can place bunch of files into directory and add an init py file to the directory if the directory is in your pythonpath or sys path you can do import directoryname to import everything in the directory or import directoryname some file in directory to import specific file that is in the directory the init py files are required to make python treat the directories as containing packages this is done to prevent directories with common name such as string from unintentionally hiding valid modules that occur later on the module search path in the simplest case init py can just be an empty file but it can also execute initialization code for the package or set the all variable described later
|
QA
|
large python includes have file that want to include in python but the included file is fairly long and it would be much neater to be able to split them into several files but then have to use several include statements is there some way to group together several files and include them all at once
|
put files in one folder add init py file to the folder do necessary imports in init py replace multiple imports by one import folder name see python package management
|
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
|
put at the end of your line or enclose the statement in parens from ibm and and or and and
|
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
|
what is the line you can just have arguments on the next line without any problems dostuff blahblah blahblah blahblah blahblah blahblah blahblah blahblah otherwise you can do something like this if true and false check the style guide for more information from your example line or note that the style guide says that using the implicit continuation with parentheses is preferred but in this particular case just adding parentheses around your expression is probably the wrong way to go
|
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
|
from the horse mouth explicit line joining two or more physical lines may be joined into logical lines using backslash characters as follows when physical line ends in backslash that is not part of string literal or comment it is joined with the following forming single logical line deleting the backslash and the following end of line character for example if year and month and day and hour and minute and second looks like valid date return line ending in backslash cannot carry comment backslash does not continue comment backslash does not continue token except for string literals tokens other than string literals cannot be split across physical lines using backslash backslash is illegal elsewhere on line outside string literal
|
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
|
from style guide for python code the preferred way of wrapping long lines is by using python implied line continuation inside parentheses brackets and braces long lines can be broken over multiple lines by wrapping expressions in parentheses these should be used in preference to using backslash for line continuation backslashes may still be appropriate at times for example long multiple with statements cannot use implicit continuation so backslashes are acceptable with open path to some file you want to read as file open path to some file being written as file file write file read another such case is with assert statements make sure to indent the continued line appropriately the preferred place to break around binary operator is after the operator not before it some examples class rectangle blob def init self width height color black emphasis none highlight if width and height and color red and emphasis strong or highlight raise valueerror sorry you lose if width and height and color red or emphasis is none raise valueerror do not think so values are width height blob init self width height color emphasis highlight edit pep now recommends the opposite convention for breaking at binary operations used by mathematicians and their publishers to improve readability donald knuth style of breaking before binary operator aligns operators vertically thus reducing the eye workload when determining which items are added and subtracted from pep should line break before or after binary operator donald knuth explains the traditional rule in his computers and typesetting series although formulas within paragraph always break after binary operations and relations displayed formulas always break before binary operations following the tradition from mathematics usually results in more readable code yes easy to match operators with operands income gross wages taxable interest dividends qualified dividends ira deduction student loan interest in python code it is permissible to break before or after binary operator as long as the convention is consistent locally for new code knuth style is suggested donald knuth the texbook pages and
|
QA
|
how do you check whether python method is bound or not given reference to method is there way to check whether the method is bound to an object or not can you also access the instance that it is bound to
|
im self attribute
|
QA
|
generator expressions vs list comprehension when should you use generator expressions and when should you use list comprehensions in python generator expression for in range list comprehension for in range
|
sometimes you can get away with the tee function from itertools it returns multiple iterators for the same generator that can be used independently
|
QA
|
why are sql aggregate functions so much slower than python and java or poor man olap need real dba opinion postgres takes ms to execute this query on my macbook pro while java and python perform the same calculation in under ms rows select count id average average average average from tuples is this normal behaviour when using sql database the schema the table holds responses to survey create table tuples id integer primary key integer integer integer integer copy tuples from responses csv delimiter as wrote some tests in java and python for context and they crush sql except for pure python java threads ms java ms python numpy ms python ms even sqlite is competitive with postgres despite it assumping all columns are strings for contrast even using just switching to numeric columns instead of integers in postgres results in slowdown tunings have tried without success include blindly following some web advice increased the shared memory available to postgres to mb increased the working memory to mb disabled connection and statement logging used stored procedure via create function language sql so my question is is my experience here normal and this is what can expect when using sql database can understand that acid must come with costs but this is kind of crazy in my opinion am not asking for realtime game speed but since java can process millions of doubles in under ms feel bit jealous is there better way to do simple olap on the cheap both in terms of money and server complexity have looked into mondrian and pig hadoop but not super excited about maintaining yet another server application and not sure if they would even help no the python code and java code do all the work in house so to speak just generate arrays with random values each then take the average do not include the generation in the timings only the averaging step the java threads timing uses threads one per array average overkill but it is definitely the fastest the sqlite timing is driven by the python program and is running from disk not memory realize postgres is doing much more behind the scenes but most of that work does not matter to me since this is read only data the postgres query does not change timing on subsequent runs have rerun the python tests to include spooling it off the disk the timing slows down considerably to nearly secs but am guessing that python file handling code is pretty much in though maybe not the csv lib so this indicates to me that postgres is not streaming from the disk either or that you are correct and should bow down before whoever wrote their storage layer
|
am ms sql guy myself and we would use dbcc pintable to keep table cached and set statistics io to see that it is reading from cache and not disk cannot find anything on postgres to mimic pintable but pg buffercache seems to give details on what is in the cache you may want to check that and see if your table is actually being cached quick back of the envelope calculation makes me suspect that you are paging from disk assuming postgres uses byte integers you have bytes per row so your table is minimum of bytes mb assuming mb sustained throughput on your hdd you are looking at right around ms to read the data which as pointed out should be where almost all of the time is being spent unless screwed up my math somewhere do not see how it is possible that you are able to read mb into your java app and process it in the times you are showing unless that file is already cached by either the drive or your os
|
QA
|
how do you check whether python method is bound or not given reference to method is there way to check whether the method is bound to an object or not can you also access the instance that it is bound to
|
def isbound method return method im self is not none def instance bounded method return bounded method im self user defined methods when user defined method object is created by retrieving user defined function object from class its im self attribute is none and the method object is said to be unbound when one is created by retrieving user defined function object from class via one of its instances its im self attribute is the instance and the method object is said to be bound in either case the new method im class attribute is the class from which the retrieval takes place and its im func attribute is the original function object in python and instance method objects have new attributes for the object and function comprising the method the new synonym for im self is self and im func is also available as func the old names are still supported in python but are gone in
|
QA
|
why are sql aggregate functions so much slower than python and java or poor man olap need real dba opinion postgres takes ms to execute this query on my macbook pro while java and python perform the same calculation in under ms rows select count id average average average average from tuples is this normal behaviour when using sql database the schema the table holds responses to survey create table tuples id integer primary key integer integer integer integer copy tuples from responses csv delimiter as wrote some tests in java and python for context and they crush sql except for pure python java threads ms java ms python numpy ms python ms even sqlite is competitive with postgres despite it assumping all columns are strings for contrast even using just switching to numeric columns instead of integers in postgres results in slowdown tunings have tried without success include blindly following some web advice increased the shared memory available to postgres to mb increased the working memory to mb disabled connection and statement logging used stored procedure via create function language sql so my question is is my experience here normal and this is what can expect when using sql database can understand that acid must come with costs but this is kind of crazy in my opinion am not asking for realtime game speed but since java can process millions of doubles in under ms feel bit jealous is there better way to do simple olap on the cheap both in terms of money and server complexity have looked into mondrian and pig hadoop but not super excited about maintaining yet another server application and not sure if they would even help no the python code and java code do all the work in house so to speak just generate arrays with random values each then take the average do not include the generation in the timings only the averaging step the java threads timing uses threads one per array average overkill but it is definitely the fastest the sqlite timing is driven by the python program and is running from disk not memory realize postgres is doing much more behind the scenes but most of that work does not matter to me since this is read only data the postgres query does not change timing on subsequent runs have rerun the python tests to include spooling it off the disk the timing slows down considerably to nearly secs but am guessing that python file handling code is pretty much in though maybe not the csv lib so this indicates to me that postgres is not streaming from the disk either or that you are correct and should bow down before whoever wrote their storage layer
|
retested with mysql specifying engine memory and it does not change thing still ms sqlite using an in memory db gives similar timings as well ms the math here looks correct at least the size as that is how big the sqlite db is am just not buying the disk causes slowness argument as there is every indication the tables are in memory the postgres guys all warn against trying too hard to pin tables to memory as they swear the os will do it better than the programmer to clarify the timings the java code is not reading from disk making it totally unfair comparison if postgres is reading from the disk and calculating complicated query but that is really besides the point the db should be smart enough to bring small table into memory and precompile stored procedure imho update in response to the first comment below am not sure how would test the query without using an aggregation function in way that would be fair since if select all of the rows it will spend tons of time serializing and formatting everything am not saying that the slowness is due to the aggregation function it could still be just overhead from concurrency integrity and friends just do not know how to isolate the aggregation as the sole independent variable
|
QA
|
best way to check if list is empty for example if passed the following how do check to see if is empty
|
if not print list is empty using the implicit booleanness of the empty list is quite pythonic
|
QA
|
best way to check if list is empty for example if passed the following how do check to see if is empty
|
have seen the below as preferred as it will catch the null list as well if not print the list is empty or null
|
QA
|
best way to check if list is empty for example if passed the following how do check to see if is empty
|
an empty list is itself considered false in true value testing see python documentation if print not empty daren thomas edit another point against testing the empty list as false what about polymorphism you should not depend on list being list it should just quack like duck how are you going to get your duckcollection to quack false when it has no elements your duckcollection should implement nonzero or len so the if will work without problems
|
QA
|
best way to check if list is empty for example if passed the following how do check to see if is empty
|
prefer the following if print the list is empty readable and you do not have to worry about calling function like len to iterate through the variable although am not entirely sure what the bigo notation of something like this is but python so blazingly fast doubt it would matter unless was gigantic
|
QA
|
what are some strategies to write python code that works in cpython jython and ironpython having tries to target two of these environments at the same time can safely say the if you have to use database etc you end up having to write unique code for that environment have you got great way to handle this situation
|
if you do find you need to write unique code for an environment use pythons import mymodule jython as mymodule import mymodule cpython as mymodule have this stuff in simple module module importer and write your code like this from module importer import mymodule this way all you need to do is alter module importer py per platform
|
QA
|
why are sql aggregate functions so much slower than python and java or poor man olap need real dba opinion postgres takes ms to execute this query on my macbook pro while java and python perform the same calculation in under ms rows select count id average average average average from tuples is this normal behaviour when using sql database the schema the table holds responses to survey create table tuples id integer primary key integer integer integer integer copy tuples from responses csv delimiter as wrote some tests in java and python for context and they crush sql except for pure python java threads ms java ms python numpy ms python ms even sqlite is competitive with postgres despite it assumping all columns are strings for contrast even using just switching to numeric columns instead of integers in postgres results in slowdown tunings have tried without success include blindly following some web advice increased the shared memory available to postgres to mb increased the working memory to mb disabled connection and statement logging used stored procedure via create function language sql so my question is is my experience here normal and this is what can expect when using sql database can understand that acid must come with costs but this is kind of crazy in my opinion am not asking for realtime game speed but since java can process millions of doubles in under ms feel bit jealous is there better way to do simple olap on the cheap both in terms of money and server complexity have looked into mondrian and pig hadoop but not super excited about maintaining yet another server application and not sure if they would even help no the python code and java code do all the work in house so to speak just generate arrays with random values each then take the average do not include the generation in the timings only the averaging step the java threads timing uses threads one per array average overkill but it is definitely the fastest the sqlite timing is driven by the python program and is running from disk not memory realize postgres is doing much more behind the scenes but most of that work does not matter to me since this is read only data the postgres query does not change timing on subsequent runs have rerun the python tests to include spooling it off the disk the timing slows down considerably to nearly secs but am guessing that python file handling code is pretty much in though maybe not the csv lib so this indicates to me that postgres is not streaming from the disk either or that you are correct and should bow down before whoever wrote their storage layer
|
are you using tcp to access the postgres in that case nagle is messing with your timing
|
QA
|
best way to check if list is empty for example if passed the following how do check to see if is empty
|
the pythonic way to do it is from the pep style guide for sequences strings lists tuples use the fact that empty sequences are false yes if not seq if seq no if len seq if not len seq
|
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
|
why do not you try the grinder to load test your server it comes with all this and more prebuilt and it supports python as scripting language
|
QA
|
any good ajax framework for google app engine apps am trying to implement ajax in my google app engine application and so am looking for good ajax framework that will help me anyone has any idea am thinking about google web toolkit how good it is in terms of creating ajax for google app engine
|
as google web toolkit is subset of java it works best when you java at the backend too since google app engine is currently python only think you would have to do lot of messing about to get your server and client to talk nicely to each other jquery seems to be the most popular javascript library option in the ajax tag at djangosnippets com edit the above is only true of google app engine applications written in python as google app engine now supports java gwt could now be good choice for writing an ajax front end google even have tutorial showing you how to do it
|
QA
|
any good ajax framework for google app engine apps am trying to implement ajax in my google app engine application and so am looking for good ajax framework that will help me anyone has any idea am thinking about google web toolkit how good it is in terms of creating ajax for google app engine
|
would recommend looking into pure javascript framework probably jquery for your client side code and write json services in python that seems to be the easiest bestest way to go google web toolkit let us you write the ui in java and compile it to javascript as dave says it may be better choice where the backend is in java as it has nice rpc hooks for that case
|
QA
|
any good ajax framework for google app engine apps am trying to implement ajax in my google app engine application and so am looking for good ajax framework that will help me anyone has any idea am thinking about google web toolkit how good it is in terms of creating ajax for google app engine
|
jquery is fine library but also check out the prototype javascript framework it really turns javascript from being an occasionally awkward language into beautiful and elegant language
|
QA
|
glade or no glade what is the best way to use pygtk have been learning python for while now with some success even managed to create one or two simple programs using pygtk glade the thing is am not sure if the best way to use gtk with python is by building the interfaces using glade was wondering if the more experienced ones among us remember am just beginner could point out the benefits and caveats of using glade as opposed to creating everything in the code itself assuming that learning the correct gtk bindings would not exactly be problem
|
glade is very useful for creating interfaces it means you can easily change the gui without doing much coding you will find that if you want to do anything useful build treeview you will have to get familiar with various parts of the gtk documentation in practice finding good tutorial examples
|
QA
|
what is the difference between old style and new style classes in python what is the difference between old style and new style classes in python is there ever reason to use old style classes these days
|
from http docs python org reference datamodel html new style and classic classes up to python old style classes were the only flavour available to the user the concept of old style class is unrelated to the concept of type if is an instance of an old style class then class designates the class of but type is always type instance this reflects the fact that all old style instances independently of their class are implemented with single built in type called instance new style classes were introduced in python to unify the concepts of class and type new style class is simply user defined type no more no less if is an instance of new style class then type is typically the same as class although this is not guaranteed new style class instance is permitted to override the value returned for class the major motivation for introducing new style classes is to provide unified object model with full meta model it also has number of immediate benefits like the ability to subclass most built in types or the introduction of descriptors which enable computed properties for compatibility reasons classes are still old style by default new style classes are created by specifying another new style class type as parent class or the top level type object if no other parent is needed the behaviour of new style classes differs from that of old style classes in number of important details in addition to what type returns some of these changes are fundamental to the new object model like the way special methods are invoked others are fixes that could not be implemented before for compatibility concerns like the method resolution order in case of multiple inheritance python only has new style classes no matter if you subclass from object or not classes are new style in python it is however recommended that you still subclass from object
|
QA
|
any good ajax framework for google app engine apps am trying to implement ajax in my google app engine application and so am looking for good ajax framework that will help me anyone has any idea am thinking about google web toolkit how good it is in terms of creating ajax for google app engine
|
there is no reason why you should not use gae and google web toolkit gwt together you write your backend code in python and the frontend code in java and possibly some javascript which is then compiled to javascript when using another ajax framework you will also have this difference between server and client side language gwt has features that make remote invocation of java code on the server easier but these are entirely optional you can just use json or xml interfaces just like with other ajax frameworks gwt also comes with javascript overlay types that basically allow you to treat piece of json data like java object when developing the client side code you can read more about this here update now that google has added java support for google app engine you can develop both backend and frontend code in java on full google stack if you like there is nice eclipse plugin from google that makes it very easy to develop and deploy applications that use gae gwt or both
|
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
|
this snippet will do so if you are going to do it frequently you might want to make sortkeys method or somesuch to make it easier on the eyes keys list keys keys sort for key in keys print key edit df solution is better forgot all about sorted
|
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
|
do you mean that you need the values sorted by the value of the key in that case this should do it for key in sorted print key edit changed to use sorted instead of sorted keys thanks eli
|
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
|
or shorter for key value in sorted items print value
|
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
|
this is this is this is for in sorted items print this is this is this is
|
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
|
this is this is this is ks keys ks sort for in ks print this is
|
QA
|
what are some strategies to write python code that works in cpython jython and ironpython having tries to target two of these environments at the same time can safely say the if you have to use database etc you end up having to write unique code for that environment have you got great way to handle this situation
|
daren thomas agree but you should use the platform module to determine which interpreter you are running
|
QA
|
what is the difference between old style and new style classes in python what is the difference between old style and new style classes in python is there ever reason to use old style classes these days
|
or rather you should always use new style classes unless you have code that needs to work with versions of python older than
|
QA
|
what python way would you suggest to check whois database records am trying to get webservice up and running that actually requires to check whois databases what am doing right now is ugly and would like to avoid it as much as can call gwhois command and parse its output ugly did some search to try to find pythonic way to do this task generally got quite much nothing this old discussion list link has way to check if domain exist quite not what was looking for but still it was best anwser google gave me everything else is just bunch of unanwsered questions any of you have succeeded to get some method up and running would very much appreciate some tips or should just do it the opensource way sit down and code something by myself
|
there is nothing wrong with using command line utility to do what you want if you put nice wrapper around the service you can implement the internals however you want for example class whois object whois by query cache def init self query initializes the instance variables to defaults see meth lookup for details on how to submit the query self query query self domain none other fields def lookup self submits the whois query and stores results internally implementation now whether or not you roll your own using urllib wrap around command line utility like you are doing or import third party library and use that like you are saying this interface stays the same this approach is generally not considered ugly at all sometimes command utilities do what you want and you should be able to leverage them if speed ends up being bottleneck your abstraction makes the process of switching to native python implementation transparent to your client code practicality beats purity that is what is pythonic
|
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 fooid value
|
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
|
parsing is one of those areas where you really do not want to roll your own if you can avoid it as you will be chasing down the edge cases and bugs for years go come would recommend using beautifulsoup it has very good reputation and looks from the docs like it is pretty easy to use
|
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
|
import re reg re compile input type hidden name value id value reg search inputhtml group print value is value
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.