prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
how to build tagging support using couchdb am using the following view function to iterate over all items in the database in order to find tag but think the performance is very poor if the dataset is large any other approach def by tag tag return function doc if doc tags length for var tag in doc tags if doc tags tag emit doc published doc tag
you are very much on the right track with the view list of thoughts though view generation is incremental if you are read traffic is greater than you are write traffic then your views will not because an issue at all people that are concerned about this generally should not be frame of reference you should be worried if you are dumping hundreds of records into the view without an update emitting an entire document will slow things down you should only emit what is necessary for use of the view not sure what the val performance would be but you should not over think things if there is tag array you should emit the tags granted if you expect tags array that will contain non strings then ignore this
QA
python inverse of matrix how do get the inverse of matrix in python have implemented it myself but it is pure python and suspect there are faster modules out there to do it
you should have look at numpy if you do matrix manipulation this is module mainly written in which will be much faster than programming in pure python here is an example of how to invert matrix and do other matrix manipulation from numpy import matrix from numpy import linalg matrix creates matrix matrix creates matrix like column vector matrix creates matrix like row vector print transpose of print matrix multiplication of and print inverse of print linalg solve solve the linear equation system you can also have look at the array module which is much more efficient implementation of lists when you have to deal with only one data type
QA
how to read and write multiple files want to write program for this in folder have number of files first read one file and perform some operation then store result in separate file then read nd file perform operation again and save result in new nd file do the same procedure for number of files the program reads all files one by one and stores results of each file separately please give examples how can do it
have just learned of the os walk command recently and it may help you here it allows you to walk down directory tree structure import os output dir results for path dirs files in os walk for file in files read open os join path file write open os path join output dir file do stuff
QA
need some help with cursor event handling in python tkinter am building code in which would like to be able to generate an event when the user changes the focus of the cursor from an entry widget to anywhere for example another entry widget button so far only came out with the idea to bind to tab and mouse click although if bind the mouse click to the entry widget only get mouse events when inside the entry widget how can accomplish to generate events for when widget loses cursor focus any help will be much appreciated thanks in advance william
this is not specific to tkinter and it is not focus based but got an answer to similar question here http stackoverflow com questions detecting mouse clicks in windows using python have not done any tkinter in quite while but there seems to be focusin and focusout events you might be able to bind and track these to solve your issue from http effbot org tkinterbook tkinter events and bindings htm
QA
is it possible to compile python natively beyond pyc byte code wonder if it is possible to create an executable module from python script need to have the most performance and the flexibility of python script without needing to run in the python environment would use this code to load on demand user modules to customize my application
have had lot of success using cython which is based on and extends pyrex cython is language that makes writing extensions for the python language as easy as python itself cython is based on the well known pyrex but supports more cutting edge functionality and optimizations the cython language is very close to the python language but cython additionally supports calling functions and declaring types on variables and class attributes this allows the compiler to generate very efficient code from cython code this makes cython the ideal language for wrapping for external libraries and for fast modules that speed up the execution of python code
QA
create an icon in memory with win in python what is good way to generate an icon in memory in python right now am forced to use pygame to draw the icon then save it to disk as an ico file and then load it from disk as an ico resource something like this if os path isfile self icon icon flags win con lr loadfromfile win con lr defaultsize hicon win gui loadimage hinst self icon win con image icon icon flags where self icon is the filename of the icon created is there any way to do this in memory edit all want to do is create an icon with digit number displayed on it weather taskbar style
you can use wxpython for this from wx import emptyicon icon emptyicon icon copyfrombitmap your wxbitmap the wxbitmap can be generated in memory using wxmemorydc look here for operations you can do on dc this icon can then be applied to wxframe window or wxtaskbaricon using frame seticon icon
QA
python unsigned bit bitwise arithmetic trying to answer to another post whose solution deals with ip addresses and netmasks got stuck with plain bitwise arithmetic is there standard way in python to carry on bitwise and or xor not operations assuming that the inputs are bit maybe negative integers or longs and that the result must be long in the range in other words need working python counterpart to the bitwise operations between unsigned longs edit the specific issue is this xffffff netmask wtf want
this is module that created long time ago and it might be of help to you ipv utils it provides at least cidr class with subnet arithmetic check the test cases at the end of the module for examples
QA
arguments to cryptographic functions am bit confused that the argument to crypto functions is string should simply wrap non string arguments with str hashlib sha str user id str expiry time hmac new str random randbits ignore for the moment that random randbits might not be cryptographically good edit realise that the hmac example is silly because am not storing the key anywhere
you can however for the hmac you actually want to store the key somewhere without the key there is no way for you to verify the hash value later
QA
arguments to cryptographic functions am bit confused that the argument to crypto functions is string should simply wrap non string arguments with str hashlib sha str user id str expiry time hmac new str random randbits ignore for the moment that random randbits might not be cryptographically good edit realise that the hmac example is silly because am not storing the key anywhere
well usually hash functions and cryptographic functions generally work on bytes the python strings are basically byte strings if you want to compute the hash of some object you have to convert it to string representation just make sure to apply the same operation later if you want to check if the hash is correct and make sure that your string representation does not contain any changing data that you do not want to be checked edit due to popular request short reminder that python unicode strings do not contain bytes but unicode code points each unicode code point contains multiple bytes or depending on how the python interpreter was compiled python strings only contain bytes so python strings type str are the type most similar to an array of bytes
QA
using sqlite in python program have created python module that creates and populates several sqlite tables now want to use it in program but do not really know how to call it properly all the tutorials have found are essentially inline they walk through using sqlite in linear fashion rather than how to actually use it in production what am trying to do is have method check to see if the database is already created if so then can use it if not an exception is raised and the program will create the database or use if else statements whichever is better created test script to see if my logic is correct but it is not working when create the try statement it just creates new database rather than checking if one already exists the next time run the script get an error that the table already exists even if tried catching the exception have not used try except before but figured this is good time to learn are there any good tutorials for using sqlite operationally or any suggestions on how to code this have looked through the pysqlite tutorial and others found but they do not address this
afaik an sqlite database is just file to check if the database exists check for file existence when you open sqlite database it will automatically create one if the file that backs it up is not in place if you try and open file as sqlite database that is not database you will get this sqlite databaseerror file is encrypted or is not database so check to see if the file exists and also make sure to try and catch the exception in case the file is not sqlite database
QA
using sqlite in python program have created python module that creates and populates several sqlite tables now want to use it in program but do not really know how to call it properly all the tutorials have found are essentially inline they walk through using sqlite in linear fashion rather than how to actually use it in production what am trying to do is have method check to see if the database is already created if so then can use it if not an exception is raised and the program will create the database or use if else statements whichever is better created test script to see if my logic is correct but it is not working when create the try statement it just creates new database rather than checking if one already exists the next time run the script get an error that the table already exists even if tried catching the exception have not used try except before but figured this is good time to learn are there any good tutorials for using sqlite operationally or any suggestions on how to code this have looked through the pysqlite tutorial and others found but they do not address this
doing sql in overall is horrible in any language have picked up sqlalchemy has shown to be easiest from them to use because actual query and committing with it is so clean and absent from troubles here is some basic steps on actually using sqlalchemy in your app better details can be found from the documentation provide table definitions and create orm mappings load database ask it to create tables from the definitions will not do so if they exist create session maker optional create session after creating session you can commit and query from the database
QA
using sqlite in python program have created python module that creates and populates several sqlite tables now want to use it in program but do not really know how to call it properly all the tutorials have found are essentially inline they walk through using sqlite in linear fashion rather than how to actually use it in production what am trying to do is have method check to see if the database is already created if so then can use it if not an exception is raised and the program will create the database or use if else statements whichever is better created test script to see if my logic is correct but it is not working when create the try statement it just creates new database rather than checking if one already exists the next time run the script get an error that the table already exists even if tried catching the exception have not used try except before but figured this is good time to learn are there any good tutorials for using sqlite operationally or any suggestions on how to code this have looked through the pysqlite tutorial and others found but they do not address this
sqlite does not throw an exception if you create new database with the same name it will just connect to it since sqlite is file based database suggest you just check for the existence of the file about your second problem to check if table has been already created just catch the exception an exception sqlite operationalerror table test already exists is thrown if the table already exist import sqlite import os database name newdb db if not os path isfile database name print the database already exist db connection sqlite connect database name db cursor db connection cursor try db cursor execute create table test integer except sqlite operationalerror message print message
QA
using sqlite in python program have created python module that creates and populates several sqlite tables now want to use it in program but do not really know how to call it properly all the tutorials have found are essentially inline they walk through using sqlite in linear fashion rather than how to actually use it in production what am trying to do is have method check to see if the database is already created if so then can use it if not an exception is raised and the program will create the database or use if else statements whichever is better created test script to see if my logic is correct but it is not working when create the try statement it just creates new database rather than checking if one already exists the next time run the script get an error that the table already exists even if tried catching the exception have not used try except before but figured this is good time to learn are there any good tutorials for using sqlite operationally or any suggestions on how to code this have looked through the pysqlite tutorial and others found but they do not address this
as diciu pointed out the database file will be created by sqlite connect if you want to take special action when the file is not there you will have to explicitly check for existance import os import sqlite if not os path exists mydb path create new db create table stocks con sqlite connect mydb path con execute create table stocks date text trans text symbol text qty real price real else use existing db con sqlite connect mydb path
QA
using sqlite in python program have created python module that creates and populates several sqlite tables now want to use it in program but do not really know how to call it properly all the tutorials have found are essentially inline they walk through using sqlite in linear fashion rather than how to actually use it in production what am trying to do is have method check to see if the database is already created if so then can use it if not an exception is raised and the program will create the database or use if else statements whichever is better created test script to see if my logic is correct but it is not working when create the try statement it just creates new database rather than checking if one already exists the next time run the script get an error that the table already exists even if tried catching the exception have not used try except before but figured this is good time to learn are there any good tutorials for using sqlite operationally or any suggestions on how to code this have looked through the pysqlite tutorial and others found but they do not address this
sqlite automatically creates the database file the first time you try to use it the sql statements for creating tables can use if not exists to make the commands only take effect if the table has not been created this way you do not need to check for the database existence beforehand sqlite can take care of that for you the main thing would still be worried about is that executing create table if exists for every web transaction say would be inefficient you can avoid that by having the program keep an in memory variable saying whether it has created the database today so it runs the create table script once per run this would still allow for you to delete the database and start over during debugging
QA
using sqlite in python program have created python module that creates and populates several sqlite tables now want to use it in program but do not really know how to call it properly all the tutorials have found are essentially inline they walk through using sqlite in linear fashion rather than how to actually use it in production what am trying to do is have method check to see if the database is already created if so then can use it if not an exception is raised and the program will create the database or use if else statements whichever is better created test script to see if my logic is correct but it is not working when create the try statement it just creates new database rather than checking if one already exists the next time run the script get an error that the table already exists even if tried catching the exception have not used try except before but figured this is good time to learn are there any good tutorials for using sqlite operationally or any suggestions on how to code this have looked through the pysqlite tutorial and others found but they do not address this
do not make this more complex than it needs to be the big independent databases have complex setup and configuration requirements sqlite is just file you access with sql it is much simpler do the following add table to your database for components or versions or configuration or release or something administrative like that create table revision release number char in your application connect to your database normally execute simple query against the revision table here is what can happen the query fails to execute your database does not exist so execute series of create statements to build it the query succeeds but returns no rows or the release number is lower than expected your database exists but is out of date you need to migrate from that release to the current release hopefully you have sequence of drop create and alter statements to do this the query succeeds and the release number is the expected value do nothing more your database is configured correctly
QA
what is an easy way to create trivial one off python object would like to create trivial one off python object to hold some command line options would like to do something like this options options verbose true options ignore warnings false then elsewhere in the code if options verbose of course could use dictionary but options verbose is more readable and easier to type than options verbose thought that should be able to do options object since object is the base type of all class objects and therefore should be something like class with no attributes but it does not work because an object created using object does not have dict member and so one cannot add attributes to it options verbose true traceback most recent call last file stdin line in module attributeerror object object has no attribute verbose what is the simplest pythonic way to create an object that can be used this way preferably without having to create an extra helper class
the collections module has grown namedtuple function in import collections opt collections namedtuple options verbose ignore warnings myoptions opt true false myoptions options verbose true ignore warnings false myoptions verbose true namedtuple is immutable so you can only assign field values when you create it in earlier python versions you can create an empty class class options object pass myoptions options myoptions verbose true myoptions ignore warnings false myoptions ignore warnings myoptions verbose false true
QA
using os execvp in python have question about using os execvp in python have the following bit of code that is used to create list of arguments args java classpath djava library path lib path ea xmx server code swarm params when output string using join args and paste that into my she will prompt the jvm launches fine and everything works everything works if use os system join args in my python script too but the following bit of code does not work os execvp java args get the following error unrecognized option classpath and then the classpath created which looks okay could not create the java virtual machine so what gives why does copying pasting into the she will or using os system work but not os execvp
make sure you are not relying on she will expansion in your classpath my jar will get expanded by the she will in an os system call but not believe in an os execvp call
QA
what is an easy way to create trivial one off python object would like to create trivial one off python object to hold some command line options would like to do something like this options options verbose true options ignore warnings false then elsewhere in the code if options verbose of course could use dictionary but options verbose is more readable and easier to type than options verbose thought that should be able to do options object since object is the base type of all class objects and therefore should be something like class with no attributes but it does not work because an object created using object does not have dict member and so one cannot add attributes to it options verbose true traceback most recent call last file stdin line in module attributeerror object object has no attribute verbose what is the simplest pythonic way to create an object that can be used this way preferably without having to create an extra helper class
use attrdict class attrdict dict def init self args kwargs dict init self args kwargs self dict self depending on your point of view you probably think it is either big kludge or quite clever but whatever you think it does make for nice looking code and is compatible with dict ad attrdict foo bar ad foo ad bar ad baz hello ad baz hello ad baz hello foo bar isinstance ad dict true
QA
what is an easy way to create trivial one off python object would like to create trivial one off python object to hold some command line options would like to do something like this options options verbose true options ignore warnings false then elsewhere in the code if options verbose of course could use dictionary but options verbose is more readable and easier to type than options verbose thought that should be able to do options object since object is the base type of all class objects and therefore should be something like class with no attributes but it does not work because an object created using object does not have dict member and so one cannot add attributes to it options verbose true traceback most recent call last file stdin line in module attributeerror object object has no attribute verbose what is the simplest pythonic way to create an object that can be used this way preferably without having to create an extra helper class
simplifying davraamides suggestion one could use the following class attrdict object def init self args kwargs self dict update args kwargs which is not so kludgy does not contaminate the namespace of each object with the standard methods of dict for example ad has key is not defined for objects of type attrdict by the way it is even easier to initialize instances of attrdict or attrdict ad attrdict foo bar granted attrdict is not compatible with dict if you do not need the magic initialization behavior you can even use class attrdict object pass ad attrdict ad foo ad bar but was still hoping for solution that does not require an auxiliary class
QA
what is an easy way to create trivial one off python object would like to create trivial one off python object to hold some command line options would like to do something like this options options verbose true options ignore warnings false then elsewhere in the code if options verbose of course could use dictionary but options verbose is more readable and easier to type than options verbose thought that should be able to do options object since object is the base type of all class objects and therefore should be something like class with no attributes but it does not work because an object created using object does not have dict member and so one cannot add attributes to it options verbose true traceback most recent call last file stdin line in module attributeerror object object has no attribute verbose what is the simplest pythonic way to create an object that can be used this way preferably without having to create an extra helper class
one can use class options object verbose true ignore warnings false options verbose false if options verbose using the class object itself not an instance of the class as the place to store individual options this is terse and satisfies all of the requirements but it seems like misuse of the class concept it would also lead to confusion if user instantiated the options class if multiple instances of the options holding objects were needed this would be very nice solution the class definition supplies default values which can be overridden in individual instances
QA
overloading init in python let us say have class that has member called data which is list want to be able to initialize the class with for example filename which contains data to initialize the list or with an actual list what is your technique for doing this do you just check the type by looking at class is there some trick might be missing am used to where overloading by argument type is easy thanks
excellent question have tackled this problem as well and while agree that factories class method constructors are good method would like to suggest another which have also found very useful here is sample this is read method and not constructor but the idea is the same def read self str none filename none addr read binary data and return store object the data store is also saved in the interal data attribute the data can either be taken from string str argument or file provide filename which will be read in binary mode if both are provided the str will be used if neither is provided an argumenterror is raised if str is none if filename is none raise argumenterror please supply string or filename file open filename rb str file read file close rest of code the key idea is here is using python excellent support for named arguments to implement this now if want to read the data from file say obj read filename blob txt and to read it from string say obj read str this way the user has just single method to call handling it inside as you saw is not overly complex
QA
what is an easy way to create trivial one off python object would like to create trivial one off python object to hold some command line options would like to do something like this options options verbose true options ignore warnings false then elsewhere in the code if options verbose of course could use dictionary but options verbose is more readable and easier to type than options verbose thought that should be able to do options object since object is the base type of all class objects and therefore should be something like class with no attributes but it does not work because an object created using object does not have dict member and so one cannot add attributes to it options verbose true traceback most recent call last file stdin line in module attributeerror object object has no attribute verbose what is the simplest pythonic way to create an object that can be used this way preferably without having to create an extra helper class
the absolutely simplest class to do the job is class struct def init self entries self dict update entries it can be later used as john struct name john doe salary print john salary namedtuple as another commented suggested is more advanced class that gives you more functionality if you are still using python the implementation namedtuple is based on can be found at http code activestate com recipes
QA
what is an easy way to create trivial one off python object would like to create trivial one off python object to hold some command line options would like to do something like this options options verbose true options ignore warnings false then elsewhere in the code if options verbose of course could use dictionary but options verbose is more readable and easier to type than options verbose thought that should be able to do options object since object is the base type of all class objects and therefore should be something like class with no attributes but it does not work because an object created using object does not have dict member and so one cannot add attributes to it options verbose true traceback most recent call last file stdin line in module attributeerror object object has no attribute verbose what is the simplest pythonic way to create an object that can be used this way preferably without having to create an extra helper class
if you insist on not having to define class you can abuse some existing classes most objects belong to new style classes which do not have dict but functions can have arbitrary attributes lambda any function will do foo bar bar xyzzy foo bar bar xyzzy function lambda at cf one problem is that functions already have some attributes so dir is little messy dir call class delattr dict doc get getattribute hash init module name new reduce reduce ex repr setattr str foo func closure func code func defaults func dict func doc func globals func name xyzzy
QA
what is an easy way to create trivial one off python object would like to create trivial one off python object to hold some command line options would like to do something like this options options verbose true options ignore warnings false then elsewhere in the code if options verbose of course could use dictionary but options verbose is more readable and easier to type than options verbose thought that should be able to do options object since object is the base type of all class objects and therefore should be something like class with no attributes but it does not work because an object created using object does not have dict member and so one cannot add attributes to it options verbose true traceback most recent call last file stdin line in module attributeerror object object has no attribute verbose what is the simplest pythonic way to create an object that can be used this way preferably without having to create an extra helper class
given your requirements would say the custom class is your best bet class options object verbose true ignore warnings true if options verbose to be complete another approach would be using separate module options py to encapsulate your option defaults options py verbose true ignore warnings true then in main py import options if options verbose this has the feature of removing some clutter from your script the default values are easy to find and change as they are cordoned off in their own module if later your application has grown you can easily access the options from other modules this is pattern that frequently use and would heartily recommend if you do not mind your application growing larger than single module or start with custom class and expand to module later if your app grows to multiple modules
QA
turning gqlquery result set into python dictionary let us say have model like this class foo db model id db stringproperty bar db stringproperty baz db stringproperty and am going gqlquery like this foos db gqlquery select from foo want to take the results of the gqlquery and turn into some sort of json string that can manipulate from different languages here is how am doing it now add method to the foo class that converts it into dictionary def todict self return id self id bar self bar baz self baz loop through the gqlquery results and manually add each foo instance to dictionary foodict for foo in foos foodict foo id foo todict return simplejson dumps foodict my approach above works but it feels kind of gross is there cleaner more pythonic way to handle this the end format does not have to be exactly what have done above it just has to be something that converts nicely to json so can deal with it from javascript php whatever
cannot do too much better than that but here are couple of ideas class foo id db stringproperty etc json attrs id bar baz split depending on how easy it is to identify string properties there might also be way to assign json attrs programmatically after the definition of foo like this foo json attrs attr for attr in dir foo if isstringproperty getattr foo attr foodict dict foo id dict getattr foo attr for attr in foo json attrs for foo in foos
QA
what is an easy way to create trivial one off python object would like to create trivial one off python object to hold some command line options would like to do something like this options options verbose true options ignore warnings false then elsewhere in the code if options verbose of course could use dictionary but options verbose is more readable and easier to type than options verbose thought that should be able to do options object since object is the base type of all class objects and therefore should be something like class with no attributes but it does not work because an object created using object does not have dict member and so one cannot add attributes to it options verbose true traceback most recent call last file stdin line in module attributeerror object object has no attribute verbose what is the simplest pythonic way to create an object that can be used this way preferably without having to create an extra helper class
just make module called options py and import it put your default options values in there as global variables
QA
binary search bisection in python is there library function that performs binary search on list tuple and return the position of the item if found and false none etc if not found the functions bisect left right in the bisect module but they still return position even if the item is not in the list that is perfectly fine for their intended usage but just want to know if an item is in the list or not do not want to insert anything thought of using bisect left and then checking if the item at that position is equal to what am searching but that seems cumbersome and also need to do bounds checking if the number can be larger than the largest number in my list if there is nicer method would like to know about it edit to clarify what need this for am aware that dictionary would be very well suited for this but am trying to keep the memory consumption as low as possible my intended usage would be sort of double way look up table have in the table list of values and need to be able to access the values based on their index and also want to be able to find the index of particular value or none if the value is not in the list using dictionary for this would be the fastest way but would approximately double the memory requirements was asking this question thinking that may have overlooked something in the python libraries it seems will have to write my own code as moe suggested
why not look at the code for bisect left right and adapt it to suit your purpose like this def binary search lo hi none if hi is none hi len while lo hi mid lo hi midval mid if midval lo mid elif midval hi mid else return mid return
QA
binary search bisection in python is there library function that performs binary search on list tuple and return the position of the item if found and false none etc if not found the functions bisect left right in the bisect module but they still return position even if the item is not in the list that is perfectly fine for their intended usage but just want to know if an item is in the list or not do not want to insert anything thought of using bisect left and then checking if the item at that position is equal to what am searching but that seems cumbersome and also need to do bounds checking if the number can be larger than the largest number in my list if there is nicer method would like to know about it edit to clarify what need this for am aware that dictionary would be very well suited for this but am trying to keep the memory consumption as low as possible my intended usage would be sort of double way look up table have in the table list of values and need to be able to access the values based on their index and also want to be able to find the index of particular value or none if the value is not in the list using dictionary for this would be the fastest way but would approximately double the memory requirements was asking this question thinking that may have overlooked something in the python libraries it seems will have to write my own code as moe suggested
if you just want to see if it is present try turning the list into dict generate list for in range convert to dict does not matter what you map values to dict for in count for in range compare with if in if in count on my machine if in took seconds while if in took seconds
QA
turning gqlquery result set into python dictionary let us say have model like this class foo db model id db stringproperty bar db stringproperty baz db stringproperty and am going gqlquery like this foos db gqlquery select from foo want to take the results of the gqlquery and turn into some sort of json string that can manipulate from different languages here is how am doing it now add method to the foo class that converts it into dictionary def todict self return id self id bar self bar baz self baz loop through the gqlquery results and manually add each foo instance to dictionary foodict for foo in foos foodict foo id foo todict return simplejson dumps foodict my approach above works but it feels kind of gross is there cleaner more pythonic way to handle this the end format does not have to be exactly what have done above it just has to be something that converts nicely to json so can deal with it from javascript php whatever
take look at google appengine api datastore it is the lower level datastore api that google appengine ext db builds on and it returns entity objects which subclass dict you can query it using gql with google appengine ext gql or my personal preference use the query class which avoids the need for you to construct text strings for the gql parser to parse the query class in api datastore behaves exactly like the one documented here but returns the lower level entity objects instead of model instances as an example your query above can be reformulated as datastore query foo all
QA
what is an easy way to create trivial one off python object would like to create trivial one off python object to hold some command line options would like to do something like this options options verbose true options ignore warnings false then elsewhere in the code if options verbose of course could use dictionary but options verbose is more readable and easier to type than options verbose thought that should be able to do options object since object is the base type of all class objects and therefore should be something like class with no attributes but it does not work because an object created using object does not have dict member and so one cannot add attributes to it options verbose true traceback most recent call last file stdin line in module attributeerror object object has no attribute verbose what is the simplest pythonic way to create an object that can be used this way preferably without having to create an extra helper class
why not just use optparse from optparse import optionparser parser optionparser parser add option file dest filename help write report to file metavar file parser add option quiet action store false dest verbose default true help do not print status messages to stdout options args parser parse args file options filename if options quiet true
QA
binary search bisection in python is there library function that performs binary search on list tuple and return the position of the item if found and false none etc if not found the functions bisect left right in the bisect module but they still return position even if the item is not in the list that is perfectly fine for their intended usage but just want to know if an item is in the list or not do not want to insert anything thought of using bisect left and then checking if the item at that position is equal to what am searching but that seems cumbersome and also need to do bounds checking if the number can be larger than the largest number in my list if there is nicer method would like to know about it edit to clarify what need this for am aware that dictionary would be very well suited for this but am trying to keep the memory consumption as low as possible my intended usage would be sort of double way look up table have in the table list of values and need to be able to access the values based on their index and also want to be able to find the index of particular value or none if the value is not in the list using dictionary for this would be the fastest way but would approximately double the memory requirements was asking this question thinking that may have overlooked something in the python libraries it seems will have to write my own code as moe suggested
this is little off topic since moe answer seems complete to the op question but it might be worth looking at the complexity for your whole procedure from end to end if you are storing thing in sorted lists which is where binary search would help and then just checking for existence you are incurring worst case unless specified sorted lists log to initially create the list if it is unsorted data if it is sorted log lookups this is the binary search part insert delete might be or log average case depending on your pattern whereas with set you are incurring to create lookup insert delete the thing sorted list really gets you are next previous and ranges including inserting or deleting ranges which are or range given starting index if you are not using those sorts of operations often then storing as sets and sorting for display might be better deal overall set incurs very little additional overhead in python
QA
keyboard interruptable blocking queue in python it seems import queue queue queue get timeout is keyboard interruptible ctrl whereas import queue queue queue get is not could always create loop import queue queue while true try get timeout except queue empty pass but this seems like strange thing to do so is there way of getting an indefinitely waiting but keyboard interruptible queue get
queue objects have this behavior because they lock using condition objects form the threading module so your solution is really the only way to go however if you really want queue method that does this you can monkeypatch the queue class for example def interruptable get self while true try return self get timeout except queue empty pass queue interruptable get interruptable get this would let you say interruptable get instead of interruptable get although monkeypatching is generally discouraged by the python community in cases such as these since regular function seems just as good
QA
how to build tagging support using couchdb am using the following view function to iterate over all items in the database in order to find tag but think the performance is very poor if the dataset is large any other approach def by tag tag return function doc if doc tags length for var tag in doc tags if doc tags tag emit doc published doc tag
disclaimer did not test this and do not know if it can perform better create single perm view function doc for var tag in doc tags emit tag doc published doc and query with view your view all startkey your tag here endkey your tag here resulting json structure will be slightly different but you will still get the publish date sorting
QA
is there any way to get python omnicomplete to work with non system modules in vim the only thing can get python omnicomplete to work with are system modules get nothing for help with modules in my site packages or modules that am currently working on
once generated ctags for one of my site packages it started working for that package so am guessing that the omnicomplete function depends on ctags for non sys modules edit not true at all here is the problem poor testing on my part omnicomplete was working for parts of my project just not most of it the issue was that am working on django project and in order to import django db you need to have an environment variable set since could not import django db any class that inherited from django db or any module that imported class that inherited from django db would not complete
QA
starting new database driven python web application would you use javascript widget framework if so which framework am starting new web application project want to use python as am using it at my bread and butter job however do not want to reinvent the wheel some things have thought about ajax would be nice if it not too much of hazzle it is best if the licensing allows commercialization but is not crucial at this point it could also be funny to try out the google app engine if the tools will let me should be using javascript ui framework or should go for standard html forms which framework would you recommend
web py uses jquery
QA
in django how could one use django update object generic view to edit forms of inherited models in django given excerpts from an application animals likeso animals models py with from django db import models from django contrib contenttypes models import contenttype class animal models model content type models foreignkey contenttype editable false null true name models charfield class dog animal is lucky models booleanfield class cat animal lives left models integerfield and an animals urls py from django conf urls default import from animals models import animal dog cat dict model animal urlpatterns url edit object id create update update object dict how can one use generic views to edit dog and or cat using the same form the form object that is passed to animals animal form html will be animal and thus will not contain any of the specifics for the derived classes dog and cat how could have django automatically pass form for the child class to animal animals form html incidentally am using djangosnippets for contenttype management so animal would have method named as leaf class that returns the derived class clearly one could create forms for each derived class but that is quite lot of unnecessary duplication as the templates will all be generic essentially form as incidentally it is best to assume that animal will probably be one of several unrelated base classes with the same problem so an ideal solution would be generic thank you in advance for the help
afaict cats and dogs are on different db tables and maybe there is no animal table but you are using one url pattern for all somewhere you need to choose between each would use different url patter for cats and dogs both would call create update update object but using different dict for each one with model dog and the other with model cat or maybe you want single table where each record can be cat or dog do not think you can use inherited models for that
QA
good multithreaded python webserver am looking for python webserver which is multithreaded instead of being multi process as in case of mod python for apache want it to be multithreaded because want to have an in memory object cache that will be used by various http threads my webserver does lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing this is not possible in multi process web server environment storing this information in memcache is also not good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of ipc implemented simple webserver using basehttpserver it gives good performance but it gets stuck after few hours time need some more matured webserver is it possible to configure apache to use mod python under thread model so that can do some object caching
not multithreaded but twisted might serve your needs
QA
good multithreaded python webserver am looking for python webserver which is multithreaded instead of being multi process as in case of mod python for apache want it to be multithreaded because want to have an in memory object cache that will be used by various http threads my webserver does lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing this is not possible in multi process web server environment storing this information in memcache is also not good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of ipc implemented simple webserver using basehttpserver it gives good performance but it gets stuck after few hours time need some more matured webserver is it possible to configure apache to use mod python under thread model so that can do some object caching
perhaps you have problem with your implementation in python using basehttpserver there is no reason for it to get stuck and implementing simple threaded server using basehttpserver and threading should not be difficult also see http pymotw com basehttpserver index html module basehttpserver about implementing simple multi threaded server with httpserver and threadingmixin
QA
good multithreaded python webserver am looking for python webserver which is multithreaded instead of being multi process as in case of mod python for apache want it to be multithreaded because want to have an in memory object cache that will be used by various http threads my webserver does lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing this is not possible in multi process web server environment storing this information in memcache is also not good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of ipc implemented simple webserver using basehttpserver it gives good performance but it gets stuck after few hours time need some more matured webserver is it possible to configure apache to use mod python under thread model so that can do some object caching
use cherrypy both personally and professionally and am extremely happy with it even do the kinds of thing you are describing such as having global object caches running other threads in the background etc and it integrates well with apache simply run cherrypy as standalone server bound to localhost then use apache mod proxy and mod rewrite to have apache transparently forward your requests to cherrypy the cherrypy website is http cherrypy org
QA
good multithreaded python webserver am looking for python webserver which is multithreaded instead of being multi process as in case of mod python for apache want it to be multithreaded because want to have an in memory object cache that will be used by various http threads my webserver does lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing this is not possible in multi process web server environment storing this information in memcache is also not good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of ipc implemented simple webserver using basehttpserver it gives good performance but it gets stuck after few hours time need some more matured webserver is it possible to configure apache to use mod python under thread model so that can do some object caching
you could instead use distributed cache that is accessible from each process memcached being the example that springs to mind
QA
good multithreaded python webserver am looking for python webserver which is multithreaded instead of being multi process as in case of mod python for apache want it to be multithreaded because want to have an in memory object cache that will be used by various http threads my webserver does lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing this is not possible in multi process web server environment storing this information in memcache is also not good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of ipc implemented simple webserver using basehttpserver it gives good performance but it gets stuck after few hours time need some more matured webserver is it possible to configure apache to use mod python under thread model so that can do some object caching
cherrypy features as listed from the website fast http compliant wsgi thread pooled webserver typically cherrypy itself takes only ms per page support for any other wsgi enabled webserver or adapter including apache iis lighttpd mod python fastcgi scgi and mod wsgi easy to run multiple http servers on multiple ports at once powerful configuration system for developers and deployers alike flexible plugin system built in tools for caching encoding sessions authorization static content and many more native mod python adapter complete test suite swappable and customizable everything built in profiling coverage and testing support
QA
good multithreaded python webserver am looking for python webserver which is multithreaded instead of being multi process as in case of mod python for apache want it to be multithreaded because want to have an in memory object cache that will be used by various http threads my webserver does lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing this is not possible in multi process web server environment storing this information in memcache is also not good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of ipc implemented simple webserver using basehttpserver it gives good performance but it gets stuck after few hours time need some more matured webserver is it possible to configure apache to use mod python under thread model so that can do some object caching
consider reconsidering your design maintaining that much state in your webserver is probably bad idea multi process is much better way to go for stability is there another way to share state between separate processes what about service database index it seems unlikely that maintaining huge array of data in memory and relying on single multi threaded process to serve all your requests is the best design or architecture for your app
QA
how to convert string char array into python string when there are non ascii characters in the string have embedded python interpreter in program suppose the program reads some bytes from file into char array and learns somehow that the bytes represent text with certain encoding iso windows or utf how do decode the contents of this char array into python string the python string should in general be of type unicode for instance in windows encoded input becomes you have attempted to use pystring decode but it always fails when there are non ascii characters in the string here is an example that fails include python include stdio int main int argc char argv char string char pyobject py string py initialize py string pystring decode string windows replace if py string pyerr print return return the error message is unicodeencodeerror ascii codec cannot encode character you in position ordinal not in range which indicates that the ascii encoding is used even though we specify windows in the call to pystring decode the following code works around the problem by using pystring fromstring to create python string of the undecoded bytes then calling its decode method include python include stdio int main int argc char argv char string char pyobject raw decoded py initialize raw pystring fromstring string printf undecoded pyobject print raw stdout printf decoded pyobject callmethod raw decode windows py decref raw printf decoded pyobject print decoded stdout printf return
you do not want to decode the string into unicode representation you just want to treat it as an array of bytes right just use pystring fromstring char cstring pyobject pystring pystring fromstring cstring that is all now you have python str object see docs here https docs python org api string html am little bit confused about how to specify str or unicode they are quite different if you have non ascii characters if you want to decode string and you know exactly what character set it is in then yes pystring decodestring is good place to start
QA
python threadsafe object cache have implemented python webserver each http request spawns new thread have requirement of caching objects in memory and since its webserver want the cache to be thread safe is there standard implementatin of thread safe object cache in python found the following http freshmeat net projects lrucache this does not look to be thread safe can anybody point me to good implementation of thread safe cache in python thanks
you probably want to use memcached instead it is very fast very stable very popular has good python libraries and will allow you to grow to distributed cache should you need to http www danga com memcached
QA
python inverse of matrix how do get the inverse of matrix in python have implemented it myself but it is pure python and suspect there are faster modules out there to do it
if you hate numpy get out rpy and your local copy of and use it instead would also echo to make you you really need to invert the matrix in for example linalg solve and the solve function do not actually do full inversion since it is unnecessary
QA
good multithreaded python webserver am looking for python webserver which is multithreaded instead of being multi process as in case of mod python for apache want it to be multithreaded because want to have an in memory object cache that will be used by various http threads my webserver does lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing this is not possible in multi process web server environment storing this information in memcache is also not good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of ipc implemented simple webserver using basehttpserver it gives good performance but it gets stuck after few hours time need some more matured webserver is it possible to configure apache to use mod python under thread model so that can do some object caching
just to point out something different from the usual suspects some years ago while was using zope read about medusa as it was the web server used for the platform they advertised it to work well under heavy load and it can provide you with the functionality you asked
QA
good multithreaded python webserver am looking for python webserver which is multithreaded instead of being multi process as in case of mod python for apache want it to be multithreaded because want to have an in memory object cache that will be used by various http threads my webserver does lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing this is not possible in multi process web server environment storing this information in memcache is also not good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of ipc implemented simple webserver using basehttpserver it gives good performance but it gets stuck after few hours time need some more matured webserver is it possible to configure apache to use mod python under thread model so that can do some object caching
its hard to give definitive answer without knowing what kind of site you are working on and what kind of load you are expecting sub second performance may be serious requirement or it may not if you really need to save that last millisecond then you absolutely need to keep your arrays in memory however as others have suggested it is more than likely that you do not and could get by with something else your usage pattern of the data in the array may affect what kinds of choices you make you probably do not need access to the entire set of data from the array all at once so you could break your data up into smaller chunks and put those chunks in the cache instead of the one big lump depending on how often your array data needs to get updated you might make choice between memcached local db berkley sqlite small mysql installation etc or remote db would say memcached for fairly frequent updates local db for something in the frequency of hourly and remote for the frequency of daily one thing to consider also is what happens after cache miss if clients all of sudden get cache miss and all of them at the same time decide to start regenerating those expensive arrays your box es will quickly be reduced to so you have to take in to consideration how you will handle that many articles out there cover how to recover from cache misses hope this is helpful
QA
python threadsafe object cache have implemented python webserver each http request spawns new thread have requirement of caching objects in memory and since its webserver want the cache to be thread safe is there standard implementatin of thread safe object cache in python found the following http freshmeat net projects lrucache this does not look to be thread safe can anybody point me to good implementation of thread safe cache in python thanks
thread per request is often bad idea if your server experiences huge spikes in load it will take the box to its knees consider using thread pool that can grow to limited size during peak usage and shrink to smaller size when load is light
QA
how to convert string char array into python string when there are non ascii characters in the string have embedded python interpreter in program suppose the program reads some bytes from file into char array and learns somehow that the bytes represent text with certain encoding iso windows or utf how do decode the contents of this char array into python string the python string should in general be of type unicode for instance in windows encoded input becomes you have attempted to use pystring decode but it always fails when there are non ascii characters in the string here is an example that fails include python include stdio int main int argc char argv char string char pyobject py string py initialize py string pystring decode string windows replace if py string pyerr print return return the error message is unicodeencodeerror ascii codec cannot encode character you in position ordinal not in range which indicates that the ascii encoding is used even though we specify windows in the call to pystring decode the following code works around the problem by using pystring fromstring to create python string of the undecoded bytes then calling its decode method include python include stdio int main int argc char argv char string char pyobject raw decoded py initialize raw pystring fromstring string printf undecoded pyobject print raw stdout printf decoded pyobject callmethod raw decode windows py decref raw printf decoded pyobject print decoded stdout printf return
try calling pyerr print in the if py string clause perhaps the python exception will give you some more information
QA
would python make good substitute for the windows command line batch scripts have got some experience with bash which do not mind but now that am doing lot of windows development am needing to do basic stuff write basic scripts using the windows command line language for some reason said language really irritates me so was considering learning python and using that instead is python suitable for such things moving files around creating scripts to do things like unzipping backup and restoring sql database etc
python is well suited for these tasks and would guess much easier to develop in and debug than windows batch files the question is think how easy and painless it is to ensure that all the computers that you have to run these scripts on have python installed
QA
would python make good substitute for the windows command line batch scripts have got some experience with bash which do not mind but now that am doing lot of windows development am needing to do basic stuff write basic scripts using the windows command line language for some reason said language really irritates me so was considering learning python and using that instead is python suitable for such things moving files around creating scripts to do things like unzipping backup and restoring sql database etc
are you aware of powershell
QA
would python make good substitute for the windows command line batch scripts have got some experience with bash which do not mind but now that am doing lot of windows development am needing to do basic stuff write basic scripts using the windows command line language for some reason said language really irritates me so was considering learning python and using that instead is python suitable for such things moving files around creating scripts to do things like unzipping backup and restoring sql database etc
sure python is pretty good choice for those tasks am sure many will recommend powershell instead here is fine introduction from that point of view http www redhatmagazine com python for bash scripters well kept secret edit about gnud concern http www portablepython com
QA
would python make good substitute for the windows command line batch scripts have got some experience with bash which do not mind but now that am doing lot of windows development am needing to do basic stuff write basic scripts using the windows command line language for some reason said language really irritates me so was considering learning python and using that instead is python suitable for such things moving files around creating scripts to do things like unzipping backup and restoring sql database etc
python is certainly well suited to that if you are going down that road you might also want to investigate scons which is build system itself built with python the cool thing is the build scripts are actually full blown python scripts themselves so you can do anything in the build script that you could otherwise do in python it makes make look pretty anemic in comparison upon rereading your question should note that scons is more suited to building software projects than to writing system maintenance scripts but would not hesitate to recommend python to you in any case
QA
would python make good substitute for the windows command line batch scripts have got some experience with bash which do not mind but now that am doing lot of windows development am needing to do basic stuff write basic scripts using the windows command line language for some reason said language really irritates me so was considering learning python and using that instead is python suitable for such things moving files around creating scripts to do things like unzipping backup and restoring sql database etc
anything is good replacement for the batch file system in windows perl python powershell are all good choices
QA
binary search bisection in python is there library function that performs binary search on list tuple and return the position of the item if found and false none etc if not found the functions bisect left right in the bisect module but they still return position even if the item is not in the list that is perfectly fine for their intended usage but just want to know if an item is in the list or not do not want to insert anything thought of using bisect left and then checking if the item at that position is equal to what am searching but that seems cumbersome and also need to do bounds checking if the number can be larger than the largest number in my list if there is nicer method would like to know about it edit to clarify what need this for am aware that dictionary would be very well suited for this but am trying to keep the memory consumption as low as possible my intended usage would be sort of double way look up table have in the table list of values and need to be able to access the values based on their index and also want to be able to find the index of particular value or none if the value is not in the list using dictionary for this would be the fastest way but would approximately double the memory requirements was asking this question thinking that may have overlooked something in the python libraries it seems will have to write my own code as moe suggested
using dict would not like double your memory usage unless the objects you are storing are really tiny since the values are only pointers to the actual objects foo is true in that example foo is only stored once does that make difference for you and exactly how many items are we talking about anyway
QA
parse dicom files in native python what is the simplest and most pythonic way to parse dicom file native python implementation without the use of non python libraries would be much preferred dicom is the standard file format in digital medical imaging look here for more information there are some libraries that support reading subset of dicom files two or three of them even have python bindings native python parser would serve two purposes for me no need to build any external libraries learn about the dicom file format
if you want to learn about the dicom format digital imaging and communications in medicine dicom practical introduction and survival guide by oleg pianykh is quite readable and gives good introduction to key dicom concepts springer verlag is the publisher of this book the full dicom standard is of course the ultimate reference although it is somewhat more intimidating it is available from nema http medical nema org the file format is actually less esoteric than you might imagine and consists of preamble followed by sequence of data elements the preamble contains the ascii text dicm and several reserved bytes that are unused following the preamble is sequence of data elements each data element consists of the size of the element two character ascii code indicating the value representation dicom tag and the value data elements in the file are ordered by their dicom tag numbers the image itself is just another data element with size value representation etc value representations specify exactly how to interpret the value is it number is it character string if it is character string is it short one or long one and which characters are permitted the value representation code tells you this dicom tag is byte hexadecimal code composed of byte group number and byte element number the group number is an identifier that tells you what information entity the tag applies to for example group refers to the patient and group refers to the study the element number identifies the interpretation of the value items such as the patient id number the series description etc to find out how you should interpret the value your code looks up the dicom tag in dictionary file there are some other details involved but that is the essence of it probably the most instructive thing you can do to learn about the file format is to take an example dicom file look at it with hex editor and go through the process of parsing it mentally would advise against trying to learn about dicom by looking at existing open source implementations at least initially it is more likely to confuse instead of enlighten getting the big picture is more important once you have the big picture then you can descend into subtleties
QA
opening handle to device in python on windows am trying to use the giveio sys driver which requires file to be opened before you can access protected memory am looking at example from winavr avrdude that uses the syntax define drivername giveio handle createfile drivername generic read null open existing file attribute normal null but this does not seem to work in python just get the specified path is invalid error for both os open giveio os rdonly and os open giveio os rdonly why does not this do the same thing edited to hopefully reduce confusion of ideas thanks will did verify that the device driver is running via the batch files that come with avrdude further edited to clarify samb bounty
you are question is very confusing to say the least the code you pasted is using trick to communicate with the driver using its dosname drivername have you created loaded the giveio driver the reason the driver handles this calls is because of this http msdn microsoft com en us library ms aspx
QA
how can write wrapper around ngrep that highlights matches just learned about ngrep cool program that let us you easily sniff packets that match particular string the only problem is that it can be hard to see the match in the big blob of output would like to write wrapper script to highlight these matches it could use ansi escape sequences echo this is mred am most familiar with perl but am perfectly happy with solution in python or any other language the simplest approach would be something like while stdin keyword keyword print however this is not nice solution because ngrep prints out hash marks without newlines whenever it receives non matching packet and the code above will suppress the printing of these hashmarks until the script sees newline is there any way to do the highlighting without inhibiting the instant appearance of the hashmarks
it should not be too hard if you have the answer this question essentially read one character at time and if it is hash print it if it is not hash save the character to print out later
QA
how to improve trac performance have noticed that my particular instance of trac is not running quickly and has big lags this is at the very onset of project so not much is in trac except for plugins and code loaded into svn setup info this is via selinux system hosted by webfaction it is behind apache and connections are over ssl currently the htpasswd file is what use to control access are there any recommend ways to improve the performance of trac
it is hard to say without knowing more about your setup but one easy win is to make sure that trac is running in something like mod python which keeps the python runtime in memory otherwise every http request will cause python to run import all the modules and then finally handle the request using mod python or fastcgi whichever you prefer will eliminate that loading and skip straight to the good stuff also as your trac database grows and you get more people using the site you will probably outgrow the default sqlite database at that point you should think about migrating the database to postgresql or mysql because they will be able to handle concurrent requests much faster
QA
how can write wrapper around ngrep that highlights matches just learned about ngrep cool program that let us you easily sniff packets that match particular string the only problem is that it can be hard to see the match in the big blob of output would like to write wrapper script to highlight these matches it could use ansi escape sequences echo this is mred am most familiar with perl but am perfectly happy with solution in python or any other language the simplest approach would be something like while stdin keyword keyword print however this is not nice solution because ngrep prints out hash marks without newlines whenever it receives non matching packet and the code above will suppress the printing of these hashmarks until the script sees newline is there any way to do the highlighting without inhibiting the instant appearance of the hashmarks
ah forget it this is too much of pain it was lot easier to get the source to ngrep and make it print the hash marks to stderr ngrep ngrep new if quiet printf fflush stdout fprintf stderr switch ip proto then filtering is piece of cake while cmd keyword print
QA
how can write wrapper around ngrep that highlights matches just learned about ngrep cool program that let us you easily sniff packets that match particular string the only problem is that it can be hard to see the match in the big blob of output would like to write wrapper script to highlight these matches it could use ansi escape sequences echo this is mred am most familiar with perl but am perfectly happy with solution in python or any other language the simplest approach would be something like while stdin keyword keyword print however this is not nice solution because ngrep prints out hash marks without newlines whenever it receives non matching packet and the code above will suppress the printing of these hashmarks until the script sees newline is there any way to do the highlighting without inhibiting the instant appearance of the hashmarks
this is easy in python usr bin env python import sys re keyword red while sys stdin read if not break if in sys stdout write else sys stdout write sys stdin readline replace keyword keyword
QA
would python make good substitute for the windows command line batch scripts have got some experience with bash which do not mind but now that am doing lot of windows development am needing to do basic stuff write basic scripts using the windows command line language for some reason said language really irritates me so was considering learning python and using that instead is python suitable for such things moving files around creating scripts to do things like unzipping backup and restoring sql database etc
bkb definitely has valid concern here is couple links you will want to check if you run into any issues that cannot be solved with the standard library pywin is package for working with low level win apis advanced file system modifications com interfaces etc tim golden python page he maintains wmi wrapper package that builds off of pywin but be sure to also check out his win how do page for details on how to accomplish typical windows tasks in python
QA
would python make good substitute for the windows command line batch scripts have got some experience with bash which do not mind but now that am doing lot of windows development am needing to do basic stuff write basic scripts using the windows command line language for some reason said language really irritates me so was considering learning python and using that instead is python suitable for such things moving files around creating scripts to do things like unzipping backup and restoring sql database etc
have been using lot of windows script files lately more powerful than batch scripts and since it uses windows scripting there is nothing to install
QA
would python make good substitute for the windows command line batch scripts have got some experience with bash which do not mind but now that am doing lot of windows development am needing to do basic stuff write basic scripts using the windows command line language for some reason said language really irritates me so was considering learning python and using that instead is python suitable for such things moving files around creating scripts to do things like unzipping backup and restoring sql database etc
python along with pywin would be fine for windows automation however vbscript or jscript used with the winows scripting host works just as well and requires nothing additional to install
QA
using django rest interface have django application that would like to add some rest interfaces to have seen http code google com django rest interface but it seems to be pretty simplistic for instance it does not seem to have way of enforcing security how would go about limiting what people can view and manipulate through the rest interface normally would put this kind of logic in my views is this the right place or should be moving some more logic down into the model alternatively is there better library out there or do need to roll my own
well from the look of things there is an authentication parameter to collection see this example authentication py second even if django does not have it yet there should probably be middleware that does csrf xsrf form checking oh there seems to be one you should also be able to use the login required and permission required decorators in the urls py
QA
would python make good substitute for the windows command line batch scripts have got some experience with bash which do not mind but now that am doing lot of windows development am needing to do basic stuff write basic scripts using the windows command line language for some reason said language really irritates me so was considering learning python and using that instead is python suitable for such things moving files around creating scripts to do things like unzipping backup and restoring sql database etc
have done decent amount of scripting in both linux unix and windows environments in python perl batch files bash etc my advice is that if it is possible install cygwin and use bash it sounds from your description like installing scripting language or env is not problem you will be more comfortable with that since the transition is minimal if that is not an option then here is my take batch files are very kludgy and limited but make lot of sense for simple tasks like copy some files or restart this service python will be cleaner easier to maintain and much more powerful however the downside is that either you end up calling external applications from python with subprocess popen or similar otherwise you end up writing bunch more code to do things that are comparatively simple in batch files like copying folder full of files lot of this depends on what your scripts are doing text string processing is going to be much cleaner in python for example lastly it is probably not an attractive alternative but you might also consider vbscript as an alternative do not enjoy working with it as language personally but if portability is any kind of concern then it wins out by virtue of being available out of the box in any copy of windows because of this have found myself writing scripts that were unwieldy as batch files in vbscript instead since cannot usually depend on python or perl or bash being available on windows
QA
good multithreaded python webserver am looking for python webserver which is multithreaded instead of being multi process as in case of mod python for apache want it to be multithreaded because want to have an in memory object cache that will be used by various http threads my webserver does lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing this is not possible in multi process web server environment storing this information in memcache is also not good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of ipc implemented simple webserver using basehttpserver it gives good performance but it gets stuck after few hours time need some more matured webserver is it possible to configure apache to use mod python under thread model so that can do some object caching
twisted can serve as such web server while not multithreaded itself there is not yet released multithreaded wsgi container present in the current trunk you can check out the svn repository and then run twistd web wsgi your wsgi application
QA
how can write wrapper around ngrep that highlights matches just learned about ngrep cool program that let us you easily sniff packets that match particular string the only problem is that it can be hard to see the match in the big blob of output would like to write wrapper script to highlight these matches it could use ansi escape sequences echo this is mred am most familiar with perl but am perfectly happy with solution in python or any other language the simplest approach would be something like while stdin keyword keyword print however this is not nice solution because ngrep prints out hash marks without newlines whenever it receives non matching packet and the code above will suppress the printing of these hashmarks until the script sees newline is there any way to do the highlighting without inhibiting the instant appearance of the hashmarks
you could also pipe the output through ack the passthru flag will help
QA
how to create numpy record array from on the python side can create new numpy record arrays as follows numpy zeros dtype how do do the same from program suppose have to call pyarray simplenewfromdescr nd dims descr but how do construct pyarray descr that is appropriate for passing as the third argument to pyarray simplenewfromdescr
see the guide to numpy section there is lots of different ways to make descriptor although it is not nearly as easy as writing
QA
how are you planning on handling the migration to python am sure this is subject that is on most python developers minds considering that python is coming out soon some questions to get us going in the right direction will you have python and python version to be maintained concurrently or will you simply have python version once it is finished have you already started or plan on starting soon or do you plan on waiting until the final version comes out to get into full swing
here is the general plan for twisted was originally going to blog this but then thought why blog about it when could get points for it wait until somebody cares right now nobody has python we are not going to spend bunch of effort until at least one actual user has come forth and said need python support and has good reason for it aside from the fact that looks shiny wait until our dependencies have migrated large system like twisted has number of dependencies for starters ours include zope interface pycrypto pyopenssl pywin pygtk though this dependency is sadly very light right now by the time migration rolls around hope twisted will have more gui tools pyasn pypam gmpy some of these projects have their own array of dependencies so we will have to wait for those as well wait until somebody cares enough to help there are charitably people who work on twisted and say charitably because that is counting me and have not committed in months we have over open tickets right now and it would be nice to actually fix some of those fix bugs add features and generally make twisted better product in its own right before spending time on getting it ported over to substantially new version of the language this potentially includes sponsors caring enough to pay for us to do it but hope that there will be an influx of volunteers who care about support and want to help move the community forward follow guido advice this means we will not change our api incompatibly and we will follow the transitional development guidelines that guido posted last year that starts with having unit tests and running the to conversion tool over the twisted codebase report bugs against and file patches for the to tool when we get to the point where we are actually using it anticipate that there will be lot of problems with running to in the future running it over twisted right now takes an extremely long time and last checked which was quite while ago cannot parse few of the files in the twisted repository so the resulting output will not import think there will have to be fair amount of success stories from small projects and lot of hammering on the tool before it will actually work for us however the python development team has been very helpful in responding to our bug reports and early responses to these problems have been encouraging so expect that all of these issues will be fixed in time maintain compatibility for several years right now twisted supports python to currently we are working on support which we will obviously have to finish before our plan is to we revise our supported versions of python based on the long term supported versions of ubuntu release which includes python will be supported until according to guido advice we will need to drop support for in order to support but am hoping we can find way around that we are pretty creative with version compatibility hacks so we are planning to support python until at least in two years ubuntu will release another long term supported version of ubuntu if they still exist and stay on schedule that will be personally am guessing that this will ship with python perhaps python as usr bin python because there is huge amount of python software packaged with the distribution and it will take long time to update it all so five years from then in we can start looking at dropping support during this period we will continue to follow guido advice about migration running to over our codebase and modifying the codebase to keep its tests passing in both versions the upshot of this is that python will not be source language for twisted until well after my th birthday it will be target runtime and set of guidelines and restrictions for my python code expect to be writing programs in python for the next ten years or so so that is the plan am hoping that it ends up looking laughably conservative in year or so that the transition is easy as pie and everyone rapidly upgrades other things could happen too the and branches could converge someone might end up writing to or another runtime pypy comes to mind might allow for running and code in the same process directly making our conversion process easier for the time being however we are assuming that for many years we will have people with large codebases they are maintaining or people writing new code who want to use other libraries which have not yet been migrated who still want new features and bug fixes in twisted pretty soon expect we will also have bleeding edge users that want to use twisted on python would like to provide all of those people with positive experience for as long as possible
QA
using sqlite in python program have created python module that creates and populates several sqlite tables now want to use it in program but do not really know how to call it properly all the tutorials have found are essentially inline they walk through using sqlite in linear fashion rather than how to actually use it in production what am trying to do is have method check to see if the database is already created if so then can use it if not an exception is raised and the program will create the database or use if else statements whichever is better created test script to see if my logic is correct but it is not working when create the try statement it just creates new database rather than checking if one already exists the next time run the script get an error that the table already exists even if tried catching the exception have not used try except before but figured this is good time to learn are there any good tutorials for using sqlite operationally or any suggestions on how to code this have looked through the pysqlite tutorial and others found but they do not address this
yes was nuking out the problem all needed to do was check for the file and catch the ioerror if it did not exist thanks for all the other answers they may come in handy in the future
QA
python templates for web designers what are some good templating engines for web designers definitely have my preferences as to what would prefer to work with as programmer but web designers seem to have different way of thinking about things and thus may prefer different system so web designers what templating engine do you prefer to work with programmers what templating engines have you worked with that made working with web designers easy
personally found cheetah templates to be very designer friendly what needed some time was the idea of templates subclassing and this was something hard to get at the beginning but designer creates full template duplicating his code then you can go clean things up bit
QA
python templates for web designers what are some good templating engines for web designers definitely have my preferences as to what would prefer to work with as programmer but web designers seem to have different way of thinking about things and thus may prefer different system so web designers what templating engine do you prefer to work with programmers what templating engines have you worked with that made working with web designers easy
django templating engine is quite decent it is pretty robust while not stepping on too many toes if you are working with python would recommend it do not know how to divorce it from django but doubt it would be very difficult seeing as django is quite modular edit apparently the mini guide to using django templating engine standalone was sitting in front of me already thanks insin
QA
python import does not work as expected when using import with dotted name something like somepackage somemodule the module returned is not somemodule whatever is returned seems to be mostly empty what is going on here
there is something that works as you want it to twisted python reflect namedany from twisted python reflect import namedany namedany operator eq built in function eq namedany pysqlite dbapi connect built in function connect namedany os module os from usr lib python os pyc
QA
opening handle to device in python on windows am trying to use the giveio sys driver which requires file to be opened before you can access protected memory am looking at example from winavr avrdude that uses the syntax define drivername giveio handle createfile drivername generic read null open existing file attribute normal null but this does not seem to work in python just get the specified path is invalid error for both os open giveio os rdonly and os open giveio os rdonly why does not this do the same thing edited to hopefully reduce confusion of ideas thanks will did verify that the device driver is running via the batch files that come with avrdude further edited to clarify samb bounty
am not sure if that is possible as an alternative you could write program that does all that kernel space work for you and interface with it in python via the subprocess module or python bindings and another link for that
QA
turning gqlquery result set into python dictionary let us say have model like this class foo db model id db stringproperty bar db stringproperty baz db stringproperty and am going gqlquery like this foos db gqlquery select from foo want to take the results of the gqlquery and turn into some sort of json string that can manipulate from different languages here is how am doing it now add method to the foo class that converts it into dictionary def todict self return id self id bar self bar baz self baz loop through the gqlquery results and manually add each foo instance to dictionary foodict for foo in foos foodict foo id foo todict return simplejson dumps foodict my approach above works but it feels kind of gross is there cleaner more pythonic way to handle this the end format does not have to be exactly what have done above it just has to be something that converts nicely to json so can deal with it from javascript php whatever
http code google com google app engine samples source browse trunk geochat json py the encoder method will solve your gql to json needs nicely would recommend getting rid of some of the excessive datetime options out time as an epoch really
QA
how can write wrapper around ngrep that highlights matches just learned about ngrep cool program that let us you easily sniff packets that match particular string the only problem is that it can be hard to see the match in the big blob of output would like to write wrapper script to highlight these matches it could use ansi escape sequences echo this is mred am most familiar with perl but am perfectly happy with solution in python or any other language the simplest approach would be something like while stdin keyword keyword print however this is not nice solution because ngrep prints out hash marks without newlines whenever it receives non matching packet and the code above will suppress the printing of these hashmarks until the script sees newline is there any way to do the highlighting without inhibiting the instant appearance of the hashmarks
this seems to do the trick at least comparing two windows one running straight ngrep ngrep whatever and one being piped into the following program with ngrep whatever ngrephl target string usr bin perl use strict use warnings autoflush on my keyword shift or die no pattern specified my cache while read stdin my ch if ch eq cache keyword syswrite stdout cache ch cache else cache ch
QA
how do you convert yyyy mm ddthh mm ss time format to mm dd yyyy time format in python for example am trying to convert to what is the simplest way of accomplishing this
import time timestamp ts time strptime timestamp dt time strftime ts see the documentation of the python time module for more information
QA
python module dlls is there way to make python module load dll in my application directory rather than the version that came with the python installation without making changes to the python installation which would then require made an installer and be careful did not break other apps for people by overwrting python modules and changing dll versions globaly specifically would like python to use my version of the sqlite dll rather than the version that came with python which is older and does not appear to have the fts module
if your version of sqlite is in sys path before the systems version it will use that so you can either put it in the current directory or change the pythonpath environment variable to do that
QA
opening handle to device in python on windows am trying to use the giveio sys driver which requires file to be opened before you can access protected memory am looking at example from winavr avrdude that uses the syntax define drivername giveio handle createfile drivername generic read null open existing file attribute normal null but this does not seem to work in python just get the specified path is invalid error for both os open giveio os rdonly and os open giveio os rdonly why does not this do the same thing edited to hopefully reduce confusion of ideas thanks will did verify that the device driver is running via the batch files that come with avrdude further edited to clarify samb bounty
do not know anything about python but do know bit about drivers you are not trying to open file in kernel space at all you are just trying to open handle to device which happens to be made to look bit like opening file createfile is user mode function and everything you are doing here is user mode not kernel mode as xenon says your call may be failing because you have not loaded the driver yet or because whatever python call you are using to do the createfile is not passing the write parameters in have never used giveio sys myself but personally would establish that it was loaded correctly by using or or some pre written app before tried to get it working via python
QA
python module dlls is there way to make python module load dll in my application directory rather than the version that came with the python installation without making changes to the python installation which would then require made an installer and be careful did not break other apps for people by overwrting python modules and changing dll versions globaly specifically would like python to use my version of the sqlite dll rather than the version that came with python which is older and does not appear to have the fts module
if you are talking about python module dlls then simply modifying sys path should be fine however if you are talking about dlls linked against those dlls libfoo dll which foo pyd depends on then you need to modify your path environment variable wrote about doing this for pygtk while ago but in your case think it should be as simple as import os os environ path my app dir os environ path that will insert my app dir at the head of your windows path which believe also controls the load order for dlls keep in mind that you will need to do this before loading the dll in question before importing anything interesting sqlite may be bit of special case though since it is distributed with python it is obviously kind of tricky to test this quickly so have not checked sqlite dll specifically
QA
python module dlls is there way to make python module load dll in my application directory rather than the version that came with the python installation without making changes to the python installation which would then require made an installer and be careful did not break other apps for people by overwrting python modules and changing dll versions globaly specifically would like python to use my version of the sqlite dll rather than the version that came with python which is older and does not appear to have the fts module
ok it terns out python always loads the dll in the same directory as the pyd file regardless of what the python and os paths are set to so needed to copy the sqlite pyd from python dlls to my apps directory where the new sqlite dll is making it load my new dll rather than the one that comes with python since the pyd files seem to follow the pythonpath even though the actaul dlls themselves do not
QA
can you add new statements to python syntax can you add new statements like print raise with to python syntax say to allow mystatement something or new if true print example not so much if you should but rather if it is possible short of modifying the python interpreters code
ten years ago you could not and doubt that is changed however it was not that hard to modify the syntax back then if you were prepared to recompile python and doubt that is changed either
QA
can you add new statements to python syntax can you add new statements like print raise with to python syntax say to allow mystatement something or new if true print example not so much if you should but rather if it is possible short of modifying the python interpreters code
short of changing and recompiling the source code which is possible with open source changing the base language is not really possible even if you do recompile the source it would not be python just your hacked up changed version which you need to be very careful not to introduce bugs into however am not sure why you would want to python object oriented features makes it quite simple to achieve similar results with the language as it stands
QA
can you add new statements to python syntax can you add new statements like print raise with to python syntax say to allow mystatement something or new if true print example not so much if you should but rather if it is possible short of modifying the python interpreters code
not without modifying the interpreter know lot of languages in the past several years have been described as extensible but not in the way you are describing you extend python by adding functions and classes
QA
python templates for web designers what are some good templating engines for web designers definitely have my preferences as to what would prefer to work with as programmer but web designers seem to have different way of thinking about things and thus may prefer different system so web designers what templating engine do you prefer to work with programmers what templating engines have you worked with that made working with web designers easy
look at mako here is how cope with web designers ask them to mock up the page in html use the html as the basis for the template replacing the mocked up content with replacements fold in loops to handle repeats the use of if statements requires negotiation since the mock up is one version of the page and there are usually some explanations for conditional presentation of some material
QA
using django rest interface have django application that would like to add some rest interfaces to have seen http code google com django rest interface but it seems to be pretty simplistic for instance it does not seem to have way of enforcing security how would go about limiting what people can view and manipulate through the rest interface normally would put this kind of logic in my views is this the right place or should be moving some more logic down into the model alternatively is there better library out there or do need to roll my own
even with the authentication parameter you do not have fine grained control over what people can do the current implementation of the django rest interface does not track the user information so you do not have this information available for doing fine grained authorization checks see issue however it is relatively easy to extend it to add some features use lot of subclasses to add features updating the request with login information however is tricky in django rather than do that leave the information in the collection right now would estimate that between patches and subclasses what have written is about as big as rolling my own restful view functions django rest however gracefully and neatly handles http digest authentication do not look forward to replacing theirs with some kind of decorator for my django view functions maybe we should open source forge project and work out clean replacement
QA
python templates for web designers what are some good templating engines for web designers definitely have my preferences as to what would prefer to work with as programmer but web designers seem to have different way of thinking about things and thus may prefer different system so web designers what templating engine do you prefer to work with programmers what templating engines have you worked with that made working with web designers easy
had good votes when answering this same question duplicate my answer was jinja nice syntax good customization possibilities integrates well can be sandboxed so you do not have to trust completely your template authors mako cannot it is also pretty fast with the bonus of compiling your template to bytecode and cache it as in the demonstration below import jinja print jinja environment compile for row in data row name upper endfor raw true from future import division from jinja runtime import loopcontext context templatereference macro markup templateruntimeerror missing concat escape markup join unicode join name none def root context environment environment data context resolve data environment filters upper if yield none for row in data if yield none yield unicode environment getattr row name blocks debug info this code has been generated on the fly by jinja of course the compiler optmizes it further removing if yield none
QA
python templates for web designers what are some good templating engines for web designers definitely have my preferences as to what would prefer to work with as programmer but web designers seem to have different way of thinking about things and thus may prefer different system so web designers what templating engine do you prefer to work with programmers what templating engines have you worked with that made working with web designers easy
mi vote goes to clearsilver it is the template engine used in trac before it is also used in pages like google groups or orkut the main benefits of this template engine is that it is very fast and language independent
QA
socket programming for mobile phones in python have written code for communication between my phone and comp thru tcp sockets when type out the code line by line in the interactive console it works fine however when try running the script directly through filebrowser py it just will not work am using nokia is there anyway can run this script directly without using filebrowser py am new to python for mobile phones so any suggestions would be appreciated thanks
do not you have the run script menu in your interactive python she will
QA
can you add new statements to python syntax can you add new statements like print raise with to python syntax say to allow mystatement something or new if true print example not so much if you should but rather if it is possible short of modifying the python interpreters code
have found guide on adding new statements converted from pdf to html by google http search cache ijub tasq www troeger eu teaching pythonvm lab pdf python add statement hl en ct clnk cd basically to add new statements you must edit python ast among other things and recompile the python binary while it is possible do not you can achieve almost everything via functions and classes which will not require people to recompile python just to run your script
QA
how do you convert yyyy mm ddthh mm ss time format to mm dd yyyy time format in python for example am trying to convert to what is the simplest way of accomplishing this
is an iso date and the format can be very diverse if you want to parse these dates see the python wiki on working with time it contains some useful links to modules
QA
how to improve trac performance have noticed that my particular instance of trac is not running quickly and has big lags this is at the very onset of project so not much is in trac except for plugins and code loaded into svn setup info this is via selinux system hosted by webfaction it is behind apache and connections are over ssl currently the htpasswd file is what use to control access are there any recommend ways to improve the performance of trac
we have had the best luck with fastcgi another critical factor was to only use https for authentication but use http for all other traffic was really surprised how much that made difference
QA
how to create numpy record array from on the python side can create new numpy record arrays as follows numpy zeros dtype how do do the same from program suppose have to call pyarray simplenewfromdescr nd dims descr but how do construct pyarray descr that is appropriate for passing as the third argument to pyarray simplenewfromdescr
use pyarray descrconverter here is an example include python include stdio include numpy arrayobject int main int argc char argv int dims pyobject op array pyarray descr descr py initialize import array op py buildvalue pyarray descrconverter op descr py decref op array pyarray simplenewfromdescr dims descr pyobject print array stdout printf py decref array return thanks to adam rosenfield for pointing to section of the guide to numpy
QA
efficient image thumbnail control for python what is the best choice for python gui application to display large number of thumbnails or more for performance reasons such thumbnail control must support virtual items request application for those thumbnails only which are currently visible to user
if you had to resort to writing your own have had good results using the python imaging library to create thumbnails in the past http www pythonware com products pil
QA
wxpython expand list control vertically not horizontally have listctrl that displays list of items for the user to select this works fine except that when the ctrl is not large enough to show all the items want it to expand downwards with vertical scoll bar rather than using horizontal scroll bar as it expands to the right the listctrl creation self subjectlist wx listctrl self self id subject style wx lc list wx lc single sel wx lc vrules items are inserted using wx listitem item wx listitem item settext subject item setdata id item setwidth self subjectlist insertitem item
use the wxlc report style import wx class test wx frame def init self wx frame init self none self test wx listctrl self style wx lc report wx lc no header for in range self test insertcolumn col self test setcolumnwidth for in range index self test insertstringitem self test getitemcount for in range self test setstringitem index str self show app wx pysimpleapp app topwindow test app mainloop
QA
efficient image thumbnail control for python what is the best choice for python gui application to display large number of thumbnails or more for performance reasons such thumbnail control must support virtual items request application for those thumbnails only which are currently visible to user
in wxpython you can use wxgrid for this as it supports virtual mode and custom cell renderers this is the minimal interface you have to implement for wxgrid data provider class griddata wx grid pygridtablebase def getcollabelvalue self col pass def getnumberrows self pass def getnumbercols self pass def isemptycell self row col pass def getvalue self row col pass this is the minimal interface you have to implement for wxgrid cell renderer class cellrenderer wx grid pygridcellrenderer def draw self grid attr dc rect row col isselected pass you can find working example that utilizes these classes in wxpython docs and demos it is called grid megaexample
QA
good multithreaded python webserver am looking for python webserver which is multithreaded instead of being multi process as in case of mod python for apache want it to be multithreaded because want to have an in memory object cache that will be used by various http threads my webserver does lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing this is not possible in multi process web server environment storing this information in memcache is also not good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of ipc implemented simple webserver using basehttpserver it gives good performance but it gets stuck after few hours time need some more matured webserver is it possible to configure apache to use mod python under thread model so that can do some object caching
actually had the same issue recently namely we wrote simple server using basehttpserver and found that the fact that it is not multi threaded was big drawback my solution was to port the server to pylons http pylonshq com the port was fairly easy and one benefit was it is very easy to create gui using pylons so was able to throw status page on top of what is basically daemon process would summarize pylons this way it is similar to ruby on rails in that it aims to be very easy to deploy web apps it is default templating language mako is very nice to work with it uses system of routing urls that is very convenient for us performance is not an issue so cannot guarantee that pylons would perform adequately for your needs you can use it with apache lighthttpd though have not tried this we also run an app with twisted and are happy with it twisted has good performance but find twisted single threaded defer to thread programming model fairly complicated it has lots of advantages but would not be my choice for simple app good luck
QA
good multithreaded python webserver am looking for python webserver which is multithreaded instead of being multi process as in case of mod python for apache want it to be multithreaded because want to have an in memory object cache that will be used by various http threads my webserver does lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing this is not possible in multi process web server environment storing this information in memcache is also not good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of ipc implemented simple webserver using basehttpserver it gives good performance but it gets stuck after few hours time need some more matured webserver is it possible to configure apache to use mod python under thread model so that can do some object caching
web py has made me happy in the past consider checking it out but it does sound like an architectural redesign might be the proper though more expensive solution
QA
how do you fix trac installation that begins giving errors relating to python egg cache we have been using trac for task defect tracking and things were going well enough but this morning it started serving up error looking in the apache error log get stack trace that culminates in pythonhandler trac web modpython frontend extractionerror cannot extract file to egg cache the following error occurred while trying to extract file to the python egg cache errno permission denied python eggs the python egg cache directory is currently set to python eggs perhaps your account does not have write access to this directory you can change the cache directory by setting the python egg cache environment variable to point to an accessible directory so explicitly set python egg cache to srv trac plugin cache restarted apache yet get the same error it still says egg cache directory current set to python eggs how should proceed is the simplest thing to do to reinstall trac if go that route what steps do need to take to ensure that do not lose existing data
that should be fixed in according to their bug tracking system if that is not the case you should try to pass the environment var to apache since doing setenv in the configuration file does not work adding something like export python egg cache tmp python eggs to the script you use to start apache should work