prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
is there any difference between foo is none and foo none is there any difference between if foo is none pass and if foo none pass the convention that have seen in most python code and the code myself write is the former but recently came across code which uses the latter none is an instance and the only instance iirc of nonetype so it should not matter right are there any circumstances in which it might
for none there should not be difference between equality and identity is the nonetype probably returns identity for equality since none is the only instance you can make of nonetype think this is true the two operations are the same in the case of other types this is not always the case for example list list if list list print equal if list is list print same this would print equal since lists have comparison operation that is not the default returning of identity
QA
wxpython how do examine dragged data in ondragover am bit perplexed by drag and drop in wxpython but perhaps this questions pertains to drag and drop in other gui frameworks as well the frameworks provides couple of callbacks onenter and ondragover that purportedly allow me to inform the system whether the current mouse position is valid place to drop whatever it is that is being dragged from these methods can return wx dragnone wx dragcopy etc what baffles me is that from within these methods am not allowed to call getdata which means am not allowed to examine the data that the user is dragging if cannot see the data how am supposed to know whether it is ok for the user to drop here
one solution which is hack of limited usefulness is when drag is initiated store the dragged data in global or static reference somewhere this way in the onenter and ondragover handlers it is possible to get reference to the data being dragged this is of course only useful for drags within the same application the same instance of the application actually
QA
what is the best way to grab parse command line arguments passed to python script what is the easiest tersest and most flexible method or library for parsing python command line arguments
this answer suggests optparse which is appropriate for older python versions for python and above argparse replaces optparse see this answer for more information as other people pointed out you are better off going with optparse over getopt getopt is pretty much one to one mapping of the standard getopt library functions and not very easy to use optparse while being bit more verbose is much better structured and simpler to extend later on here is typical line to add an option to your parser parser add option query action store dest query help query string default spam it pretty much speaks for itself at processing time it will accept or query as options store the argument in an attribute called query and has default value if you do not specify it it is also self documenting in that you declare the help argument which will be used when run with help right there with the option usually you parse your arguments with options args parser parse args this will by default parse the standard arguments passed to the script sys argv options query will then be set to the value you passed to the script you create parser simply by doing parser optparse optionparser these are all the basics you need here is complete python script that shows this import optparse parser optparse optionparser parser add option query action store dest query help query string default spam options args parser parse args print query string options query lines of python that show you the basics save it in sample py and run it once with python sample py and once with python sample py query myquery beyond that you will find that optparse is very easy to extend in one of my projects created command class which allows you to nest subcommands in command tree easily it uses optparse heavily to chain commands together it is not something can easily explain in few lines but feel free to browse around in my repository for the main class as well as class that uses it and the option parser
QA
find broken symlinks with python if call os stat on broken symlink python throws an oserror exception this makes it useful for finding them however there are few other reasons that os stat might throw similar exception is there more precise way of detecting broken symlinks with python under linux
common python saying is that it is easier to ask forgiveness than permission while am not fan of this statement in real life it does apply in lot of cases usually you want to avoid code that chains two system calls on the same file because you never know what will happen to the file in between your two calls in your code typical mistake is to write something like if os path exists path os unlink path the second call os unlink may fail if something else deleted it after your if test raise an exception and stop the rest of your function from executing you might think this does not happen in real life but we just fished another bug like that out of our codebase last week and it was the kind of bug that left few programmers scratching their head and claiming heisenbug for the last few months so in your particular case would probably do try os stat path except oserror if errno errno enoent print path does not exist or is broken symlink path else raise the annoyance here is that stat returns the same error code for symlink that just is not there and broken symlink so guess you have no choice than to break the atomicity and do something like if not os path exists os readlink path print path is broken symlink path
QA
is there any difference between foo is none and foo none is there any difference between if foo is none pass and if foo none pass the convention that have seen in most python code and the code myself write is the former but recently came across code which uses the latter none is an instance and the only instance iirc of nonetype so it should not matter right are there any circumstances in which it might
jason recommend using something more along the lines of if foo foo is not none else foo is none do not like using if foo unless foo truly represents boolean value or if foo is string or an object or something else if foo may work but it looks like lazy shortcut to me if you are checking to see if is none say if is none
QA
where can learn more about pypy translation function have been having hard time trying to understand pypy translation it looks like something absolutely revolutionary from simply reading the description however am hard pressed to find good documentation on actually translating real world piece of code to something such as llvm does such thing exist the official pypy documentation on it just skims over the functionality rather than providing anything can try out myself
are you looking for python specific translation or just the general how do you compile some code to bytecode if the latter is your case check the llvm tutorial especially find chapter two which teaches you to write compiler for your own language interesting
QA
class views in django django view points to function which can be problem if you want to change only bit of functionality yes could have million keyword arguments and even more if statements in the function but was thinking more of an object oriented approach for example have page that displays user this page is very similar to page that displays group but it is still not so similar to just use another data model group also has members etc one way would be to point views to class methods and then extend that class has anyone tried this approach or has any other idea
if you want to share common functionality between pages suggest you look at custom tags they are quite easy to create and are very powerful also templates can extend from other templates this allows you to have base template to set up the layout of the page and to share this between other templates which fill in the blanks you can nest templates to any depth allowing you to specify the layout on separate groups of related pages in one place
QA
class views in django django view points to function which can be problem if you want to change only bit of functionality yes could have million keyword arguments and even more if statements in the function but was thinking more of an object oriented approach for example have page that displays user this page is very similar to page that displays group but it is still not so similar to just use another data model group also has members etc one way would be to point views to class methods and then extend that class has anyone tried this approach or has any other idea
you can always create class override the call function and then point the url file to an instance of the class you can take look at the formwizard class to see how this is done
QA
how to use xpath in python what is the library is there full implementation how is the library used where is its website
libxml has number of advantages compliance to the spec active development and community participation speed this is really python wrapper around implementation ubiquity the libxml library is pervasive and thus well tested downsides include compliance to the spec it is strict things like default namespace handling are easier in other libraries use of native code this can be pain depending on your how your application is distributed deployed rpms are available that ease some of this pain manual resource handling note in the sample below the calls to freedoc and xpathfreecontext this is not very pythonic if you are doing simple path selection stick with elementtree which is included in python if you need full spec compliance or raw speed and can cope with the distribution of native code go with libxml sample of libxml xpath use import libxml doc libxml parsefile tst xml ctxt doc xpathnewcontext res ctxt xpatheval if len res print xpath query wrong node set size sys exit if res name doc or res name foo print xpath query wrong node set value sys exit doc freedoc ctxt xpathfreecontext sample of elementtree xpath use from elementtree elementtree import elementtree mydoc elementtree file tst xml for in mydoc findall foo bar print get title text
QA
is there any difference between foo is none and foo none is there any difference between if foo is none pass and if foo none pass the convention that have seen in most python code and the code myself write is the former but recently came across code which uses the latter none is an instance and the only instance iirc of nonetype so it should not matter right are there any circumstances in which it might
word of caution if foo do something is not exactly the same as if is not none do something the former is boolean value test and can evaluate to false in different contexts there are number of things that represent false in boolean value tests for example empty containers boolean values none also evaluates to false in this situation but other things do too
QA
does php have an equivalent to this type of python string substitution python has this wonderful way of handling string substitutions using dictionaries the site site adj because it adj site stackoverflow adj rocks the stackoverflow site rocks because it rocks love this because you can specify value once in the dictionary and then replace it all over the place in the string have tried to achieve something similar in php using various string replace functions but everything have come up with feels awkward does anybody have nice clean way to do this kind of string substitution in php edit here is the code from the sprintf page that liked best php function sprintf str vars char tmp array foreach vars as tmp char char return str replace array keys tmp array values tmp str echo sprintf the site site adj because it adj array site stackoverflow adj rocks
some of the user contributed notes and functions in php documentation for sprintf come quite close note search the page for sprintf
QA
does php have an equivalent to this type of python string substitution python has this wonderful way of handling string substitutions using dictionaries the site site adj because it adj site stackoverflow adj rocks the stackoverflow site rocks because it rocks love this because you can specify value once in the dictionary and then replace it all over the place in the string have tried to achieve something similar in php using various string replace functions but everything have come up with feels awkward does anybody have nice clean way to do this kind of string substitution in php edit here is the code from the sprintf page that liked best php function sprintf str vars char tmp array foreach vars as tmp char char return str replace array keys tmp array values tmp str echo sprintf the site site adj because it adj array site stackoverflow adj rocks
function subst str dict return preg replace array map create function return array keys dict array values dict str you call it like so echo subst the site site adj because it adj array site stackoverflow adj rocks
QA
does php have an equivalent to this type of python string substitution python has this wonderful way of handling string substitutions using dictionaries the site site adj because it adj site stackoverflow adj rocks the stackoverflow site rocks because it rocks love this because you can specify value once in the dictionary and then replace it all over the place in the string have tried to achieve something similar in php using various string replace functions but everything have come up with feels awkward does anybody have nice clean way to do this kind of string substitution in php edit here is the code from the sprintf page that liked best php function sprintf str vars char tmp array foreach vars as tmp char char return str replace array keys tmp array values tmp str echo sprintf the site site adj because it adj array site stackoverflow adj rocks
marius do not know if it is faster but you can do it without regexes function subst str dict foreach dict as key value str str replace key value str return str
QA
how to check what os am running on in python what do need to look at to see if am on windows unix etc
you can also use sys platform if you already have imported sys and you do not want to import another module import sys sys platform linux
QA
is safe eval really safe am looking for safe eval function to implement spreadsheet like calculations using numpy scipy the functionality to do this the rexec module has been removed from python since due to apparently unfixable security problems there are several third party hacks out there that purport to do this the most thought out solution that have found is this python cookbok recipe safe eval am reasonably safe if use this or something similar to protect from malicious code or am stuck with writing my own parser does anyone know of any better alternatives edit just discovered restrictedpython which is part of zope any opinions on this are welcome
writing your own parser could be fun it might be better option because people are expecting to use the familiar spreadsheet syntax excel etc and not python when they are entering formulas am not familiar with safe eval but would imagine that anything like this certainly has the potential for exploitation
QA
prototyping with python code before compiling have been mulling over writing peak fitting library for while know python fairly well and plan on implementing everything in python to begin with but envisage that may have to re implement some core routines in compiled language eventually iirc one of python original remits was as prototyping language however python is pretty liberal in allowing functions functors objects to be passed to functions and methods whereas suspect the same is not true of say or fortran what should know about designing functions classes which envisage will have to interface into the compiled language and how much of these potential problems are dealt with by libraries such as ctypes bgen swig boost python cython or python sip for this particular use case fitting library imagine allowing users to define mathematical functions guassian lorentzian etc as python functions which can then to be passed an interpreted by the compiled code fitting library passing and returning arrays is also essential
have not used swig or sip but find writing python wrappers with boost python to be very powerful and relatively easy to use am not clear on what your requirements are for passing types between and python but you can do that easily by either exposing type to python or by using generic boost python object argument to your api you can also register converters to automatically convert python types to types and vice versa if you plan use boost python the tutorial is good place to start have implemented something somewhat similar to what you need have function that accepts python function and an image as arguments and applies the python function to each pixel in the image image unary boost python object op image am image out new image am width am height am channels for unsigned int am size out extract float op am return out in this case image is object exposed to python an image with float pixels and op is python defined function or really any python object with call attribute you can then use this function as follows assuming unary is located in the called image that also contains image and load function import image am image load somefile tiff double im image unary lambda am as for using arrays with boost personally have not done this but know the functionality to expose arrays to python using boost is available this might be helpful
QA
most pythonic way equivalent for while next end what is the best python idiom for this construct while next end do not have the ability to recode next update and the answer from seems to be for in iter next end
maybe it is not terribly idiomatic but would be inclined to go with next while end do something with next but that is because find that sort of thing easy to read
QA
most pythonic way equivalent for while next end what is the best python idiom for this construct while next end do not have the ability to recode next update and the answer from seems to be for in iter next end
what are you trying to do here if you are iterating over list you can use for in where is the element and is the list if you are filtering list you can use list comprehensions for in if to get all the even numbers in list
QA
most pythonic way equivalent for while next end what is the best python idiom for this construct while next end do not have the ability to recode next update and the answer from seems to be for in iter next end
it depends bit what you want to do to match your example as far as possible would make next generator and iterate over it def next for num in range yield num for in next print
QA
most pythonic way equivalent for while next end what is the best python idiom for this construct while next end do not have the ability to recode next update and the answer from seems to be for in iter next end
if you need to do this more than once the pythonic way would use an iterator for in iternext do something with where iternext would be defined using something like explicit is better than implicit def iternext next while end yield next
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
it has been really long time since did anything with filemaker pro but know that it does have capabilities for an odbc and jdbc connection to be made to it however do not know how or if that translates to the linux perl python world though this article shows how to share expose your filemaker data via odbc jdbc sharing filemaker pro data via odbc or jdbc from there if you are able to create an odbc jdbc connection you could query out data as needed
QA
accessing mp meta data with python what is the best way to retrieve mp metadata in python have seen couple frameworks out there but am unsure as to which would be the best to use any ideas
if you can use ironpython there is taglibsharp it can be used from any net language
QA
most pythonic way equivalent for while next end what is the best python idiom for this construct while next end do not have the ability to recode next update and the answer from seems to be for in iter next end
short answer there is no way to do inline variable assignment in while loop in python meaning that cannot say while next do something here since that is not possible there are number of idiomatically correct ways of doing this while next if end blah else break obviously this is kind of ugly you can also use one of the iterator approaches listed above but again that may not be ideal finally you can use the pita pocket approach that actually just found while googling class pita object slots pocket marker object def init self marker if is not self marker self pocket def call self marker if is not self marker self pocket return self pocket now you can do pita while next end do stuff with pocket thanks for this question learning about the call idiom was really cool edit would like to give credit where credit is due the pita pocket idiom was found here
QA
most pythonic way equivalent for while next end what is the best python idiom for this construct while next end do not have the ability to recode next update and the answer from seems to be for in iter next end
can you provide more information about what you are trying to accomplish it is not clear to me why you cannot just say for in everything and have the everything function return everything instead of writing next function to just return one thing at time generators can even do this quite efficiently
QA
pygame within pygtk application what is the best way to use pygame sdl within pygtk application am searching for method that allows me to have drawing area in the gtk window and at the same time being able to manage both gtk and sdl events
have never attempted it myself but hearing plenty about other people who have tried it is not road you want to go down there is the alternative of putting the gui in pygame itself there are plenty of gui toolkits built specifically for pygame that you could use most of them are rather unfinished but there are big actively maintained ones pgu and ocempgui the full list on the pygame site is here
QA
how to capture python interpreter and or cmd exe output from python script is it possible to capture python interpreter output from python script is it possible to capture windows cmd output from python script if so which librar ies should look into
actually you definitely can and it is beautiful ugly and crazy at the same time you can replace sys stdout and sys stderr with stringio objects that collect the output here is an example save it as evil py import sys import stringio stringio stringio sys stdout print hey this is not going to stdout at all print where is it sys stderr write it actually went to stringio object will show you now sys stderr write getvalue when you run this program you will see that nothing went to stdout where print usually prints to the first string that gets written to stderr is the one starting with it the next two lines are the ones that were collected in the stringio object replacing sys stdout err like this is an application of what is called monkeypatching opinions may vary whether or not this is supported and it is definitely an ugly hack but it has saved my bacon when trying to wrap around external stuff once or twice tested on linux not on windows but it should work just as well let me know if it works on windows
QA
how do create an xml document in python here is my sample code from xml dom minidom import def make xml doc document node doc createelement foo node innertext bar doc appendchild node return doc if name main make xml writexml sys stdout when run the above code get this xml version foo would like to get xml version foo bar foo just guessed that there was an innertext property it gives no compiler error but does not seem to work how do go about creating text node
setting an attribute on an object will not give compile time or run time error it will just do nothing useful if the object does not access it node nosuchattr bar would also not give an error unless you need specific feature of minidom would look at elementtree import sys from xml etree celementtree import element elementtree def make xml node element foo node text bar doc elementtree node return doc if name main make xml write sys stdout
QA
how do create an xml document in python here is my sample code from xml dom minidom import def make xml doc document node doc createelement foo node innertext bar doc appendchild node return doc if name main make xml writexml sys stdout when run the above code get this xml version foo would like to get xml version foo bar foo just guessed that there was an innertext property it gives no compiler error but does not seem to work how do go about creating text node
daniel thanks for the reply also figured out how to do it with the minidom am not sure of the difference between the elementtree vs the minidom from xml dom minidom import def make xml doc document node doc createelement foo node appendchild doc createtextnode bar doc appendchild node return doc if name main make xml writexml sys stdout swear tried this before posting my question
QA
how do create an xml document in python here is my sample code from xml dom minidom import def make xml doc document node doc createelement foo node innertext bar doc appendchild node return doc if name main make xml writexml sys stdout when run the above code get this xml version foo would like to get xml version foo bar foo just guessed that there was an innertext property it gives no compiler error but does not seem to work how do go about creating text node
found pretty verbose tutorial on the minidom method here is tutorial for the etree method it is much nicer to read and seems quite simple it also goes over parsing of xml briefly
QA
is safe eval really safe am looking for safe eval function to implement spreadsheet like calculations using numpy scipy the functionality to do this the rexec module has been removed from python since due to apparently unfixable security problems there are several third party hacks out there that purport to do this the most thought out solution that have found is this python cookbok recipe safe eval am reasonably safe if use this or something similar to protect from malicious code or am stuck with writing my own parser does anyone know of any better alternatives edit just discovered restrictedpython which is part of zope any opinions on this are welcome
although that code looks quite secure have always held the opinion that any sufficiently motivated person could break it given adequate time do think it will take quite bit of determination to get through that but am relatively sure it could be done
QA
python distutils does anyone know how to use it wrote quick program in python to add gtk gui to cli program was wondering how can create an installer using distutils since it is just gui frontend for command line app it only works in nix anyway so am not worried about it being cross platform my main goal is to create deb package for debian ubuntu users but do not understand make configure files have primarily been web developer up until now thanks for your help edit does anyone know of project that uses distutils so could see it in action and you know actually try building it here are few useful links ubuntu python packaging guide this guide is very helpful do not know how missed it during my initial wave of gooling it even walks you through packaging up an existing python application the ubuntu motu project this is the official package maintaining project at ubuntu anyone can join and there are lots of tutorials and info about creating packages of all types which include the above python packaging guide python distutils to deb ars technica forum discussion according to this conversation you cannot just use distutils it does not follow the debian packaging format or something like that guess that is why you need dh make as seen in the ubuntu packaging guide bdist deb command for distutils this one has some interesting discussion it is also how found the ubuntu guide about concatenating zip file and she will script to create some kind of universal executable anything with python and bash that is weird let me know if anyone finds more info on this practice because have never heard of it description of the deb format and how distutils fit in python mailing list
see the distutils simple example that is basically what it is like except real install scripts usually contain bit more information have not seen any that are fundamentally more complicated though in essence you just give it list of what needs to be installed sometimes you need to give it some mapping dicts since the source and installed trees might not be the same here is real life anonymized example usr bin python from distutils core import setup setup name initech package description services and libraries abc def author that guy initech ltd author email that guy initech com version package dir package site packages package packages package package queries data files etc package etc package externalresources conf
QA
what refactoring tools do you use for python have bunch of classes want to rename some of them have names that are small and that name is reused in other class names where do not want that name changed most of this lives in python code but we also have some xml code that references class names simple search and replace only gets me so far in my case want to rename adminaction to adminactionplug and adminactionlogger to adminactionloggerplug so the first one search and replace would also hit the second wrongly does anyone have experience with python refactoring tools bonus points if they can fix class names in the xml documents too
in the meantime have tried it two tools that have some sort of integration with vim the first is rope python refactoring library that comes with vim and emacs plug in tried it for few renames and that definitely worked as expected it allowed me to preview the refactoring as different which is nice it is bit text driven but that is alright for me just takes longer to learn the second is bicycle repair man which guess wins points on name also plugs into vim and emacs have not played much with it yet but remember trying it long time ago have not played with both enough yet or tried more types of refactoring but will do some more hacking with them
QA
python distutils does anyone know how to use it wrote quick program in python to add gtk gui to cli program was wondering how can create an installer using distutils since it is just gui frontend for command line app it only works in nix anyway so am not worried about it being cross platform my main goal is to create deb package for debian ubuntu users but do not understand make configure files have primarily been web developer up until now thanks for your help edit does anyone know of project that uses distutils so could see it in action and you know actually try building it here are few useful links ubuntu python packaging guide this guide is very helpful do not know how missed it during my initial wave of gooling it even walks you through packaging up an existing python application the ubuntu motu project this is the official package maintaining project at ubuntu anyone can join and there are lots of tutorials and info about creating packages of all types which include the above python packaging guide python distutils to deb ars technica forum discussion according to this conversation you cannot just use distutils it does not follow the debian packaging format or something like that guess that is why you need dh make as seen in the ubuntu packaging guide bdist deb command for distutils this one has some interesting discussion it is also how found the ubuntu guide about concatenating zip file and she will script to create some kind of universal executable anything with python and bash that is weird let me know if anyone finds more info on this practice because have never heard of it description of the deb format and how distutils fit in python mailing list
most python programs will use distutils django is one see http code djangoproject com svn django trunk setup py you should also read the documentation as it is very comprehensive and has some good examples
QA
install python to match directory layout in os the default python install on os is with fat bit intel and ppc client want to setup apache and mysql to run django in the past have run apache and mysql to match this install in bit mode even stripping out the bit stuff from apache to make it work want to upgrade python to bit am completely comfortable with compiling it from source with one caveat how to match the way that the default install is laid out especially with regards to site packages being in library python and not the one in buried at the top of the framework once compile it
not sure entirely understand your question but cannot you simply build and install bit version and then create symbolic links so that library python and below point to your freshly built version of python
QA
what is the best way to grab parse command line arguments passed to python script what is the easiest tersest and most flexible method or library for parsing python command line arguments
think the best way for larger projects is optparse but if you are looking for an easy way maybe http werkzeug pocoo org documentation script is something for you from werkzeug import script actions go here def action foo name action foo does foo pass def action bar id title default title action bar does bar pass if name main script run so basically every function action is exposed to the command line and nice help message is generated for free python foo py usage foo py action options foo py help actions bar action bar does bar id integer title string default title foo action foo does foo name string
QA
using in to match an attribute of python objects in an array do not remember whether was dreaming or not but seem to recall there being function which allowed something like foo in iter attr array of python objects attribute name have looked over the docs but this kind of thing does not fall under any obvious listed headers
you could always write one yourself def iterattr iterator attributename for obj in iterator yield getattr obj attributename will work with anything that iterates be it tuple list or whatever love python it makes stuff like this very simple and no more of hassle than neccessary and in use stuff like this is hugely elegant
QA
using in to match an attribute of python objects in an array do not remember whether was dreaming or not but seem to recall there being function which allowed something like foo in iter attr array of python objects attribute name have looked over the docs but this kind of thing does not fall under any obvious listed headers
if you plan on searching anything of remotely decent size your best bet is going to be to use dictionary or set otherwise you basically have to iterate through every element of the iterator until you get to the one you want if this is not necessarily performance sensitive code then the list comprehension way should work but note that it is fairly inefficient because it goes over every element of the iterator and then goes back over it again until it finds what it wants remember python has one of the most efficient hashing algorithms around use it to your advantage
QA
python distutils does anyone know how to use it wrote quick program in python to add gtk gui to cli program was wondering how can create an installer using distutils since it is just gui frontend for command line app it only works in nix anyway so am not worried about it being cross platform my main goal is to create deb package for debian ubuntu users but do not understand make configure files have primarily been web developer up until now thanks for your help edit does anyone know of project that uses distutils so could see it in action and you know actually try building it here are few useful links ubuntu python packaging guide this guide is very helpful do not know how missed it during my initial wave of gooling it even walks you through packaging up an existing python application the ubuntu motu project this is the official package maintaining project at ubuntu anyone can join and there are lots of tutorials and info about creating packages of all types which include the above python packaging guide python distutils to deb ars technica forum discussion according to this conversation you cannot just use distutils it does not follow the debian packaging format or something like that guess that is why you need dh make as seen in the ubuntu packaging guide bdist deb command for distutils this one has some interesting discussion it is also how found the ubuntu guide about concatenating zip file and she will script to create some kind of universal executable anything with python and bash that is weird let me know if anyone finds more info on this practice because have never heard of it description of the deb format and how distutils fit in python mailing list
distutils really is not all that difficult once you get the hang of it it is really just matter of putting in some meta information program name author version etc and then selecting what files you want to include for example here is sample distutils setup py module from decently complex python library kamaelia setup py note that this does not deal with any data files or or whatnot so ymmv on another note agree that the distutils documentation is probably some of python worst documentation it is extremely inclusive in some areas but neglects some really important information in others
QA
install python to match directory layout in os the default python install on os is with fat bit intel and ppc client want to setup apache and mysql to run django in the past have run apache and mysql to match this install in bit mode even stripping out the bit stuff from apache to make it work want to upgrade python to bit am completely comfortable with compiling it from source with one caveat how to match the way that the default install is laid out especially with regards to site packages being in library python and not the one in buried at the top of the framework once compile it
essentially yes was not sure you could do it like that current version does not do it like that when using the python install script however there is no option that can find to specify where to put directories and files eg prefix was hoping to match the current layout of python related files so as to avoid polluting my machine with redundant files
QA
how do threads work in python and what are common python threading specific pitfalls have been trying to wrap my head around how threads work in python and it is hard to find good information on how they operate may just be missing link or something but it seems like the official documentation is not very thorough on the subject and have not been able to find good write up from what can tell only one thread can be running at once and the active thread switches every instructions or so where is there good explanation or can you provide one it would also be very nice to be aware of common problems that you run into while using threads with python
below is basic threading sample it will spawn threads each thread will output its thread number run it and observe the order in which they print import threading class foo threading thread def init self self threading thread init self def run self print str self for in xrange foo start as you have hinted at python threads are implemented through time slicing this is how they get the parallel effect in my example my foo class extends thread then implement the run method which is where the code that you would like to run in thread goes to start the thread you call start on the thread object which will automatically invoke the run method of course this is just the very basics you will eventually want to learn about semaphores mutexes and locks for thread synchronization and message passing
QA
how do threads work in python and what are common python threading specific pitfalls have been trying to wrap my head around how threads work in python and it is hard to find good information on how they operate may just be missing link or something but it seems like the official documentation is not very thorough on the subject and have not been able to find good write up from what can tell only one thread can be running at once and the active thread switches every instructions or so where is there good explanation or can you provide one it would also be very nice to be aware of common problems that you run into while using threads with python
python fairly easy language to thread in but there are caveats the biggest thing you need to know about is the global interpreter lock this allows only one thread to access the interpreter this means two things you rarely ever find yourself using lock statement in python and if you want to take advantage of multi processor systems you have to use separate processes edit should also point out that you can put some of the code in if you want to get around the gil as well thus you need to re consider why you want to use threads if you want to parallelize your app to take advantage of dual core architecture you need to consider breaking your app up into multiple processes if you want to improve responsiveness you should consider using threads there are other alternatives though namely microthreading there are also some frameworks that you should look into stackless python greenlets gevent monocle
QA
install python to match directory layout in os the default python install on os is with fat bit intel and ppc client want to setup apache and mysql to run django in the past have run apache and mysql to match this install in bit mode even stripping out the bit stuff from apache to make it work want to upgrade python to bit am completely comfortable with compiling it from source with one caveat how to match the way that the default install is laid out especially with regards to site packages being in library python and not the one in buried at the top of the framework once compile it
personally would not worry about it until you see problem messing with the default python install on nix system can cause more trouble than it is worth can say from personal experience that you never truly understand what python has done for the nix world until you have problem with it you can also add second python installation but that also causes more problems than it is worth am going to so suppose the best question to start out with would be why exactly do you want to use the bit version of python
QA
how do threads work in python and what are common python threading specific pitfalls have been trying to wrap my head around how threads work in python and it is hard to find good information on how they operate may just be missing link or something but it seems like the official documentation is not very thorough on the subject and have not been able to find good write up from what can tell only one thread can be running at once and the active thread switches every instructions or so where is there good explanation or can you provide one it would also be very nice to be aware of common problems that you run into while using threads with python
yes because of the global interpreter lock gil there can only run one thread at time here are some links with some insights about this http www artima com weblogs viewpost jsp thread http smoothspan wordpress com guido is right to leave the gil in python not for multicore but for utility computing from the last link an interesting quote let me explain what all that means threads run inside the same virtual machine and hence run on the same physical machine processes can run on the same physical machine or in another physical machine if you architect your application around threads you ve done nothing to access multiple machines so you can scale to as many cores are on the single machine which will be quite few over time but to really reach web scales you ll need to solve the multiple machine problem anyway if you want to use multi core pyprocessing defines an process based api to do real parallelization the pep also includes some interesting benchmarks
QA
install python to match directory layout in os the default python install on os is with fat bit intel and ppc client want to setup apache and mysql to run django in the past have run apache and mysql to match this install in bit mode even stripping out the bit stuff from apache to make it work want to upgrade python to bit am completely comfortable with compiling it from source with one caveat how to match the way that the default install is laid out especially with regards to site packages being in library python and not the one in buried at the top of the framework once compile it
the short answer is because can the long answer expanding on what the op said is to be more compatible with apache and mysql postgresql they are all bit apache is fat binary with ppc ppc and and the others just straight bit mysqldb and mod python will not compile unless they are all running the same architecture yes could run them all in bit and have in the past but this is much more work then compiling one program edit you pretty much convinced though to just let the installer do its thing and update the path to reflect this
QA
how do threads work in python and what are common python threading specific pitfalls have been trying to wrap my head around how threads work in python and it is hard to find good information on how they operate may just be missing link or something but it seems like the official documentation is not very thorough on the subject and have not been able to find good write up from what can tell only one thread can be running at once and the active thread switches every instructions or so where is there good explanation or can you provide one it would also be very nice to be aware of common problems that you run into while using threads with python
use threads in python if the individual workers are doing bound operations if you are trying to scale across multiple cores on machine either find good ipc framework for python or pick different language
QA
install python to match directory layout in os the default python install on os is with fat bit intel and ppc client want to setup apache and mysql to run django in the past have run apache and mysql to match this install in bit mode even stripping out the bit stuff from apache to make it work want to upgrade python to bit am completely comfortable with compiling it from source with one caveat how to match the way that the default install is laid out especially with regards to site packages being in library python and not the one in buried at the top of the framework once compile it
hyposaurus it is possible to have multiple versions of python installed simultaneously installing two versions in parallel solves your problem and helps avoid the problems laid out by jason baker above the easiest way and the way recommend is to use macports which will install all its software separately by default for example everything is installed in opt local another method is to simply download the source and compile with specified prefix note that this method does not modify your path environment variable so you will need to do that yourself if you want to avoid typing the fully qualified path to the python executable each time configure prefix usr local python make sudo make install then you can simply point your apache install at the new version using mod python pythoninterpreter directive
QA
how can create directly executable cross platform gui app using python python works on multiple platforms and can be used for desktop and web applications thus conclude that there is some way to compile it into an executable for mac windows and linux the problem being have no idea where to start or how to write gui with it can anybody she would some light on this and point me in the right direction please
another system not mentioned in the accepted answer yet is pyinstaller which worked for pyqt project of mine when py exe would not found it easier to use http www pyinstaller org pyinstaller is based on gordon mcmillan python installer which is no longer available
QA
what is the best way to use web services in python have medium sized application that runs as net web service which do not control and want to create loose pythonic api above it to enable easy scripting wanted to know what is the best most practical solution for using web services in python edit need to consume complex soap ws and have no control over it
if have to expose apis prefer doing it as json python has excellent support for json objects json objects are infact python dictionaries
QA
pygame within pygtk application what is the best way to use pygame sdl within pygtk application am searching for method that allows me to have drawing area in the gtk window and at the same time being able to manage both gtk and sdl events
pygame works much better when it can manage its own window or even better use the whole screen gtk has flexible enough widgets to allow creation of drawing area this page may help though if you want to try it
QA
is safe eval really safe am looking for safe eval function to implement spreadsheet like calculations using numpy scipy the functionality to do this the rexec module has been removed from python since due to apparently unfixable security problems there are several third party hacks out there that purport to do this the most thought out solution that have found is this python cookbok recipe safe eval am reasonably safe if use this or something similar to protect from malicious code or am stuck with writing my own parser does anyone know of any better alternatives edit just discovered restrictedpython which is part of zope any opinions on this are welcome
daniel jinja implements sandboxe environment that may or may not be useful to you from what remember it does not yet comprehend list comprehensions sanbox info
QA
is safe eval really safe am looking for safe eval function to implement spreadsheet like calculations using numpy scipy the functionality to do this the rexec module has been removed from python since due to apparently unfixable security problems there are several third party hacks out there that purport to do this the most thought out solution that have found is this python cookbok recipe safe eval am reasonably safe if use this or something similar to protect from malicious code or am stuck with writing my own parser does anyone know of any better alternatives edit just discovered restrictedpython which is part of zope any opinions on this are welcome
depends on your definition of safe suppose lot of the security depends on what you pass in and what you are allowed to pass in the context for instance if file is passed in can open arbitrary files names open foo safe eval safe eval baz type baz names names baz open file baz mode at da furthermore the environment is very restricted you cannot pass in modules thus you cannot simply pass in module of utility functions like re or random on the other hand you do not need to write your own parser you could just write your own evaluator for the python ast import compiler ast compiler parse print hello world that way hopefully you could implement safe imports the other idea is to use jython or ironpython and take advantage of java net sandboxing capabilities
QA
how can render tree structure recursive using django template have tree structure in memory that would like to render in html using django template class node name node name children there will be some object root that is node and children is list of nodes root will be passed in the content of the template have found this one discussion of how this might be achieved but the poster suggests this might not be good in production environment does anybody know of better way
think the canonical answer is do not what you should probably do instead is unravel the thing in your view code so it is just matter of iterating over in de dents in the template think would do it by appending indents and dedents to list while recursing through the tree and then sending that travelogue list to the template the template would then insert li and li from that list creating the recursive structure with understanding it am also pretty sure recursively including template files is really wrong way to do it
QA
programmatically editing python source this is something that think would be very useful basically would like there to be way to edit python source programmatically without requiring human intervention there are couple of things would like to do with this edit the configuration of python apps that use source modules for configuration set up template so that can customize python source file on the fly this way can set up project system on an open source app am working on and allow certain files to be customized could probably write something that can do this myself but can see that opening up lot of devil in the details type issues are there any ways to do this currently or am just going to have to bite the bullet and implement it myself
python standard library provides pretty good facilities for working with python source note the tokenize and parser modules
QA
is it possible to run python script as service in windows if possible how am sketching the architecture for set of programs that share various interrelated objects stored in database want one of the programs to act as service which provides higher level interface for operations on these objects and the other programs to access the objects through that service am currently aiming for python and the django framework as the technologies to implement that service with am pretty sure figure how to demonize the python program in linux however it is an optional spec item that the system should support windows have little experience with windows programming and no experience at all with windows services is it possible to run python programs as windows service run it automatically without user login will not necessarily have to implement this part but need rough idea how it would be done in order to decide whether to design along these lines edit thanks for all the answers so far they are quite comprehensive would like to know one more thing how is windows aware of my service can manage it with the native windows utilities basically what is the equivalent of putting start stop script in etc init
yes you can do it using the pythoncom libraries that come included with activepython or can be installed with pywin python for windows extensions this is basic skeleton for simple service import win serviceutil import win service import win event import servicemanager import socket class appserversvc win serviceutil serviceframework svc name testservice svc display name test service def init self args win serviceutil serviceframework init self args self hwaitstop win event createevent none none socket setdefaulttimeout def svcstop self self reportservicestatus win service service stop pending win event setevent self hwaitstop def svcdorun self servicemanager logmsg servicemanager eventlog information type servicemanager pys service started self svc name self main def main self pass if name main win serviceutil handlecommandline appserversvc your code would go in the main method usually with some kind of infinite loop that might be interrumped by checking flag that you set in the svcstop method
QA
how can render tree structure recursive using django template have tree structure in memory that would like to render in html using django template class node name node name children there will be some object root that is node and children is list of nodes root will be passed in the content of the template have found this one discussion of how this might be achieved but the poster suggests this might not be good in production environment does anybody know of better way
this might be way more than you need but there is django module called mptt this stores hierarchical tree structure in an sql database and includes templates for display in the view code you might be able to find something useful there here is the link django mptt
QA
how to generate dynamic parametrized unit tests in python have some kind of test data and want to create an unit test for each item my first idea was to do it like this import unittest foo bar lee class testsequence unittest testcase def testsample self for name in print test name self assertequal if name main unittest main the downside of this is that it handles all data in one test would like to generate one test for each item on the fly any suggestions
use something like this import unittest foo bar lee class testsequense unittest testcase pass def test generator def test self self assertequal return test if name main for in test name test test test generator setattr testsequense test name test unittest main the nose parameterized package can be used to automate this process from nose parameterized import parameterized class testsequence unittest testcase parameterized expand foo bar lee def test sequence self name self assertequal which will generate the tests test sequence foo main testsequence ok test sequence bar main testsequence fail test sequence lee main testsequence ok fail test sequence bar main testsequence traceback most recent call last file usr local lib python site packages nose parameterized parameterized py line in lambda standalone func lambda func args kwargs file py line in test sequence self assertequal assertionerror
QA
programmatically editing python source this is something that think would be very useful basically would like there to be way to edit python source programmatically without requiring human intervention there are couple of things would like to do with this edit the configuration of python apps that use source modules for configuration set up template so that can customize python source file on the fly this way can set up project system on an open source app am working on and allow certain files to be customized could probably write something that can do this myself but can see that opening up lot of devil in the details type issues are there any ways to do this currently or am just going to have to bite the bullet and implement it myself
had the same issue and simply opened the file and did some replace then reload the file in the python interpreter this works fine and is easy to do otherwise afaik you have to use some conf objects
QA
ssh hangs when command invoked directly but exits cleanly when run interactive need to launch server on the remote machine and retrieve the port number that the server process is lsitening on when invoked the server will listen on random port and output the port number on stderr want to automate the process of logging on to the remote machine launching the process and retrieving the port number wrote python script called invokejob py that lives on the remote machine to act as wrapper that invokes the job and then returns the port number it looks like this import re subprocess executable name of executable regex regex to extract the port number from the output subprocess popen executable bufsize line buffered stderr subprocess pipe stderr readline port re match regex groups print port if log in interactively this script works ssh remotehost example com last login thu aug from localhost invokejob py exit logout connection to remotehost example com closed note successful logout it did not hang however if try to invoke it from the command line it just hangs ssh remotehost example com invokejob py does anybody know why it hangs in the second case and what can do to avoid this note that need to retrieve the output of the program so cannot just use the ssh flag or redirect standard output
stderr readline suspect it is the above line when you invoke command directly through ssh you do not get your full pty assuming linux and thus no stderr to read from when you log in interactively stdin stdout and stderr are set up for you and so your script works
QA
extending base classes in python am trying to extend some base classes in python class xlist list def len self return len self def add self args self extend args return none class xint int def add self value self value return self xlist print len ok print ok add print ok xint print ok add print not ok print type class main xint ok print type type int not ok it works fine in the list case because the append method modifies the object in place without returning it but in the int case the add method does not modify the value of the external variable suppose that is fine in the sense that self is local variable in the add method of the class but this is preventing me from modifying the initial value assigned to the instance of the class is it possible to extend class this way or should define class property with the base type and map all the needed methods to this property
ints are immutable and you cannot modify them in place so you should go with option because option is impossible without some trickery
QA
extending base classes in python am trying to extend some base classes in python class xlist list def len self return len self def add self args self extend args return none class xint int def add self value self value return self xlist print len ok print ok add print ok xint print ok add print not ok print type class main xint ok print type type int not ok it works fine in the list case because the append method modifies the object in place without returning it but in the int case the add method does not modify the value of the external variable suppose that is fine in the sense that self is local variable in the add method of the class but this is preventing me from modifying the initial value assigned to the instance of the class is it possible to extend class this way or should define class property with the base type and map all the needed methods to this property
int is value type so each time you do an assignment both instances of above it does not modify the object you have on the heap but replaces the reference with one of the result of the right hand side of the assignment an int list is not value type so it is not bound by the same rules this page has more details on the differences http docs python org ref objects html am going to yes you should define new class that keeps an int as an instance variable
QA
extending base classes in python am trying to extend some base classes in python class xlist list def len self return len self def add self args self extend args return none class xint int def add self value self value return self xlist print len ok print ok add print ok xint print ok add print not ok print type class main xint ok print type type int not ok it works fine in the list case because the append method modifies the object in place without returning it but in the int case the add method does not modify the value of the external variable suppose that is fine in the sense that self is local variable in the add method of the class but this is preventing me from modifying the initial value assigned to the instance of the class is it possible to extend class this way or should define class property with the base type and map all the needed methods to this property
your two xint examples do not work for two different reasons the first does not work because self value is equivalent to self self value which just reassigns the local variable self to different object an integer but does not change the original object you cannot really get this xint add to work with subclass of int since integers are immutable to get the second one to work you can define an add method like so class xint int def add self value return xint int add self value xint type class main xint type class main xint
QA
ssh hangs when command invoked directly but exits cleanly when run interactive need to launch server on the remote machine and retrieve the port number that the server process is lsitening on when invoked the server will listen on random port and output the port number on stderr want to automate the process of logging on to the remote machine launching the process and retrieving the port number wrote python script called invokejob py that lives on the remote machine to act as wrapper that invokes the job and then returns the port number it looks like this import re subprocess executable name of executable regex regex to extract the port number from the output subprocess popen executable bufsize line buffered stderr subprocess pipe stderr readline port re match regex groups print port if log in interactively this script works ssh remotehost example com last login thu aug from localhost invokejob py exit logout connection to remotehost example com closed note successful logout it did not hang however if try to invoke it from the command line it just hangs ssh remotehost example com invokejob py does anybody know why it hangs in the second case and what can do to avoid this note that need to retrieve the output of the program so cannot just use the ssh flag or redirect standard output
what if you do the following ssh remote host your command your regexp using awk or something for example ssh remote host your program ps aux awk root print this will connect to execute and then print each psid for any user root or any process with root in its description have used this method for running all kinds of commands on remote machines the catch is to wrap the command you wish to execute in single quotation marks and to separate each command with semi colon
QA
ssh hangs when command invoked directly but exits cleanly when run interactive need to launch server on the remote machine and retrieve the port number that the server process is lsitening on when invoked the server will listen on random port and output the port number on stderr want to automate the process of logging on to the remote machine launching the process and retrieving the port number wrote python script called invokejob py that lives on the remote machine to act as wrapper that invokes the job and then returns the port number it looks like this import re subprocess executable name of executable regex regex to extract the port number from the output subprocess popen executable bufsize line buffered stderr subprocess pipe stderr readline port re match regex groups print port if log in interactively this script works ssh remotehost example com last login thu aug from localhost invokejob py exit logout connection to remotehost example com closed note successful logout it did not hang however if try to invoke it from the command line it just hangs ssh remotehost example com invokejob py does anybody know why it hangs in the second case and what can do to avoid this note that need to retrieve the output of the program so cannot just use the ssh flag or redirect standard output
ben collins think you are right about stderr being an issue am pretty sure it is blocking on the readline call in the end gave up and decided to use the pxssh module from pexpect to automate my interaction with an ssh session misha unfortunately the semi colon trick does not work here it blocks on executing my program
QA
specifying mysql enum in django model how do go about specifying and using an enum in django model
using the choices parameter will not use the enum db type it will just create varchar or integer depending on whether you use choices with charfield or integerfield generally this is just fine if it is important to you that the enum type is used at the database level you have three options use manage py sql appname to see the sql django generates manually modify it to use the enum type and run it yourself if you create the table manually first manage py syncdb will not mess with it if you do not want to do this manually every time you generate your db put some custom sql in appname sql modelname sql to perform the appropriate alter table command create custom field type and define the db type method appropriately with any of these options it would be your responsibility to deal with the implications for cross database portability in option you could use database backend specific custom sql to ensure your alter table is only run on mysql in option your db type method would need to check the database engine and set the db column type to type that actually exists in that database update since the migrations framework was added in django options and above are entirely obsolete option was always the best option anyway the new version of options would involve complex custom migration using separatedatabaseandstate but really you want option
QA
class views in django django view points to function which can be problem if you want to change only bit of functionality yes could have million keyword arguments and even more if statements in the function but was thinking more of an object oriented approach for example have page that displays user this page is very similar to page that displays group but it is still not so similar to just use another data model group also has members etc one way would be to point views to class methods and then extend that class has anyone tried this approach or has any other idea
have created and used my own generic view classes defining call so an instance of the class is callable really like it while django generic views allow some customization through keyword arguments oo generic views if their behavior is split into number of separate methods can have much more fine grained customization via subclassing which let us me repeat myself lot less get tired of rewriting the same create update view logic anytime need to tweak something django generic views do not quite allow have posted some code at djangosnippets org the only real downside see is the proliferation of internal method calls which may impact performance somewhat do not think this is much of concern it is rare that python code execution would be your performance bottleneck in web app update django own generic views are now class based update fwiw have changed my opinion on class based views since this answer was written after having used them extensively on couple of projects feel they tend to lead to code that is satisfyingly dry to write but very hard to read and maintain later because functionality is spread across so many different places and subclasses are so dependent on every implementation detail of the superclasses and mixins now feel that templateresponse and view decorators is better answer for decomposing view code
QA
find out how much memory is being used by an object in python how would you go about finding out how much memory is being used by an object know it is possible to find out how much is used by block of code but not by an instantiated object anytime during its life which is what want
have not any personal experience with either of the following but simple search for python memory profiler yield pysizer memory profiler for python found at http pysizer org however the page seems to indicate that the project has not been updated for while and refers to heapy support ing debugging and optimization regarding memory related issues in python programs found at http guppy pe sourceforge net heapy hope that helps
QA
are python threads buggy reliable coder friend told me that python current multi threading implementation is seriously buggy enough to avoid using altogether what can said about this rumor
as far as know there are no real bugs but the performance when threading in cpython is really bad compared to most other threading implementations but usually good enough if all most of the threads do is block due to the gil global interpreter lock so really it is implementation specific rather than language specific jython for example does not suffer from this due to using the java thread model see this post on why it is not really feasible to remove the gil from the cpython implementation and this for some practical elaboration and workarounds do quick google for python gil for more information
QA
are python threads buggy reliable coder friend told me that python current multi threading implementation is seriously buggy enough to avoid using altogether what can said about this rumor
python threads are good for concurrent programming threads are swapped out of the cpu as soon as they block waiting for input from file network etc this allows other python threads to use the cpu while others wait this would allow you to write multi threaded web server or web crawler for example however python threads are serialized by the gil when they enter interpreter core this means that if two threads are crunching numbers only one can run at any given moment it also means that you cannot take advantage of multi core or multi processor architectures there are solutions like running multiple python interpreters concurrently using based threading library this is not for the faint of heart and the benefits might not be worth the trouble let us hope for an all python solution in future release
QA
are python threads buggy reliable coder friend told me that python current multi threading implementation is seriously buggy enough to avoid using altogether what can said about this rumor
the gil global interpreter lock might be problem but the api is quite ok try out the excellent processing module which implements the threading api for separate processes am using that right now albeit on os have yet to do some testing on windows and am really impressed the queue class is really saving my bacon in terms of managing complexity edit it seemes the processing module is being included in the standard library as of version import multiprocessing joy
QA
how to generate dynamic parametrized unit tests in python have some kind of test data and want to create an unit test for each item my first idea was to do it like this import unittest foo bar lee class testsequence unittest testcase def testsample self for name in print test name self assertequal if name main unittest main the downside of this is that it handles all data in one test would like to generate one test for each item on the fly any suggestions
the nose testing framework supports this example the code below is the entire contents of the file containing the test param list def test generator for params in param list yield check em params params def check em assert the output of the nosetests command nosetests testgen test generator ok testgen test generator fail testgen test generator ok fail testgen test generator traceback most recent call last file usr lib python site packages nose py egg nose case py line in runtest self test self arg file testgen py line in check em assert assertionerror ran tests in failed failures
QA
how to specify an authenticated proxy for python http connection what is the best way to specify proxy with username and password for an http connection in python
this works for me import urllib proxy urllib proxyhandler http http username password proxyurl proxyport auth urllib httpbasicauthhandler opener urllib build opener proxy auth urllib httphandler urllib install opener opener conn urllib urlopen http python org return str conn read
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
have not heard of direct equivalent either you could probably achieve the same effect with macros especially in language like lisp which has extremely powerful macros would not be at all surprised if other languages start to incorporate something similar because it is so powerful
QA
how do make windows aware of service have written in python in another question posted yesterday got very good advice on how python script could be run as service in windows what am left wondering is how is windows aware of the services that can be managed in the native tools services window in administrative tools what is the windows equivalent of putting start stop script in etc init under linux
here is code to install python script as service written in python http code activestate com recipes this post could also help you out http essiene blogspot com python windows services html
QA
django imagefield core false in newforms admin in the transition to newforms admin am having difficulty figuring out how specify core false for imagefields get the following error typeerror init got an unexpected keyword argument core edit however by just removing the core argument get this field is required error in the admin interface on attempted submission how does one accomplish what core false is meant to do using newforms admin
this is simple started getting this problems few revisions ago basically just remove the core true parameter in the imagefield in the models and then follow the instructions here to convert to what the newforms admin uses
QA
how do make windows aware of service have written in python in another question posted yesterday got very good advice on how python script could be run as service in windows what am left wondering is how is windows aware of the services that can be managed in the native tools services window in administrative tools what is the windows equivalent of putting start stop script in etc init under linux
as with most aware things in windows the answer is registry take look at this microsoft knowledge base article http support microsoft com kb search for win program that can be started by the service controller and that obeys the service control protocol this is the kind of service you are interested in the service registration contents of key local machine system currentcontrolset services myservice carries information about the service including things like its executable location what to do when it fails halt the os what services must be started before this one what user it runs as as to service control protocol main of your program is supposed to invoke windows api call setting up callbacks for start stop pause for your service what you do in those callbacks is all up to you
QA
how do make windows aware of service have written in python in another question posted yesterday got very good advice on how python script could be run as service in windows what am left wondering is how is windows aware of the services that can be managed in the native tools services window in administrative tools what is the windows equivalent of putting start stop script in etc init under linux
you can use srvany exe from windows nt resource kit to create user defined service that will show up in the admin tools http support microsoft com kb am using this method to run tracd python script server for trac here are some very clear instructions http www tacktech com display cfm ttid it does require some registry editing very minimal and easy but will allow you to make any command line script windows service
QA
finding what methods an object has given python object of any kind is there an easy way to get list of all methods that this object has or if this is not possible is there at least an easy way to check if it has particular method other than simply checking if an error occurs when the method is called
it appears you can use this code replacing object with the object you are interested in method for method in dir object if callable getattr object method discovered it at this site hopefully that should provide some further detail
QA
finding what methods an object has given python object of any kind is there an easy way to get list of all methods that this object has or if this is not possible is there at least an easy way to check if it has particular method other than simply checking if an error occurs when the method is called
you can use the built in dir function to get list of all the attributes module has try this at the command line to see how it works import modulename dir modulename also you can use the hasattr module name attr name function to find out if module has specific attribute see the guide to python introspection for more information
QA
finding what methods an object has given python object of any kind is there an easy way to get list of all methods that this object has or if this is not possible is there at least an easy way to check if it has particular method other than simply checking if an error occurs when the method is called
to check if it has particular method hasattr object method
QA
finding what methods an object has given python object of any kind is there an easy way to get list of all methods that this object has or if this is not possible is there at least an easy way to check if it has particular method other than simply checking if an error occurs when the method is called
on top of the more direct answers would be remiss if did not mention ipython hit tab to see the available methods with autocompletion and once you have found method try help object method to see the pydocs method signature etc ahh repl
QA
python sound bell would like to have python program alert me when it has completed its task by making beep noise currently use import os and then use command line speech program to say process complete much rather it be simple bell know that there is function that can be used in cocoa apps nsbeep but do not think that has much anything to do with this have also tried print but that did not work am using mac if you could not tell by my cocoa comment so that may help thanks
if you have pyobjc the python objective bridge installed or are running on os system python which ships with pyobjc you can do from appkit import nsbeep nsbeep to play the system alert
QA
are python threads buggy reliable coder friend told me that python current multi threading implementation is seriously buggy enough to avoid using altogether what can said about this rumor
the standard implementation of python generally known as cpython as it is written in uses os threads but since there is the global interpreter lock only one thread at time is allowed to run python code but within those limitations the threading libraries are robust and widely used if you want to be able to use multiple cpu cores there are few options one is to use multiple python interpreters concurrently as mentioned by others another option is to use different implementation of python that does not use gil the two main options are jython and ironpython jython is written in java and is now fairly mature though some incompatibilities remain for example the web framework django does not run perfectly yet but is getting closer all the time jython is great for thread safety comes out better in benchmarks and has cheeky message for those wanting the gil ironpython uses the net framework and is written in compatibility is reaching the stage where django can run on ironpython at least as demo and there are guides to using threads in ironpython
QA
django imagefield core false in newforms admin in the transition to newforms admin am having difficulty figuring out how specify core false for imagefields get the following error typeerror init got an unexpected keyword argument core edit however by just removing the core argument get this field is required error in the admin interface on attempted submission how does one accomplish what core false is meant to do using newforms admin
the core attribute is not used anymore from brian rosner blog you can safely just remove any and all core arguments they are no longer used newforms admin now provides nice delete checkbox for exisiting instances in inlines
QA
scaffolding in pylons is there anything similar to rails scaffolding fo pylons have been poking around google but fofund only this thing caled dbsprockets which is fine although probably way to much for my needs what really need is basic crud thas is based on the sqlalchemy model
hear you have followed the pylons mailing list for while looking for something similar there have been some attempts in the past see adminpylon and restin but none have really kept up with sqlalchemy rapidly developing orm api since dbsprockets is likely to be incorporated into turbogears it will likely be maintained would bite the bullet and go with that
QA
python super class reflection if have python code class pass class pass class pass and have class is there way to iterate through it is super classed and something like pseudocode magicgetsuperclasses type type one solution seems to be inspect module and getclasstree function def magicgetsuperclasses cls return for in inspect getclasstree cls if type type but is this pythonian way to achieve the goal
john your snippet does not work you are returning the class of the base classes which are also known as metaclasses you really just want cls bases class pass class pass class pass instance assert bases works assert class bases works def magicgetsuperclasses clz return tuple base class for base in clz bases assert magicgetsuperclasses fails also if you are using python you can use generator expressions instead of creating list via then turning it into tuple via tuple for example def get base metaclasses cls returns the metaclass of all the base classes of cls return tuple base class for base in clz bases that is somewhat confusing example but genexps are generally easy and cool
QA
how to specify an authenticated proxy for python http connection what is the best way to specify proxy with username and password for an http connection in python
the best way of going through proxy that requires authentication is using urllib to build custom url opener then using that to make all the requests you want to go through the proxy note in particular you probably do not want to embed the proxy password in the url or the python source code unless it is just quick hack import urllib def get proxy opener proxyurl proxyuser proxypass proxyscheme http password mgr urllib httppasswordmgrwithdefaultrealm password mgr add password none proxyurl proxyuser proxypass proxy handler urllib proxyhandler proxyscheme proxyurl proxy auth handler urllib proxybasicauthhandler password mgr return urllib build opener proxy handler proxy auth handler if name main import sys if len sys argv url opener get proxy opener sys argv for url in sys argv print url opener open url headers else print usage sys argv proxy user pass fetchurls in more complex program you can seperate these components out as appropriate for instance only using one password manager for the lifetime of the application the python documentation has more examples on how to do complex things with urllib that you might also find useful
QA
validate html in python what is the best way to go about validating that document follows some version of html prefereably that can specify would like to be able to know where the failures occur as in web based validator except in native python app
xhtml is easy use lxml html is harder since there is traditionally not been as much interest in validation among the html crowd run stackoverflow itself through validator yikes the easiest solution would be to execute external applications such as nsgmls or openjade and then parse their output
QA
validate html in python what is the best way to go about validating that document follows some version of html prefereably that can specify would like to be able to know where the failures occur as in web based validator except in native python app
think that html tidy will do what you want there is python binding for it
QA
validate html in python what is the best way to go about validating that document follows some version of html prefereably that can specify would like to be able to know where the failures occur as in web based validator except in native python app
try tidylib you can get some really basic bindings as part of the elementtidy module builds elementtrees from html documents http effbot org downloads elementtidy import elementtidy xhtml log elementtidy fixup html html print log line column warning missing doctype declaration line column warning discarding unexpected html line column warning inserting missing title element parsing the log should give you pretty much everything you need
QA
why does python iter on mapping return iterkeys instead of iteritems it seems like if you want to get the keys of mapping you ask for them otherwise give me the whole mapping constituted by set of key value pairs is there historical reason for this
check out this thread for discussion on the reasons behind this behavior including that guido likes it and it is not likely to change
QA
django imagefield core false in newforms admin in the transition to newforms admin am having difficulty figuring out how specify core false for imagefields get the following error typeerror init got an unexpected keyword argument core edit however by just removing the core argument get this field is required error in the admin interface on attempted submission how does one accomplish what core false is meant to do using newforms admin
to get rid of this field is required you need to make it not required by using blank true and possibly null true as well if it is not charfield
QA
ruby is equivalent is there ruby equivalent for python is it tests whether two objects are identical have the same memory location
use equal http www ruby doc org core classes object html unlike the equal method should never be overridden by subclasses it is used to determine object identity that is equal iff is the same object as
QA
find out how much memory is being used by an object in python how would you go about finding out how much memory is being used by an object know it is possible to find out how much is used by block of code but not by an instantiated object anytime during its life which is what want
there is no easy way to find out the memory size of python object one of the problems you may find is that python objects like lists and dicts may have references to other python objects in this case what would your size be the size containing the size of each object or not there are some pointers overhead and internal structures related to object types and garbage collection finally some python objects have non obvious behaviors for instance lists reserve space for more objects than they have most of the time dicts are even more complicated since they can operate in different ways they have different implementation for small number of keys and sometimes they over allocate entries there is big chunk of code and an updated big chunk of code out there to try to best approximate the size of python object in memory there is also some simpler approximations but they will always be approximations you may also want to check some old description about pyobject the internal struct that represents virtually all python objects
QA
how can graph the lines of code history for git repo basically want to get the number of lines of code in the repository after each commit the only really crappy ways have found is to use git filter branch to run wc and script that run git reset hard on each commit then ran wc to make it bit clearer when the tool is run it would output the lines of code of the very first commit then the second and so on this is what want the tool to output as an example me something gitsloc branch master have played around with the ruby git library but the closest found was using the lines method on different which seems like it should give the added lines but does not it returns when you delete lines for example require rubygems require git total git open working dir users dbr desktop code projects tvdb api last nil log each do cur different different last cur total total different lines puts total last cur end
you may get both added and removed lines with git log like git log shortstat reverse pretty oneline from this you can write similar script to the one you did using this info in python usr bin python display the per commit size of the current git branch import subprocess import re import sys def main argv git subprocess popen git log shortstat reverse pretty oneline stdout subprocess pipe out err git communicate total files total insertions total deletions for line in out split if not line continue if line this is description line hash desc line split else this is stat line data re findall files changed insertions deletions line files insertions deletions int for in data total files files total insertions insertions total deletions deletions print files lines hash total files total insertions total deletions if name main sys exit main sys argv
QA
how do content discovery engines like zemanta and open calais work was wondering how as semantic service like open calais figures out the names of companies or people tech concepts keywords etc from piece of text is it because they have large database that they match the text against how would service like zemanta know what images to suggest to piece of text for instance
am not familiar with the specific services listed but the field of natural language processing has developed number of techniques that enable this sort of information extraction from general text as sean stated once you have candidate terms it is not to difficult to search for those terms with some of the other entities in context and then use the results of that search to determine how confident you are that the term extracted is an actual entity of interest opennlp is great project if you would like to play around with natural language processing the capabilities you have named would probably be best accomplished with named entity recognizers ner algorithms that locate proper nouns generally and sometimes dates as well and or word sense disambiguation wsd eg the word bank has different meanings depending on it is context and that can be very important when extracting information from text given the sentences the plane banked left the snow bank was high and they robbed the bank you can see how dissambiguation can play an important part in language understanding techniques generally build on each other and ner is one of the more complex tasks so to do ner successfully you will generally need accurate tokenizers natural language tokenizers mind you statistical approaches tend to fare the best string stemmers algorithms that conflate similar words to common roots so words like informant and informer are treated equally sentence detection mr jones was tall is only one sentence so you cannot just check for punctuation part of speech taggers pos taggers and wsd there is python port of parts of opennlp called nltk http nltk sourceforge net but do not have much experience with it yet most of my work has been with the java and ports which work well all of these algorithms are language specific of course and they can take significant time to run although it is generally faster than reading the material you are processing since the state of the art is largely based on statistical techniques there is also considerable error rate to take into account furthermore because the error rate impacts all the stages and something like ner requires numerous stages of processing tokenize sentence detect pos tag wsd ner the error rates compound
QA
is python good for big software projects not web based right now am developing mostly in but wrote some small utilities in python to automatize some tasks and really love it as language especially the productivity except for the performances problem that could be sometimes solved thanks to the ease of interfacing python with modules do you think it is proper for production use in the development of stand alone complex applications think for example to word processor or graphic tool what ide would you suggest the idle provided with python is not enough even for small projects in my opinion
in my opinion python is more than ready for developing complex applications see pythons strength more on the server side than writing graphical clients but have look at http www resolversystems com they develop whole spreadsheet in python using the net ironpython port if you are familiar with eclipse have look at pydev which provides auto completion and debugging support for python with all the other eclipse goodies like svn support the guy developing it has just been bought by aptana so this will be solid choice for the future marcin cons as dynamic language has way worse ide support proper syntax completion requires static typing whether explicit in java or inferred in sml you are right that static analysis may not provide full syntax completion for dynamic languages but thing pydev gets the job done very well further more have different development style when programming python have always an ipython session open and with one do not only get the perfect completion from ipython but object introspection and manipulation as well but if you want to write second google or yahoo you will be much better with or java google just rewrote jaiku to work on top of app engine all in python and as far as know they use lot of python inside google too
QA
is python good for big software projects not web based right now am developing mostly in but wrote some small utilities in python to automatize some tasks and really love it as language especially the productivity except for the performances problem that could be sometimes solved thanks to the ease of interfacing python with modules do you think it is proper for production use in the development of stand alone complex applications think for example to word processor or graphic tool what ide would you suggest the idle provided with python is not enough even for small projects in my opinion
really like python it is usually my language of choice these days for small non gui stuff that do on my own however for some larger python projects have tackled am finding that it is not quite the same as programming in say was working on language parser and needed to represent an ast in python this is certainly within the scope of what python can do but had bit of trouble with some refactoring was changing the representation of my ast and changing methods and classes around lot and found missed the strong typing that would be available to me in solution python duck typing was almost too flexible and found myself adding lot of assert code to try to check my types as the program ran and then could not really be sure that everything was properly typed unless had code coverage testing which did not at the time actually that is another thing that miss sometimes it is possible to write syntactically correct code in python that simply will not run the compiler is incapable of telling you about it until it actually executes the code so in infrequently used code paths such as error handlers you can easily have unseen bugs lurking around even code that is as simple as printing an error message with format string can fail at runtime because of mismatched types have not used python for any gui stuff so cannot comment on that aspect
QA
is python good for big software projects not web based right now am developing mostly in but wrote some small utilities in python to automatize some tasks and really love it as language especially the productivity except for the performances problem that could be sometimes solved thanks to the ease of interfacing python with modules do you think it is proper for production use in the development of stand alone complex applications think for example to word processor or graphic tool what ide would you suggest the idle provided with python is not enough even for small projects in my opinion
python is considered among python programmers to be great language for rapid prototyping there is not lot of extraneous syntax getting in the way of your thought processes so most of the work you do tends to go into the code there is far less idioms required to be involved in writing good python code than in writing good given this most python cpython programmers ascribe to the premature optimization is the root of all evil philosophy by writing high level and significantly slower python code one can optimize the bottlenecks out using bindings when your application is nearing completion at this point it becomes more clear what your processor intensive algorithms are through proper profiling this way you write most of the code in very readable and maintainable manner while allowing for speedups down the road you will see several python library modules written in for this very reason most graphics libraries in python wxpython are just python wrappers around libraries anyway so you are pretty much writing to backend to address your ide question spe stani python editor is good ide that have used and eclipse with pydev gets the job done as well both are oss so they are free to try edit marcin have you had experience writing loc in python it is also funny that you should mention google scalability concerns since they are python biggest supporters also small organization called nasa also uses python frequently see one coder and lines of code later
QA
is python good for big software projects not web based right now am developing mostly in but wrote some small utilities in python to automatize some tasks and really love it as language especially the productivity except for the performances problem that could be sometimes solved thanks to the ease of interfacing python with modules do you think it is proper for production use in the development of stand alone complex applications think for example to word processor or graphic tool what ide would you suggest the idle provided with python is not enough even for small projects in my opinion
you will find mostly two answers to that the religous one yes of course it is the best language ever and the other religious one you got to be kidding me python no it is not mature enough will maybe skip the last religion python use ruby the truth as always is far from obvious pros it is easy readable batteries included has lots of good libraries for pretty much everything it is expressive and dynamic typing makes it more concise in many cases cons as dynamic language has way worse ide support proper syntax completion requires static typing whether explicit in java or inferred in sml its object system is far from perfect interfaces anyone and it is easy to end up with messy code that has methods returning either int or boolean or object or some sort under unknown circumstances my take love python for scripting automation tiny webapps and other simple well defined tasks in my opinion it is by far the best dynamic language on the planet that said would never use it any dynamically typed language to develop an application of substantial size say it would be fine to use it for stack overflow which has three developers and guess no more than lines of code for bigger things first your development would be super fast and then once team and codebase grow things are slowing down more than they would with java or you need to offset lack of compilation time checks by writing more unittests refactorings get harder because you never know what your refacoring broke until you run all tests or even the whole big app etc now decide on how big your team is going to be and how big the app is supposed to be once it is done if you have or less people and the target size is roughly stack overflow go ahead write in python you will finish in no time and be happy with good codebase but if you want to write second google or yahoo you will be much better with or java side note on you have mentioned if you are not writing performance critical software say massive parallel raytracer that will run for three months rendering film or very mission critical system say mars lander that will fly three years straight and has only one chance to land right or you lose mln do not use it for web apps most desktop apps most apps in general it is not good choice you will die debugging pointers and memory allocation in complex business logic
QA
programmatically editing python source this is something that think would be very useful basically would like there to be way to edit python source programmatically without requiring human intervention there are couple of things would like to do with this edit the configuration of python apps that use source modules for configuration set up template so that can customize python source file on the fly this way can set up project system on an open source app am working on and allow certain files to be customized could probably write something that can do this myself but can see that opening up lot of devil in the details type issues are there any ways to do this currently or am just going to have to bite the bullet and implement it myself
most of these kinds of things can be determined programatically in python using modules like sys os and the special identifier which tells you where you are in the filesystem path it is important to keep in mind that when module is first imported it will execute everything in the file scope which is important for developing system dependent behaviors for example the os module basically determines what operating system you are using on import and then adjusts its implementation accordingly by importing another module corresponding to linux osx windows etc there is lot of power in this feature and something along these lines is probably what you are looking for edit have also used socket gethostname in some rare hackish instances