prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
hiding password in python script have got python script which is creating an odbc connection the odbc connection is generated with connection string in this connection string have to include the username and password for this connection is there an easy way to obscure this password in the file just that nobody can read the password when am editing the file
your operating system probably provides facilities for encrypting data securely for instance on windows there is dpapi data protection api why not ask the user for their credentials the first time you run then squirrel them away encrypted for subsequent runs
QA
hiding password in python script have got python script which is creating an odbc connection the odbc connection is generated with connection string in this connection string have to include the username and password for this connection is there an easy way to obscure this password in the file just that nobody can read the password when am editing the file
how about importing the username and password from file external to the script that way even if someone got hold of the script they would not automatically get the password
QA
hiding password in python script have got python script which is creating an odbc connection the odbc connection is generated with connection string in this connection string have to include the username and password for this connection is there an easy way to obscure this password in the file just that nobody can read the password when am editing the file
douglas shearer is the generally approved solution in unix when you need to specify password for remote login you add password from file option to specify the path and read plaintext from file the file can then be in the user own area protected by the operating system it also allows different users to automatically pick up their own own file for passwords that the user of the script is not allowed to know you can run the script with elavated permission and have the password file owned by that root admin user
QA
most pythonic way of counting matching elements in something iterable have an iterable of entries on which would like to gather some simple statistics say the count of all numbers divisible by two and the count of all numbers divisible by three my first alternative while only iterating through the list once and avoiding the list expansion and keeping the split loop refactoring in mind looks rather bloated alt are xrange twos threes for in if twos if threes print twos print threes this looks rather nice but has the drawback of expanding the expression to list alt are xrange print len for in if print len for in if what would really like is something like function like this alt def count iterable for in iterable return are xrange print count for in if print count for in if but this looks lot like something that could be done without function the final variant is this alt are xrange print sum for in if print sum for in if and while the smallest and in my book probably the most elegant it does not feel like it expresses the intent very well so my question to you is which alternative do you like best to gather these types of stats feel free to supply your own alternative if you have something better to clear up some confusion below in reality my filter predicates are more complex than just this simple test the objects iterate over are larger and more complex than just numbers my filter functions are more different and hard to parameterize into one predicate
inspired by the oo stab above had to try my hands on one as well although this is way overkill for the problem am trying to solve class stat object def update self raise notimplementederror def get self raise notimplementederror class twostat stat def init self self twos def update self if self twos def get self return self twos class threestat stat def init self self threes def update self if self threes def get self return self threes class statcalculator object def init self stats self stats stats def calculate self for in for stat in self stats stat update return tuple stat get for stat in self stats statcalculator twostat threestat are xrange print calculate
QA
python module dependency ok have two modules each containing class the problem is their classes reference each other let us say for example had room module and person module containing croom and cperson the croom class contains infomation about the room and cperson list of every one in the room the cperson class however sometimes needs to use the croom class for the room its in for example to find the door or too see who else is in the room the problem is with the two modules importing each other just get an import error on which ever is being imported second in could solve this by only including the headers and since in both cases the classes just have pointers to the other class forward declaration would suffice for the header eg class cperson forward declare class croom std set cperson people is there anyway to do this in python other than placing both classes in the same module or something like that edit added python example showing problem using above classes error traceback most recent call last file projects python test main py line in from room import croom file projects python test room py line in from person import cperson file projects python test person py line in from room import croom importerror cannot import name croom room py from person import cperson class croom def init self self people self nextid def addperson self firstname secondname gender id self nextid self nextid person cperson firstname secondname gender id self people id person return person def finddoorandleave self personid del self people peopleid person py from room import croom class cperson def init self room firstname secondname gender id self room room self firstname firstname self secondname secondname self gender gender self id id def leave self self room finddoorandleave self id
do you actually need to reference the classes at class definition time ie class croom object person cperson person or more likely do you just need to use cperson in the methods of your class and vice versa eg class croom object def getperson self return cperson someone if the second there is no problem as by the time the method gets called rather than defined the module will be imported your sole problem is how to refer to it likely you are doing something like from croom import cperson or even import with circularly referencing modules you cannot do this as at the point one module imports another the original modules body will not have finished executing so the namespace will be incomplete instead use qualified references ie croom py import cperson class croom object def getperson self return cperson cperson someone here python does not need to lookup the attribute on the namespace until the method actually gets called by which time both modules should have completed their initialisation
QA
python module dependency ok have two modules each containing class the problem is their classes reference each other let us say for example had room module and person module containing croom and cperson the croom class contains infomation about the room and cperson list of every one in the room the cperson class however sometimes needs to use the croom class for the room its in for example to find the door or too see who else is in the room the problem is with the two modules importing each other just get an import error on which ever is being imported second in could solve this by only including the headers and since in both cases the classes just have pointers to the other class forward declaration would suffice for the header eg class cperson forward declare class croom std set cperson people is there anyway to do this in python other than placing both classes in the same module or something like that edit added python example showing problem using above classes error traceback most recent call last file projects python test main py line in from room import croom file projects python test room py line in from person import cperson file projects python test person py line in from room import croom importerror cannot import name croom room py from person import cperson class croom def init self self people self nextid def addperson self firstname secondname gender id self nextid self nextid person cperson firstname secondname gender id self people id person return person def finddoorandleave self personid del self people peopleid person py from room import croom class cperson def init self room firstname secondname gender id self room room self firstname firstname self secondname secondname self gender gender self id id def leave self self room finddoorandleave self id
you could just alias the second one import croom cperson croom cperson
QA
hiding password in python script have got python script which is creating an odbc connection the odbc connection is generated with connection string in this connection string have to include the username and password for this connection is there an easy way to obscure this password in the file just that nobody can read the password when am editing the file
the best solution assuming the username and password cannot be given at runtime by the user is probably separate source file containing only variable initialization for the username and password that is imported into your main code this file would only need editing when the credentials change otherwise if you are only worried about shoulder surfers with average memories base encoding is probably the easiest solution rot is just too easy to decode manually is not case sensitive and retains too much meaning in it is encrypted state encode your password and user id outside the python script have he script decode at runtime for use giving scripts credentials for automated tasks is always risky proposal your script should have its own credentials and the account it uses should have no access other than exactly what is necessary at least the password should be long and rather random
QA
python module dependency ok have two modules each containing class the problem is their classes reference each other let us say for example had room module and person module containing croom and cperson the croom class contains infomation about the room and cperson list of every one in the room the cperson class however sometimes needs to use the croom class for the room its in for example to find the door or too see who else is in the room the problem is with the two modules importing each other just get an import error on which ever is being imported second in could solve this by only including the headers and since in both cases the classes just have pointers to the other class forward declaration would suffice for the header eg class cperson forward declare class croom std set cperson people is there anyway to do this in python other than placing both classes in the same module or something like that edit added python example showing problem using above classes error traceback most recent call last file projects python test main py line in from room import croom file projects python test room py line in from person import cperson file projects python test person py line in from room import croom importerror cannot import name croom room py from person import cperson class croom def init self self people self nextid def addperson self firstname secondname gender id self nextid self nextid person cperson firstname secondname gender id self people id person return person def finddoorandleave self personid del self people peopleid person py from room import croom class cperson def init self room firstname secondname gender id self room room self firstname firstname self secondname secondname self gender gender self id id def leave self self room finddoorandleave self id
no need to import croom you do not use croom in person py so do not import it due to dynamic binding python does not need to see all class definitions at compile time if you actually do use croom in person py then change from room import croom to import room and use module qualified form room croom see effbot circular imports for details sidenote you probably have an error in self nextid line it increments nextid of instance not nextid of class to increment class counter use croom nextid or self class nextid
QA
hiding password in python script have got python script which is creating an odbc connection the odbc connection is generated with connection string in this connection string have to include the username and password for this connection is there an easy way to obscure this password in the file just that nobody can read the password when am editing the file
this is pretty common problem typically the best you can do is to either create some kind of ceasar cipher function to encode decode just not rot or the preferred method is to use an encryption key within reach of your program encode decode the password in which you can use file protection to protect access the key along those lines if your app runs as service daemon like webserver you can put your key into password protected keystore with the password input as part of the service startup it will take an admin to restart your app but you will have really good pretection for your configuration passwords
QA
python module dependency ok have two modules each containing class the problem is their classes reference each other let us say for example had room module and person module containing croom and cperson the croom class contains infomation about the room and cperson list of every one in the room the cperson class however sometimes needs to use the croom class for the room its in for example to find the door or too see who else is in the room the problem is with the two modules importing each other just get an import error on which ever is being imported second in could solve this by only including the headers and since in both cases the classes just have pointers to the other class forward declaration would suffice for the header eg class cperson forward declare class croom std set cperson people is there anyway to do this in python other than placing both classes in the same module or something like that edit added python example showing problem using above classes error traceback most recent call last file projects python test main py line in from room import croom file projects python test room py line in from person import cperson file projects python test person py line in from room import croom importerror cannot import name croom room py from person import cperson class croom def init self self people self nextid def addperson self firstname secondname gender id self nextid self nextid person cperson firstname secondname gender id self people id person return person def finddoorandleave self personid del self people peopleid person py from room import croom class cperson def init self room firstname secondname gender id self room room self firstname firstname self secondname secondname self gender gender self id id def leave self self room finddoorandleave self id
first naming your arguments with uppercase letters is confusing since python does not have formal static type checking we use the uppercase to mean class and lowercase to mean an argument second we do not bother with croom and cperson upper case is sufficient to indicate it is class the letter is not used room person third we do not usually put things in one class per file format file is python module and we more often import an entire module with all the classes and functions am aware those are habits you do not need to break them today but they do make it hard to read python does not use statically defined types like when you define method function you do not formally define the data type of the arguments to that function you merely list some variable names hopefully the client class will provide arguments of the correct type at run time when you make method request then python has to be sure the object has the method note python does not check to see if the object is the right type that does not matter it only checks to see if it has the right method the loop between room room and person person is problem you do not need to include one when defining the other it is safest to import the entire module here is room py import person class room object def init self self nextid self people def addperson self firstname secondname gender id self nextid self nextid theperson person person firstname secondname gender id self people id theperson return theperson works fine as long as person is eventually defined in the namespace where this is executing person does not have to be known when you define the class person does not have to be known until runtime when then person expression is evaluated here is person py import room class person object def something self aroom room room aroom addperson self firstname self lastname self gender your main py looks like this import room import person are room room addperson some name print
QA
most pythonic way of counting matching elements in something iterable have an iterable of entries on which would like to gather some simple statistics say the count of all numbers divisible by two and the count of all numbers divisible by three my first alternative while only iterating through the list once and avoiding the list expansion and keeping the split loop refactoring in mind looks rather bloated alt are xrange twos threes for in if twos if threes print twos print threes this looks rather nice but has the drawback of expanding the expression to list alt are xrange print len for in if print len for in if what would really like is something like function like this alt def count iterable for in iterable return are xrange print count for in if print count for in if but this looks lot like something that could be done without function the final variant is this alt are xrange print sum for in if print sum for in if and while the smallest and in my book probably the most elegant it does not feel like it expresses the intent very well so my question to you is which alternative do you like best to gather these types of stats feel free to supply your own alternative if you have something better to clear up some confusion below in reality my filter predicates are more complex than just this simple test the objects iterate over are larger and more complex than just numbers my filter functions are more different and hard to parameterize into one predicate
true booleans are coerced to unit integers and false booleans to zero integers so if you are happy to use scipy or numpy make an array of integers for each element of your sequence each array containing one element for each of your tests and sum over the arrays sum scipy array for in xrange array
QA
python module dependency ok have two modules each containing class the problem is their classes reference each other let us say for example had room module and person module containing croom and cperson the croom class contains infomation about the room and cperson list of every one in the room the cperson class however sometimes needs to use the croom class for the room its in for example to find the door or too see who else is in the room the problem is with the two modules importing each other just get an import error on which ever is being imported second in could solve this by only including the headers and since in both cases the classes just have pointers to the other class forward declaration would suffice for the header eg class cperson forward declare class croom std set cperson people is there anyway to do this in python other than placing both classes in the same module or something like that edit added python example showing problem using above classes error traceback most recent call last file projects python test main py line in from room import croom file projects python test room py line in from person import cperson file projects python test person py line in from room import croom importerror cannot import name croom room py from person import cperson class croom def init self self people self nextid def addperson self firstname secondname gender id self nextid self nextid person cperson firstname secondname gender id self people id person return person def finddoorandleave self personid del self people peopleid person py from room import croom class cperson def init self room firstname secondname gender id self room room self firstname firstname self secondname secondname self gender gender self id id def leave self self room finddoorandleave self id
lott if do not import anything into the room module get an undefined error instead imported it into the main module like you showed traceback most recent call last file projects python test main py line in ben room addperson ben blacker male file projects python test room py line in addperson person cperson firstname secondname gender id nameerror global name cperson is not defined also the reason there diffrent modules is where encountered the problem to start with the container class ieg the room is already several hundred lines so wanted the items in it eg the people in seperate file edit main py from room import croom from person import cperson room croom ben room addperson ben blacker male tom room addperson tom smith male ben leave
QA
best way to store and use large text file in python am creating networked server for boggle clone wrote in python which accepts users solves the boards and scores the player input the dictionary file am using is mb the enable dictionary and need it to be available to several game solver classes right now have it so that each class iterates through the file line by line and generates hash table associative array but the more solver classes instantiate the more memory it takes up what would like to do is import the dictionary file once and pass it to each solver instance as they need it but what is the best way to do this should import the dictionary in the global space then access it in the solver class as globals dictionary or should import the dictionary then pass it as an argument to the class constructor is one of these better than the other is there third option
even though it is essentially singleton at this point the usual arguments against globals apply for pythonic singleton substitute look up the borg object that is really the only difference once the dictionary object is created you are only binding new references as you pass it along unless if you explicitly perform deep copy it makes sense that it is centrally constructed once and only once so long as each solver instance does not require private copy for modification
QA
doing crud in turbogears are there any good packages or methods for doing extensive crud create retrieve update delete interfaces in the turbogears framework the fastdatagrid widget is too much of black box to be useful and crudtemplate looks like more trouble than rolling my own ideas suggestions
after doing some more digging and hacking it turns out to not be terribly hard to drop the cakewalk interface into an application it is not pretty without lot of work but it works right away
QA
most pythonic way of counting matching elements in something iterable have an iterable of entries on which would like to gather some simple statistics say the count of all numbers divisible by two and the count of all numbers divisible by three my first alternative while only iterating through the list once and avoiding the list expansion and keeping the split loop refactoring in mind looks rather bloated alt are xrange twos threes for in if twos if threes print twos print threes this looks rather nice but has the drawback of expanding the expression to list alt are xrange print len for in if print len for in if what would really like is something like function like this alt def count iterable for in iterable return are xrange print count for in if print count for in if but this looks lot like something that could be done without function the final variant is this alt are xrange print sum for in if print sum for in if and while the smallest and in my book probably the most elegant it does not feel like it expresses the intent very well so my question to you is which alternative do you like best to gather these types of stats feel free to supply your own alternative if you have something better to clear up some confusion below in reality my filter predicates are more complex than just this simple test the objects iterate over are larger and more complex than just numbers my filter functions are more different and hard to parameterize into one predicate
alt for the reason that it does not use memory proportional to the number of hits given pathological case like xrange one trillion many of the other offered solutions would fail badly
QA
best way to store and use large text file in python am creating networked server for boggle clone wrote in python which accepts users solves the boards and scores the player input the dictionary file am using is mb the enable dictionary and need it to be available to several game solver classes right now have it so that each class iterates through the file line by line and generates hash table associative array but the more solver classes instantiate the more memory it takes up what would like to do is import the dictionary file once and pass it to each solver instance as they need it but what is the best way to do this should import the dictionary in the global space then access it in the solver class as globals dictionary or should import the dictionary then pass it as an argument to the class constructor is one of these better than the other is there third option
if you create dictionary py module containing code which reads the file and builds dictionary this code will only be executed the first time it is imported further imports will return reference to the existing module instance as such your classes can import dictionary dictionary words whatever where dictionary py has words read file and add to words
QA
emacs and python recently started learning emacs went through the tutorial read some introductory articles so far so good now want to use it for python development from what understand there are two separate python modes for emacs python mode el which is part of the python project and python el which is part of emacs read all information could find but most of it seems fairly outdated and am still confused the questions what is their difference which mode should install and use are there other emacs add ons that are essential for python development relevant links emacseditor wiki python org pythonmode emacswiki org
this site has description of how to get python code completion in emacs ropemacs is way to get rope to work in emacs have not had extensive experience with either but they are worth looking into
QA
getting mac address need cross platform method of determining the mac address of computer at run time for windows the wmi module can be used and the only method under linux could find was to run ifconfig and run regex across its output do not like using package that only works on one os and parsing the output of another program does not seem very elegant not to mention error prone does anyone know cross platform method windows and linux method to get the mac address if not does anyone know any more elegant methods then those listed above
netifaces is good module to use for getting the mac address and other addresses it is crossplatform and makes bit more sense than using socket or uuid import netifaces netifaces interfaces lo eth tun netifaces ifaddresses eth netifaces af link addr broadcast ff ff ff ff ff ff pypi location good intro to netifaces
QA
getting mac address need cross platform method of determining the mac address of computer at run time for windows the wmi module can be used and the only method under linux could find was to run ifconfig and run regex across its output do not like using package that only works on one os and parsing the output of another program does not seem very elegant not to mention error prone does anyone know cross platform method windows and linux method to get the mac address if not does anyone know any more elegant methods then those listed above
do not know of unified way but here is something that you might find useful http www codeguru com cpp network networkinformation article php what would do in this case would be to wrap these up into function and based on the os it would run the proper command parse as required and return only the mac address formatted as you want its ofcourse all the same except that you only have to do it once and it looks cleaner from the main code
QA
getting mac address need cross platform method of determining the mac address of computer at run time for windows the wmi module can be used and the only method under linux could find was to run ifconfig and run regex across its output do not like using package that only works on one os and parsing the output of another program does not seem very elegant not to mention error prone does anyone know cross platform method windows and linux method to get the mac address if not does anyone know any more elegant methods then those listed above
python includes an uuid implementation which in at least one version needs the mac address you can import the mac finding function into your own code easily from uuid import getnode as get mac mac get mac the return value is the mac address as bit integer
QA
best way to store and use large text file in python am creating networked server for boggle clone wrote in python which accepts users solves the boards and scores the player input the dictionary file am using is mb the enable dictionary and need it to be available to several game solver classes right now have it so that each class iterates through the file line by line and generates hash table associative array but the more solver classes instantiate the more memory it takes up what would like to do is import the dictionary file once and pass it to each solver instance as they need it but what is the best way to do this should import the dictionary in the global space then access it in the solver class as globals dictionary or should import the dictionary then pass it as an argument to the class constructor is one of these better than the other is there third option
depending on what your dict contains you may be interested in the shelve or anydbm modules they give you dict like interfaces just strings as keys and items for anydbm and strings as keys and any python object as item for shelve but the data is actually in dbm file gdbm ndbm dbhash bsddb depending on what is available on the platform you probably still want to share the actual database between classes as you are asking for but it would avoid the parsing the textfile step as well as the keeping it all in memory bit
QA
best way to store and use large text file in python am creating networked server for boggle clone wrote in python which accepts users solves the boards and scores the player input the dictionary file am using is mb the enable dictionary and need it to be available to several game solver classes right now have it so that each class iterates through the file line by line and generates hash table associative array but the more solver classes instantiate the more memory it takes up what would like to do is import the dictionary file once and pass it to each solver instance as they need it but what is the best way to do this should import the dictionary in the global space then access it in the solver class as globals dictionary or should import the dictionary then pass it as an argument to the class constructor is one of these better than the other is there third option
adam remember that in python when you say read dict from file you are not actually copying and thus using more memory you are merely making another reference to the same object so basically any of the solutions you propose will be far better in terms of memory usage basically read in the dictionary once and then hang on to reference to that whether you do it with global variable or pass it to each instance or something else you will be referencing the same object and not duplicating it which one is most pythonic that is whole nother can of worms but here is what would do personally def main args run initialization stuff dictionary read dictionary from file solvers solver class dictionary dictionary for in len number of solvers hth
QA
what is the naming convention in python for variable and function names coming from background the naming convention for variables and method names are usually either camelcase or pascal case example string thisismyvariable public void thisismymethod in python have seen the above but have also seen underscores being used python example this is my variable def this is my function is there more preferable definitive coding style for python
see python pep function names should be lowercase with words separated by underscores as necessary to improve readability mixedcase is allowed only in contexts where that is already the prevailing style variables use the function naming rules lowercase with words separated by underscores as necessary to improve readability personally deviate from this because also prefer mixedcase over lower case for my own projects
QA
what is the naming convention in python for variable and function names coming from background the naming convention for variables and method names are usually either camelcase or pascal case example string thisismyvariable public void thisismymethod in python have seen the above but have also seen underscores being used python example this is my variable def this is my function is there more preferable definitive coding style for python
the coding style is usually part of an organization internal policy convention standards but think in general the all lower case underscore separator style also called snake case is most common in python
QA
what is the naming convention in python for variable and function names coming from background the naming convention for variables and method names are usually either camelcase or pascal case example string thisismyvariable public void thisismymethod in python have seen the above but have also seen underscores being used python example this is my variable def this is my function is there more preferable definitive coding style for python
there is pep as other answers show but pep is only the styleguide for the standard library and it is only taken as gospel therein one of the most frequent deviations of pep for other pieces of code is the variable naming specifically for methods there is no single predominate style although considering the volume of code that uses mixedcase if one were to make strict census one would probably end up with version of pep with mixedcase there is little other deviation from pep that is quite as common
QA
what is the naming convention in python for variable and function names coming from background the naming convention for variables and method names are usually either camelcase or pascal case example string thisismyvariable public void thisismymethod in python have seen the above but have also seen underscores being used python example this is my variable def this is my function is there more preferable definitive coding style for python
most python people prefer underscores but even am using python since more than years right now still do not like them they just look ugly to me but maybe that is all the java in my head simply like camelcase better since it fits better with the way classes are named it feels more logical to have someclass dosomething than someclass do something if you look around in the global module index in python you will find both which is due to the fact that it is collection of libraries from various sources that grew overtime and not something that was developed by one company like sun with strict coding rules would say the bottom line is use whatever you like better it is just question of personal taste
QA
python web services elementree has become the accepted standard for interacting with xml what is the prevalent web service soap library in use today
am not sure about an accepted standard but have found soappy to be fairly straight forward and useful library for handling soap based web services soapy is soap xml schema library for python given either wsdl or sdl document soapy discovers the published api for web service and exposes it to python applications as transparently as possible ibm provide good walk through and example on their site for getting started with soappy soappy no longer under active development but is instead being folded into zolera soap infrastructure zsi at the python web services project this project however has alos not seen much activity since november last year
QA
nginx fastcgi truncation problem am running django site using the fastcgi interface to nginx however some pages are being served truncated the page source just stops sometimes in the middle of tag how do fix this let me know what extra information is needed and will post it details am using flup and spawning the fastcgi server with the following command python manage py runfcgi umask maxchildren maxspare minspare method prefork socket path to runfiles django sock pidfile path to runfiles django pid the nginx config is as follows search and replace this project location pid path to runfiles nginx pid worker processes error log path to runfiles error log events worker connections use epoll http default nginx location include etc nginx mime types default type application octet stream log format main remote addr remote user time local request status bytes sent http referer http user agent gzip ratio client header timeout client body timeout send timeout connection pool size client header buffer size large client header buffers request pool size output buffers postpone output sendfile on tcp nopush on keepalive timeout tcp nodelay on client max body size client body buffer size proxy connect timeout proxy send timeout proxy read timeout client body temp path path to runfiles client body temp proxy temp path path to runfiles proxy temp fastcgi temp path path to runfiles fastcgi temp gzip on gzip min length gzip buffers gzip types text plain text html application javascript text xml text css ignore invalid headers on server listen server name alpha sonyalabs com index index html root path to django root static static resources location static root path to django root expires break location host and port to fastcgi server fastcgi pass unix path to runfiles django sock fastcgi param path info fastcgi script name fastcgi param request method request method fastcgi param query string query string fastcgi param content type content type fastcgi param content length content length fastcgi pass header authorization fastcgi intercept errors off location html root usr local nginx access log off location html root usr local nginx access log off location html root usr local nginx access log off location gif empty gif access log off access log path to runfiles localhost access log main error log path to runfiles localhost error log
what fastcgi interface are you using and how is it flup if yes paste the way you spawn the server and how it is hooked into nginx without that information it is just guessing what could go wrong possible problems nginx is buggy at least lighttpd has horrible fastcgi bugs would not wonder if nginx has some too django is dying with traceback in an internal system that is not properly catched and closes the fastcgi server which you cannot see from the client in that situation wrap the fastcgi server application call and try except it to print the exception but server log and config would be great
QA
how many bytes per element are there in python list tuple for example how much memory is required to store list of one million bit integers alist range or list range in python
new function getsizeof takes python object and returns the amount of memory used by the object measured in bytes built in objects return correct results third party extensions may not but can define sizeof method to return the object size kveretennicov nosignal py rc python python rc rc sep gcc ubuntu ubuntu on linux import sys sys getsizeof range sys getsizeof tuple range obviously returned numbers do not include memory consumed by contained objects sys getsizeof
QA
how many bytes per element are there in python list tuple for example how much memory is required to store list of one million bit integers alist range or list range in python
am wary of why you are asking are you trying to figure out how much memory you will need for given implementation say you are going to read widgets and want to know how much ram it will suck if that is the case rather than trying to figure out how much ram each widget takes figure out how much ram say widgets takes and multiply up to get your actual size
QA
getting mac address need cross platform method of determining the mac address of computer at run time for windows the wmi module can be used and the only method under linux could find was to run ifconfig and run regex across its output do not like using package that only works on one os and parsing the output of another program does not seem very elegant not to mention error prone does anyone know cross platform method windows and linux method to get the mac address if not does anyone know any more elegant methods then those listed above
note that you can build your own cross platform library in python using conditional imports import platform if platform system linux import linuxmac mac address linuxmac get mac address elif platform system windows etc this will allow you to use os system calls or platform specific libraries
QA
what is the difference between ruby and python versions of self have done some python but have just now starting to use ruby could use good explanation of the difference between self in these two languages obvious on first glance self is not keyword in python but there is self like value no matter what you call it python methods receive self as an explicit argument whereas ruby does not ruby sometimes has methods explicitly defined as part of self using dot notation initial googling reveals http rubylearning com satishtalim ruby self html http www ibiblio org swap byteofpython read self html
well do not know much about ruby but the obvious point about python self is that it is not keyword it is just the name of an argument that is sent to your method you can use any name you like for this argument self is just convention for example class def init val val def print prints the number on the terminal in the constructor the self object is actually called but in the method it is called update in october guido pointed out that having an explicit self was also necessary to allow python decorators to be general enough to work on pure functions methods or classmethods http neopythonic blogspot com why explicit self has to stay html
QA
date change notification in tkinter app win does anyone know if it is possible and if yes how to bind an event python tkinter on ms windows to system date change know can have after events checking once in while am asking if can somehow have an event fired whenever the system date time changes either automatically for daylight saving time or manually ms windows sends such events to applications and tkinter does receive them know because if have an after timer waiting and set the date time after the timer expiration the timer event fires instantly
know because if have an after timer waiting and set the date time after the timer expiration the timer event fires instantly that could just mean that tkinter or tk is polling the system clock as part of the event loop to figure out when to run timers if you are using windows mark hammond book notes that you can use the win evtlogutil module to respond to changes in the windows event log basically it works like this import win evtlogutil def onevent record do something with the event log record win evtlogutil feedeventlogrecords onevent but you will need to get docs on the structure of the event records do not feel like typing out the whole chapter sorry also do not know if date changes turn up in the event log anyway really though is it so bad to just poll the system clock it seems easiest and do not think it would slow you down much finally comment do not know about your country but here in nz daylight savings does not involve date change only the time changes from am am or vice versa
QA
hiding password in python script have got python script which is creating an odbc connection the odbc connection is generated with connection string in this connection string have to include the username and password for this connection is there an easy way to obscure this password in the file just that nobody can read the password when am editing the file
base is the way to go for your simple needs there is no need to import anything your string encode base ew cibzdhjpbmc decode base your string
QA
hiding password in python script have got python script which is creating an odbc connection the odbc connection is generated with connection string in this connection string have to include the username and password for this connection is there an easy way to obscure this password in the file just that nobody can read the password when am editing the file
place the configuration information in encrypted config file query this info in your code using an key place this key in separate file per environment and do not store it with your code
QA
python web services elementree has become the accepted standard for interacting with xml what is the prevalent web service soap library in use today
soaplib is very easy to use and seems to be active http wiki github com jkp soaplib
QA
what is the difference between ruby and python versions of self have done some python but have just now starting to use ruby could use good explanation of the difference between self in these two languages obvious on first glance self is not keyword in python but there is self like value no matter what you call it python methods receive self as an explicit argument whereas ruby does not ruby sometimes has methods explicitly defined as part of self using dot notation initial googling reveals http rubylearning com satishtalim ruby self html http www ibiblio org swap byteofpython read self html
self is used only as convention you can use spam bacon or sausage instead of self and get the same result it is just the first argument passed to bound methods but stick to using self as it will confuse others and some editors
QA
accurate timestamping in python have been building an error logging app recently and was after way of accurately timestamping the incoming data when say accurately mean each timestamp should be accurate relative to each other no need to sync to an atomic clock or anything like that have been using datetime now as first stab but this is not perfect for in range datetime datetime now datetime datetime datetime datetime datetime datetime datetime datetime datetime datetime datetime datetime datetime datetime datetime datetime datetime datetime datetime datetime datetime datetime datetime datetime etc the changes between clocks for the first second of samples looks like this usecs difference so it looks like the timer data is only updated every ms on my machine the problem comes when we come to analyse the data because sorting by something other than the timestamp and then sorting by timestamp again can leave the data in the wrong order chronologically it would be nice to have the time stamps accurate to the point that any call to the time stamp generator gives unique timestamp had been considering some methods involving using time clock call added to starting datetime but would appreciate solution that would work accurately across threads on the same machine any suggestions would be very gratefully received
thank you all for your contributions they have all be very useful brian answer seems closest to what eventually went with deal with it but use sort of unique identifier see below so have accepted his answer managed to consolidate all the various data receivers into single thread which is where the timestamping is now done using my new accurratetimestamp class what have done works as long as the time stamp is the first thing to use the clock as lott stipulates without realtime os they are never going to be absolutely perfect really only wanted something that would let me see relative to each incoming chunk of data when things were being received so what have got below will work well thanks again everyone import time class accuratetimestamp simple class to provide very accurate means of time stamping some data do the class wide initial time stamp to synchronise calls to time clock to single time stamp initialtimestamp time time time clock def init self constructor for the accuratetimestamp class this makes stamp based on the current time which should be more accurate than anything you can get out of time time note this time stamp will only work if nothing has called clock in this instance of the python interpreter get the time since the first of call to time clock offset time clock get the current accurate time currenttime accuratetimestamp initialtimestamp offset split the time into whole seconds and the portion after the fraction self accurateseconds int currenttime self accuratepastsecond currenttime self accurateseconds def getaccuratetimestampstring timestamp function to produce timestamp of the form representing the time stamp timestamp get struct time representing the number of whole seconds since the epoch that we can use to format the time stamp wholesecondsintimestamp time localtime timestamp accurateseconds convert the whole seconds and whatever fraction of second comes after into couple of strings wholesecondsstring time strftime wholesecondsintimestamp fractionaftersecondstring str int timestamp accuratepastsecond return our shiny new accurate time stamp return wholesecondsstring fractionaftersecondstring if name main for in range timestamp accuratetimestamp print getaccuratetimestampstring timestamp
QA
what is the difference between ruby and python versions of self have done some python but have just now starting to use ruby could use good explanation of the difference between self in these two languages obvious on first glance self is not keyword in python but there is self like value no matter what you call it python methods receive self as an explicit argument whereas ruby does not ruby sometimes has methods explicitly defined as part of self using dot notation initial googling reveals http rubylearning com satishtalim ruby self html http www ibiblio org swap byteofpython read self html
python is designed to support more than just object oriented programming preserving the same interface between methods and functions let us the two styles interoperate more cleanly ruby was built from the ground up to be object oriented even the literals are objects evaluate class and you get fixnum the language was built such that self is reserved keyword that returns the current instance wherever you are if you are inside an instance method of one of your class self is reference to said instance if you are in the definition of the class itself not in method self is the class itself class puts am self def instance method puts instance method end def self class method puts class method end end at class definition time am will be printed the straight def defines an instance method whereas the def self xxx defines class method new instance method instance method class method class method
QA
which is the best way to get list of running processes in unix with python am trying import commands print commands getoutput ps you but it does not work on os os instead of commands gives the same output user pid cpu mem vsz rss tt stat started time command nothing more
it works if you use os instead of commands import os print os system ps you
QA
which is the best way to get list of running processes in unix with python am trying import commands print commands getoutput ps you but it does not work on os os instead of commands gives the same output user pid cpu mem vsz rss tt stat started time command nothing more
the cross platform replacement for commands is subprocess see the subprocess module documentation the replacing older modules section includes how to get output from command of course you still have to pass the right arguments to ps for the platform you are on python cannot help you with that and though have seen occasional mention of third party libraries that try to do this they usually only work on few systems like strictly sysv style strictly bsd style or just systems with proc
QA
which is the best way to get list of running processes in unix with python am trying import commands print commands getoutput ps you but it does not work on os os instead of commands gives the same output user pid cpu mem vsz rss tt stat started time command nothing more
have tried in on os and seems to work just fine print commands getoutput ps you uid pid tty time cmd sbin launchd usr libexec kextd etc python
QA
which is the best way to get list of running processes in unix with python am trying import commands print commands getoutput ps you but it does not work on os os instead of commands gives the same output user pid cpu mem vsz rss tt stat started time command nothing more
this works on mac os note the capital you option perhaps that is been your problem import subprocess ps subprocess popen ps you she will true stdout subprocess pipe print ps stdout read ps stdout close ps wait here is the python version python feb gcc apple computer inc build on darwin
QA
model limit choices to user user went to all the documentation also went to the irc channel by the way great community and they told me that is not possible to create model and limit choices in field where the current user is in foreignkey will try to explain this with an example class project models model name models charfield max length employees models manytomanyfield profile limit choices to active class timeworked models model project models foreignkey project limit choices to user user hours models positiveintegerfield of course that code does not work because there is no user object but that was my idea and was trying to send the object user to the model to just limit the choices where the current user has projects do not want to see projects where am not in thank you very much if you can help me or give me any advice do not want to you write all the app just tip how to deal with that have days with this in my head and cannot figure it out update the solution is here http collingrady wordpress com useful form tricks in django sending request user to model
model itself does not know anything about current user but you can give this user in view to the form which operates models objects and in form reset choices for necessary field if you need this on admin site you can try raw id admin along with django granular permissions http code google com django granular permissions but could not rapidly get it working on my django but it seems to be fresh enough for so at last if you heavily need selectbox in admin then you will need to hack django contrib admin itself
QA
model limit choices to user user went to all the documentation also went to the irc channel by the way great community and they told me that is not possible to create model and limit choices in field where the current user is in foreignkey will try to explain this with an example class project models model name models charfield max length employees models manytomanyfield profile limit choices to active class timeworked models model project models foreignkey project limit choices to user user hours models positiveintegerfield of course that code does not work because there is no user object but that was my idea and was trying to send the object user to the model to just limit the choices where the current user has projects do not want to see projects where am not in thank you very much if you can help me or give me any advice do not want to you write all the app just tip how to deal with that have days with this in my head and cannot figure it out update the solution is here http collingrady wordpress com useful form tricks in django sending request user to model
am not sure that fully understand exactly what you want to do but think that there is good chance that you will get at least part the way there using custom manager in particular do not try to define your models with restrictions to the current user but create manager that only returns objects that match the current user
QA
template lib engine in python running with jython am searching template lib or template engine for generating html xml that runs under jython jython alpha is ok
jinja is pretty cool and seems to work on jython
QA
django python grouping objects by common set from many to many relationships this is part algorithm logic question how to do it part implementation question how to do it best am working with django so thought would share with that in python it is worth mentioning that the problem is somewhat related to how do use pythons itertoolsgroupby suppose you are given two django model derived classes from django db import models class car models model mods models manytomanyfield representative and from django db import models class mods models model how does one get list of cars grouped by cars with common set of mods want to get class likeso cars by common mods mods cars mods cars mods cars mods cars have been thinking of something like def cars by common mods cars cars objects all mod list for car in cars mod list append car car mods list car mods all ret for key mods group in groupby list mods lambda set mods ret append mods group return ret however that does not work because perhaps among other reasons the groupby does not seem to group by the mods sets guess the mod list has to be sorted to work with groupby all to say am confident there is something simple and elegant out there that will be both enlightening and illuminating cheers thanks
check regroup it is only for templates but guess this kind of classification belongs to the presentation layer anyway
QA
how does one do the equivalent of import from module with python import function given string with module name how do you import everything in the module as if you had called from module import given string module how does one get the equivalent of the following import fromlist this does not seem to perform as expected as it does not import anything thanks
the underlying problem is that am developing some django but on more than one host with colleagues all with different settings was hoping to do something like this in the project settings py file from platform import node settings files bmh lan settings bmh py import settings files node it seemed simple solution thus elegant but would agree that it has smell to it and the simplicity goes out the loop when you have to use logic like what john millikin posted thanks here is essentially the solution went with from platform import node from settings global import node if bmh lan from settings bmh import add your own here else raise exception no host settings for see settings py node which works fine for our purposes
QA
what is the naming convention in python for variable and function names coming from background the naming convention for variables and method names are usually either camelcase or pascal case example string thisismyvariable public void thisismymethod in python have seen the above but have also seen underscores being used python example this is my variable def this is my function is there more preferable definitive coding style for python
personally try to use camelcase for classes mixedcase methods and functions variables are usually underscore separated when can remember this way can tell at glance what exactly am calling rather than everything looking the same
QA
getting mac address need cross platform method of determining the mac address of computer at run time for windows the wmi module can be used and the only method under linux could find was to run ifconfig and run regex across its output do not like using package that only works on one os and parsing the output of another program does not seem very elegant not to mention error prone does anyone know cross platform method windows and linux method to get the mac address if not does anyone know any more elegant methods then those listed above
one other thing that you should note is that uuid getnode can fake the mac addr by returning random bit number which may not be what you are expecting also there is no explicit indication that the mac address has been faked but you could detect it by calling getnode twice and seeing if the result varies if the same value is returned by both calls you have the mac address otherwise you are getting faked address print uuid getnode doc get the hardware address as bit positive integer the first time this runs it may launch separate program which could be quite slow if all attempts to obtain the hardware address fail we choose random bit number with its eighth bit set to as recommended in rfc
QA
what is the naming convention in python for variable and function names coming from background the naming convention for variables and method names are usually either camelcase or pascal case example string thisismyvariable public void thisismymethod in python have seen the above but have also seen underscores being used python example this is my variable def this is my function is there more preferable definitive coding style for python
david goodger in code like pythonista here describes the pep recommendations as follows joined lower for functions methods attributes variables joined lower or all caps for constants studlycaps for classes camelcase only to conform to pre existing conventions
QA
what is the naming convention in python for variable and function names coming from background the naming convention for variables and method names are usually either camelcase or pascal case example string thisismyvariable public void thisismymethod in python have seen the above but have also seen underscores being used python example this is my variable def this is my function is there more preferable definitive coding style for python
typically one follow the conventions used in the language standard library
QA
are there any other good alternatives to zc buildout and or virtualenv for installing non python dependencies am member of team that is about to launch beta of python django specifically based web site and accompanying suite of backend tools the team itself has doubled in size from to over the past few weeks and we expect continued growth for the next couple of months at least one issue that has started to plague us is getting everyone up to speed in terms of getting their development environment configured and having all the right eggs installed etc am looking for ways to simplify this process and make it less error prone both zc buildout and virtualenv look like they would be good tools for addressing this problem but both seem to concentrate primarily on the python specific issues we have couple of small subprojects in other languages java and ruby specifically as well as numerous python extensions that have to be compiled natively lxml mysql drivers etc in fact one of the biggest thorns in our side has been getting some of these extensions compiled against appropriate versions of the shared libraries so as to avoid segfaults malloc errors and all sorts of similar issues it does not help that out of people we have different development environments leopard on ppc leopard on intel ubuntu and windows ultimately what would be ideal would be something that works roughly like this from the dos unix prompt git clone repository url python setup env py that then does what zc buildout virtualenv does copy symlink the python interpreter provide clean space to install eggs then installs all required eggs including installing any native shared library dependencies installs the ruby project the java project etc obviously this would be useful for both getting development environments up as well as deploying on staging production servers ideally would like for the tool that accomplishes this to be written in extensible via python since that is and always will be the lingua franca of our team but am open to solutions in other languages so my question then is does anyone have any suggestions for better alternatives or any experiences they can share using one of these solutions to handle larger broader install bases
basically you are looking for cross platform software package installer on the lines of apt get yum etc am not sure something like that exists an alternative might be specifying the list of packages that need to be installed via the os specific package management system such as fink or darwinports for mac os and having script that sets up the build environment for the in house code
QA
what is lambda binding in python understand what are lambda functions in python but cannot find what is the meaning of lambda binding by searching the python docs link to read about it would be great trivial explained example would be even better thank you
where have you seen the phrase used binding in python generally refers to the process by which variable name ends up pointing to specific object whether by assignment or parameter passing or some other means dict foo bar zip zap zig zag binds to newly created dict object binds to that same dictionary def crunch param print param crunch binds the parameter param in the function crunch to that same dict again so would guess that lambda binding refers to the process of binding lambda function to variable name or maybe binding its named parameters to specific objects there is pretty good explanation of binding in the language reference at http docs python org ref naming html
QA
emulation of lex like functionality in perl or python here is the deal is there way to have strings tokenized in line based on multiple regexes one example have to get all href tags their corresponding text and some other text based on different regex so have expressions and would like to tokenize the line and extract tokens of text matching every expression have actually done this using flex not to be confused with adobe which is an implementation of the good old lex lex provides an elegant way to do this by executing actions based on expressions one can control the way lex reading file too block line based read the problem is that flex actually produces code which actually does the tokenizing job have make file which wraps all these things was wondering if perl python can in some way do the same thing its just that would like to do everything like in single programming language itself tokenizing is just one of the things that want to do as part of my application apart from perl or python can any language functional also do this did read about ply and antlr here http stackoverflow com questions parsing where can learn about it but is there way to do it naturally in python itself pardon my ignorance but are these tools used in any popular products services thank you
have you looked at pyparsing from their homepage here is program to parse hello world or any greeting of the form from pyparsing import word alphas greet word alphas word alphas grammar defined here hello hello world print hello greet parsestring hello the program outputs the following hello world hello world
QA
emulation of lex like functionality in perl or python here is the deal is there way to have strings tokenized in line based on multiple regexes one example have to get all href tags their corresponding text and some other text based on different regex so have expressions and would like to tokenize the line and extract tokens of text matching every expression have actually done this using flex not to be confused with adobe which is an implementation of the good old lex lex provides an elegant way to do this by executing actions based on expressions one can control the way lex reading file too block line based read the problem is that flex actually produces code which actually does the tokenizing job have make file which wraps all these things was wondering if perl python can in some way do the same thing its just that would like to do everything like in single programming language itself tokenizing is just one of the things that want to do as part of my application apart from perl or python can any language functional also do this did read about ply and antlr here http stackoverflow com questions parsing where can learn about it but is there way to do it naturally in python itself pardon my ignorance but are these tools used in any popular products services thank you
sounds like you really just want to parse html recommend looking at any of the wonderful packages for doing so beautifulsoup lxml html html lib or you can use parser like one of the following pyparsing dparser glr parser with good python bindings antlr recursive decent parser generator that can generate python code this example is from the beautifulsoup documentation from beautifulsoup import beautifulsoup soupstrainer import re links soupstrainer tag for tag in beautifulsoup doc parseonlythese links href http www bob com success href http www bob com plasma experiments href http www boogabooga net boogabooga linkstobob soupstrainer href re compile bob com tag for tag in beautifulsoup doc parseonlythese linkstobob href http www bob com success href http www bob com plasma experiments
QA
what is lambda binding in python understand what are lambda functions in python but cannot find what is the meaning of lambda binding by searching the python docs link to read about it would be great trivial explained example would be even better thank you
first general definition when program or function statement is executed the current values of formal parameters are saved on the stack and within the scope of the statement they are bound to the values of the actual arguments made in the call when the statement is exited the original values of those formal arguments are restored this protocol is fully recursive if within the body of statement something is done that causes the formal parameters to be bound again to new values the lambda binding scheme guarantees that this will all happen in an orderly manner now there is an excellent python example in discussion here there is only one binding for doing just changes the value in the pre existing binding that is why def foo lambda lambda return returns two functions that both return if there was new binding after the the functions would return different values assuming you do not call foo of course also assuming nested scopes
QA
django admin site not displaying manytomanyfield relationship am working on what think is pretty standard django site but am having trouble getting my admin section to display the proper fields here is my models py class tech models model name models charfield max length class project models model title models charfield max length techs models manytomanyfield tech in other words project can have different tech objects and different tech objects can belong to different projects project was created with python and django project was and sql server however the admin site does not display any ui for the tech objects here is my admin py class techinline admin tabularinline model tech extra class projectadmin admin modeladmin fields title inlines list display title admin site register project projectadmin have tried adding the techinline class to the inlines list but that causes class home projects models tech has no foreignkey to class home projects models project error also tried adding techs to the fields list but that gives no such table projects project techs error verified and there is no projects project techs table but there is projects tech one did something perhaps get screwed up in my syncdb am using sqlite as my database if that helps
have tried adding the techinline class to the inlines list but that causes techinline not defined is that straight copy paste it looks like you just made typo try techinline instead of techinline if your syncdb did not create the proper table you can do it manually execute this command python manage py sqlreset myapp and look for the definition for the projects project techs table copy and paste it into the client for your database
QA
what is lambda binding in python understand what are lambda functions in python but cannot find what is the meaning of lambda binding by searching the python docs link to read about it would be great trivial explained example would be even better thank you
have never heard that term but one explanation could be the default parameter hack used to assign value directly to lambda parameter using swati example def foo lambda lambda return aa bb foo aa prints bb prints
QA
emulation of lex like functionality in perl or python here is the deal is there way to have strings tokenized in line based on multiple regexes one example have to get all href tags their corresponding text and some other text based on different regex so have expressions and would like to tokenize the line and extract tokens of text matching every expression have actually done this using flex not to be confused with adobe which is an implementation of the good old lex lex provides an elegant way to do this by executing actions based on expressions one can control the way lex reading file too block line based read the problem is that flex actually produces code which actually does the tokenizing job have make file which wraps all these things was wondering if perl python can in some way do the same thing its just that would like to do everything like in single programming language itself tokenizing is just one of the things that want to do as part of my application apart from perl or python can any language functional also do this did read about ply and antlr here http stackoverflow com questions parsing where can learn about it but is there way to do it naturally in python itself pardon my ignorance but are these tools used in any popular products services thank you
look at documentation for following modules on cpan html treebuilder html tableextract and parse recdescent have used these modules to process quite large and complex web pages
QA
are there any other good alternatives to zc buildout and or virtualenv for installing non python dependencies am member of team that is about to launch beta of python django specifically based web site and accompanying suite of backend tools the team itself has doubled in size from to over the past few weeks and we expect continued growth for the next couple of months at least one issue that has started to plague us is getting everyone up to speed in terms of getting their development environment configured and having all the right eggs installed etc am looking for ways to simplify this process and make it less error prone both zc buildout and virtualenv look like they would be good tools for addressing this problem but both seem to concentrate primarily on the python specific issues we have couple of small subprojects in other languages java and ruby specifically as well as numerous python extensions that have to be compiled natively lxml mysql drivers etc in fact one of the biggest thorns in our side has been getting some of these extensions compiled against appropriate versions of the shared libraries so as to avoid segfaults malloc errors and all sorts of similar issues it does not help that out of people we have different development environments leopard on ppc leopard on intel ubuntu and windows ultimately what would be ideal would be something that works roughly like this from the dos unix prompt git clone repository url python setup env py that then does what zc buildout virtualenv does copy symlink the python interpreter provide clean space to install eggs then installs all required eggs including installing any native shared library dependencies installs the ruby project the java project etc obviously this would be useful for both getting development environments up as well as deploying on staging production servers ideally would like for the tool that accomplishes this to be written in extensible via python since that is and always will be the lingua franca of our team but am open to solutions in other languages so my question then is does anyone have any suggestions for better alternatives or any experiences they can share using one of these solutions to handle larger broader install bases
have continued to research this issue since posted the question it looks like there are some attempts to address some of the needs outlined minitage and puppet which take different approaches but both may accomplish what want although minitage does not explicitly state that it supports windows lacking any better options will try to make either one of these or just extensive customized use of zc buildout work for our needs but still feel like there must be better options out there
QA
django python grouping objects by common set from many to many relationships this is part algorithm logic question how to do it part implementation question how to do it best am working with django so thought would share with that in python it is worth mentioning that the problem is somewhat related to how do use pythons itertoolsgroupby suppose you are given two django model derived classes from django db import models class car models model mods models manytomanyfield representative and from django db import models class mods models model how does one get list of cars grouped by cars with common set of mods want to get class likeso cars by common mods mods cars mods cars mods cars mods cars have been thinking of something like def cars by common mods cars cars objects all mod list for car in cars mod list append car car mods list car mods all ret for key mods group in groupby list mods lambda set mods ret append mods group return ret however that does not work because perhaps among other reasons the groupby does not seem to group by the mods sets guess the mod list has to be sorted to work with groupby all to say am confident there is something simple and elegant out there that will be both enlightening and illuminating cheers thanks
have you tried sorting the list first the algorithm you proposed should work albeit with lots of database hits import itertools cars car mods car mods car mods car mods car mods car mods car mods car mods cars sort key lambda car car mods cars by common mods for in itertools groupby cars lambda car car mods cars by common mods frozenset car car for car in print cars by common mods now about those queries import collections import itertools from operator import itemgetter from django db import connection cursor connection cursor cursor execute select car id mod id from someapp car mod order by cars collections defaultdict list for row in cursor fetchall cars row append row here is one prepared earlier which emulates the sample data we have been working with so far but using the car id instead of the previous string cars sorted cars sorted cars iteritems key itemgetter cars by common mods for in itertools groupby sorted cars key itemgetter cars by common mods append mods cars map itemgetter print cars by common mods which for the sample data gives me reformatted by hand for clarity cars mods cars mods cars mods cars mods now that you have got your lists of car ids and mod ids if you need the complete objects to work with you could do single query for each to get complete list for each model and create lookup dict for those keyed by their ids then believe bob is your proverbial father brother
QA
emulation of lex like functionality in perl or python here is the deal is there way to have strings tokenized in line based on multiple regexes one example have to get all href tags their corresponding text and some other text based on different regex so have expressions and would like to tokenize the line and extract tokens of text matching every expression have actually done this using flex not to be confused with adobe which is an implementation of the good old lex lex provides an elegant way to do this by executing actions based on expressions one can control the way lex reading file too block line based read the problem is that flex actually produces code which actually does the tokenizing job have make file which wraps all these things was wondering if perl python can in some way do the same thing its just that would like to do everything like in single programming language itself tokenizing is just one of the things that want to do as part of my application apart from perl or python can any language functional also do this did read about ply and antlr here http stackoverflow com questions parsing where can learn about it but is there way to do it naturally in python itself pardon my ignorance but are these tools used in any popular products services thank you
if you are specifically after parsing links out of web pages then perl www mechanize module will figure things out for you in very elegant fashion here is sample program that grabs the first page of stack overflow and parses out all the links printing their text and corresponding urls usr bin perl use strict use warnings use www mechanize my mech www mechanize new mech get http stackoverflow com mech success or die oh no could not fetch stackoverflow com foreach my link mech links print link text points to link url in the main loop each link is www mechanize link object so you are not just constrained to getting the text and url all the best paul
QA
django python grouping objects by common set from many to many relationships this is part algorithm logic question how to do it part implementation question how to do it best am working with django so thought would share with that in python it is worth mentioning that the problem is somewhat related to how do use pythons itertoolsgroupby suppose you are given two django model derived classes from django db import models class car models model mods models manytomanyfield representative and from django db import models class mods models model how does one get list of cars grouped by cars with common set of mods want to get class likeso cars by common mods mods cars mods cars mods cars mods cars have been thinking of something like def cars by common mods cars cars objects all mod list for car in cars mod list append car car mods list car mods all ret for key mods group in groupby list mods lambda set mods ret append mods group return ret however that does not work because perhaps among other reasons the groupby does not seem to group by the mods sets guess the mod list has to be sorted to work with groupby all to say am confident there is something simple and elegant out there that will be both enlightening and illuminating cheers thanks
you have few problems here you did not sort your list before calling groupby and this is required from itertools documentation generally the iterable needs to already be sorted on the same key function then you do not duplicate the list returned by groupby again documentation states the returned group is itself an iterator that shares the underlying iterable with groupby because the source is shared when the groupby object is advanced the previous group is no longer visible so if that data is needed later it should be stored as list groups uniquekeys for in groupby data keyfunc groups append list store group iterator as list uniquekeys append and final mistake is using sets as keys they do not work here quick fix is to cast them to sorted tuples there could be better solution but cannot think of it now so in your example the last part should look like this sortmethod lambda tuple sorted set mods sortedmods sorted list mods key sortmethod for key mods group in groupby sortedmods sortmethod ret append list mods group
QA
emulation of lex like functionality in perl or python here is the deal is there way to have strings tokenized in line based on multiple regexes one example have to get all href tags their corresponding text and some other text based on different regex so have expressions and would like to tokenize the line and extract tokens of text matching every expression have actually done this using flex not to be confused with adobe which is an implementation of the good old lex lex provides an elegant way to do this by executing actions based on expressions one can control the way lex reading file too block line based read the problem is that flex actually produces code which actually does the tokenizing job have make file which wraps all these things was wondering if perl python can in some way do the same thing its just that would like to do everything like in single programming language itself tokenizing is just one of the things that want to do as part of my application apart from perl or python can any language functional also do this did read about ply and antlr here http stackoverflow com questions parsing where can learn about it but is there way to do it naturally in python itself pardon my ignorance but are these tools used in any popular products services thank you
if your problem has anything at all to do with web scraping recommend looking at web scraper which provides easy element selection via xpath respectively css selectors have german talk on web scraper but if you run it through babelfish or just look at the code samples that can help you to get quick overview of the syntax hand parsing html is onerous and will not give you much over using one of the premade html parsers if your html is of very limited variation you can get by by using clever regular expressions but if you are already breaking out hard core parser tools it sounds as if your html is far more regular than what is sane to parse with regular expressions
QA
is there an inverse function for time gmtime that parses utc tuple to seconds since the epoch python time module seems little haphazard for example here is list of methods in there from the docstring time return current time in seconds since the epoch as float clock return cpu time since process start as float sleep delay for number of seconds given as float gmtime convert seconds since epoch to utc tuple localtime convert seconds since epoch to local time tuple asctime convert time tuple to string ctime convert time in seconds to string mktime convert local time tuple to seconds since epoch strftime convert time tuple to string according to format specification strptime parse string to time tuple according to format specification tzset change the local timezone looking at localtime and its inverse mktime why is there no inverse for gmtime bonus questions what would you name the method how would you implement it
there is actually an inverse function but for some bizarre reason it is in the calendar module calendar timegm listed the functions in this answer
QA
django admin site not displaying manytomanyfield relationship am working on what think is pretty standard django site but am having trouble getting my admin section to display the proper fields here is my models py class tech models model name models charfield max length class project models model title models charfield max length techs models manytomanyfield tech in other words project can have different tech objects and different tech objects can belong to different projects project was created with python and django project was and sql server however the admin site does not display any ui for the tech objects here is my admin py class techinline admin tabularinline model tech extra class projectadmin admin modeladmin fields title inlines list display title admin site register project projectadmin have tried adding the techinline class to the inlines list but that causes class home projects models tech has no foreignkey to class home projects models project error also tried adding techs to the fields list but that gives no such table projects project techs error verified and there is no projects project techs table but there is projects tech one did something perhaps get screwed up in my syncdb am using sqlite as my database if that helps
assuming your app is called projects the default name for your techs table will be projects tech and the projects table will be projects project the many to many table should be something like projects project techs
QA
library for converting traceback to its exception just curiosity is there an already coded way to convert printed traceback back to the exception that generated it or to sys exc info like structure
converting traceback to the exception object would not be too hard given common exception classes parse the last line for the exception class and the arguments given to it at instantiation the traceback object the third argument returned by sys exc info is an entirely different matter though the traceback object actually contains the chain of frame objects that constituted the stack at the time of the exception including local variables global variables et cetera it is impossible to recreate that just from the displayed traceback the best you could do would be to parse each file line in line and create fake frame objects that are almost entirely empty there would be very little value in it as basically the only thing you would be able to do with it would be to print it what are you trying to accomplish
QA
model limit choices to user user went to all the documentation also went to the irc channel by the way great community and they told me that is not possible to create model and limit choices in field where the current user is in foreignkey will try to explain this with an example class project models model name models charfield max length employees models manytomanyfield profile limit choices to active class timeworked models model project models foreignkey project limit choices to user user hours models positiveintegerfield of course that code does not work because there is no user object but that was my idea and was trying to send the object user to the model to just limit the choices where the current user has projects do not want to see projects where am not in thank you very much if you can help me or give me any advice do not want to you write all the app just tip how to deal with that have days with this in my head and cannot figure it out update the solution is here http collingrady wordpress com useful form tricks in django sending request user to model
use threadlocals if you want to get current user that edits this model threadlocals middleware puts current user into process wide variable take this middleware from threading import local thread locals local def get current user return getattr getattr thread locals user none id none class threadlocals object middleware that gets various objects from the request object and saves them in thread local storage def process request self request thread locals user getattr request user none check the documentation on how to use middleware classes then anywhere in code you can call user threadlocals get current user
QA
how would you implement ant style patternsets in python to select groups of files ant has nice way to select groups of files most handily using to indicate directory tree cvs all files immediately under cvs directory mydir mysubdir all files recursively under mysubdir more examples can be seen here http ant apache org manual dirtasks html how would you implement this in python so that you could do something like files get files cvs for file in files print file cvs repository mydir mysubdir cvs entries mydir mysubdir foo bar cvs entries
os walk is your friend look at the example in the python manual https docs python org library os html os walk and try to build something from that to match cvs against file name you get you can do something like this def match pattern filename if pattern startswith return fnmatch fnmatch file pattern else return fnmatch fnmatch file pattern in fnmatch fnmatch matches anything including slashes
QA
how would you implement ant style patternsets in python to select groups of files ant has nice way to select groups of files most handily using to indicate directory tree cvs all files immediately under cvs directory mydir mysubdir all files recursively under mysubdir more examples can be seen here http ant apache org manual dirtasks html how would you implement this in python so that you could do something like files get files cvs for file in files print file cvs repository mydir mysubdir cvs entries mydir mysubdir foo bar cvs entries
yup your best bet is as has already been suggested to work with os walk or write wrappers around glob and fnmatch modules perhaps
QA
emulation of lex like functionality in perl or python here is the deal is there way to have strings tokenized in line based on multiple regexes one example have to get all href tags their corresponding text and some other text based on different regex so have expressions and would like to tokenize the line and extract tokens of text matching every expression have actually done this using flex not to be confused with adobe which is an implementation of the good old lex lex provides an elegant way to do this by executing actions based on expressions one can control the way lex reading file too block line based read the problem is that flex actually produces code which actually does the tokenizing job have make file which wraps all these things was wondering if perl python can in some way do the same thing its just that would like to do everything like in single programming language itself tokenizing is just one of the things that want to do as part of my application apart from perl or python can any language functional also do this did read about ply and antlr here http stackoverflow com questions parsing where can learn about it but is there way to do it naturally in python itself pardon my ignorance but are these tools used in any popular products services thank you
also check out pquery it as really nice perlish way of doing this kind of stuff use pquery pquery http www perl com find each sub my pq pquery say pq text pq tohtml prints all html anchors on www perl com link text anchor html however if your requirement is beyond html web then here is the earlier hello world example in parse recdescent use strict use warnings use parse recdescent my grammar alpha sep end greet alpha sep alpha end shift item return item my parse parse recdescent new grammar my hello hello world print hello parse greet hello hello world hello world probably too much of large hammer to crack this nut az
QA
emulation of lex like functionality in perl or python here is the deal is there way to have strings tokenized in line based on multiple regexes one example have to get all href tags their corresponding text and some other text based on different regex so have expressions and would like to tokenize the line and extract tokens of text matching every expression have actually done this using flex not to be confused with adobe which is an implementation of the good old lex lex provides an elegant way to do this by executing actions based on expressions one can control the way lex reading file too block line based read the problem is that flex actually produces code which actually does the tokenizing job have make file which wraps all these things was wondering if perl python can in some way do the same thing its just that would like to do everything like in single programming language itself tokenizing is just one of the things that want to do as part of my application apart from perl or python can any language functional also do this did read about ply and antlr here http stackoverflow com questions parsing where can learn about it but is there way to do it naturally in python itself pardon my ignorance but are these tools used in any popular products services thank you
from perlop useful idiom for lex like scanners is gc you can combine several regexps like this to process string part by part doing different actions depending on which regexp matched each regexp tries to match where the previous one leaves off loop print digits redo loop if gc print lowercase redo loop if gc print uppercase redo loop if gc print capitalized redo loop if gc print mixed redo loop if za gc print alphanumeric redo loop if za gc print line noise redo loop if za gc print that is all
QA
interface to versioned dictionary have an versioned document store which want to access through an dict like interface common usage is to access the latest revision get set del but one should be able to access specific revisions too keys are always str unicode or int from userdict import dictmixin class vdict dictmixin def getitem self key if isinstance key tuple docid rev key else docid key rev none set to tip rev print docid rev return in vdict in none in this solution is little bit tricky and am not sure if it is clean understandable interface should provide function def getrev self docid rev instead
yes provide different api for getting different versions either single methodcall for doing retrieval of particular item of particular revision or methodcall for getting view of particular revision which you could then access like normal dict depending on whether such view would see much use or both considering the dict view solution would need some way to get particular revision item anyway class revisionview object def init self db revid self db db self revid revid def getitem self item self db getrev item self revid
QA
how would you implement ant style patternsets in python to select groups of files ant has nice way to select groups of files most handily using to indicate directory tree cvs all files immediately under cvs directory mydir mysubdir all files recursively under mysubdir more examples can be seen here http ant apache org manual dirtasks html how would you implement this in python so that you could do something like files get files cvs for file in files print file cvs repository mydir mysubdir cvs entries mydir mysubdir foo bar cvs entries
os walk is your best bet for this did the example below with svn because had that handy and it worked great import re for dirpath dirnames filenames in os walk if re search svn dirpath for file in filenames print file
QA
subclassing class with private members one of the really nice things about python is the simplicity with which you can name variables that have the same name as the accessor self value def value return self value is there simple way of providing access to the private members of class that wish to subclass often wish to simply work with the raw data objects inside of class without having to use accessors and mutators all the time know this seems to go against the general idea of private and public but usually the class am trying to subclass is one of my own which am quite happy to expose the members from to subclass but not to an instance of that class is there clean way of providing this distinction
not conveniently without further breaking encapsulation the double underscore attribute is name mangled by prepending classname for the class it is being accessed in so if you have containerthing class that has value attribute the attribute is actually being stored as containerthing value changing the class name or refactoring where the attribute is assigned to would mean breaking all subclasses that try to access that attribute this is exactly why the double underscore name mangling which is not really private just inconvenient is bad idea to use just use single leading underscore everyone will know not to touch your private attribute and you will still be able to access it in subclasses and other situations where it is darned handy the name mangling of double underscore attributes is useful only to avoid name clashes for attributes that are truly specific to particular class which is extremely rare it provides no extra security since even the name mangled attributes are trivially accessible for the record value and value and value are not the same name the underscores are part of the name
QA
django admin site not displaying manytomanyfield relationship am working on what think is pretty standard django site but am having trouble getting my admin section to display the proper fields here is my models py class tech models model name models charfield max length class project models model title models charfield max length techs models manytomanyfield tech in other words project can have different tech objects and different tech objects can belong to different projects project was created with python and django project was and sql server however the admin site does not display any ui for the tech objects here is my admin py class techinline admin tabularinline model tech extra class projectadmin admin modeladmin fields title inlines list display title admin site register project projectadmin have tried adding the techinline class to the inlines list but that causes class home projects models tech has no foreignkey to class home projects models project error also tried adding techs to the fields list but that gives no such table projects project techs error verified and there is no projects project techs table but there is projects tech one did something perhaps get screwed up in my syncdb am using sqlite as my database if that helps
john millikin thanks for the sqlreset tip that put me on the right path the sqlreset generated code that showed me that the projects project techs was never actually created ended up just deleting my deb db database and regenerating it techs then showed up as it should and just as sidenote had to do an admin site register tech to be able to create new instances of the class from the project page too will probably post another question to see if there is better way to implement model changes since am pretty sure that is what caused my problem without wiping the database
QA
urllib file name if open file using urllib like so remotefile urllib urlopen http example com somefile zip is there an easy way to get the file name other then parsing the original url edit changed openfile to urlopen not sure how that happened edit ended up using filename url split split split unless am mistaken this should strip out all potential queries as well
do you mean urllib urlopen there is no function called openfile in the urllib module anyway use the urllib urlparse functions from urllib import urlparse print urlparse urlsplit http example com somefile zip http example com somefile zip voila
QA
urllib file name if open file using urllib like so remotefile urllib urlopen http example com somefile zip is there an easy way to get the file name other then parsing the original url edit changed openfile to urlopen not sure how that happened edit ended up using filename url split split split unless am mistaken this should strip out all potential queries as well
think that the file name is not very well defined concept when it comes to http transfers the server might but is not required to provide one as content disposition header you can try to get that with remotefile headers content disposition if this fails you probably have to parse the uri yourself
QA
urllib file name if open file using urllib like so remotefile urllib urlopen http example com somefile zip is there an easy way to get the file name other then parsing the original url edit changed openfile to urlopen not sure how that happened edit ended up using filename url split split split unless am mistaken this should strip out all potential queries as well
did you mean urllib urlopen you could potentially lift the intended filename if the server was sending content disposition header by checking remotefile info content disposition but as it is think you will just have to parse the url you could use urlparse urlsplit but if you have any urls like at the second example you will end up having to pull the file name out yourself anyway urlparse urlsplit http example com somefile zip http example com somefile zip urlparse urlsplit http example com somedir somefile zip http example com somedir somefile zip might as well just do this http example com somefile zip split somefile zip http example com somedir somefile zip split somefile zip
QA
urllib file name if open file using urllib like so remotefile urllib urlopen http example com somefile zip is there an easy way to get the file name other then parsing the original url edit changed openfile to urlopen not sure how that happened edit ended up using filename url split split split unless am mistaken this should strip out all potential queries as well
guess it depends what you mean by parsing there is no way to get the filename without parsing the url the remote server does not give you filename however you do not have to do much yourself there is the urlparse module in urlparse urlparse http example com somefile zip out http example com somefile zip
QA
urllib file name if open file using urllib like so remotefile urllib urlopen http example com somefile zip is there an easy way to get the file name other then parsing the original url edit changed openfile to urlopen not sure how that happened edit ended up using filename url split split split unless am mistaken this should strip out all potential queries as well
import os urllib resp urllib urlopen http www example com index html my url resp geturl os path split my url index html this is not openfile but maybe still helps
QA
urllib file name if open file using urllib like so remotefile urllib urlopen http example com somefile zip is there an easy way to get the file name other then parsing the original url edit changed openfile to urlopen not sure how that happened edit ended up using filename url split split split unless am mistaken this should strip out all potential queries as well
not that know of but you can parse it easy enough like this url http example com somefile zip print url split
QA
django and python am just starting to get into django and of course as of last night one of the two new python versions went final obviously so am wondering if plus django is ready for actual use or do the django team need more time to finish with tweaks cleanup all the google searches did were inconclusive saw bits about some initial test runs on beta but nothing more recent seemed to show up edit http groups google com group django developers browse thread thread they have confirmed here works fine as far as they know
the impression get is that should work fine with django as found here http simonwillison net oct whatus
QA
urllib file name if open file using urllib like so remotefile urllib urlopen http example com somefile zip is there an easy way to get the file name other then parsing the original url edit changed openfile to urlopen not sure how that happened edit ended up using filename url split split split unless am mistaken this should strip out all potential queries as well
if you only want the file name itself assuming that there is no query variables at the end like http example com somedir somefile zip foo bar then you can use os path basename for this user host python python apr type help copyright credits or license for more information import os os path basename http example com somefile zip somefile zip os path basename http example com somedir somefile zip somefile zip os path basename http example com somedir somefile zip foo bar somefile zip foo bar some other posters mentioned using urlparse which will work but you would still need to strip the leading directory from the file name if you use os path basename then you do not have to worry about that since it returns only the final part of the url or file path
QA
how would you implement ant style patternsets in python to select groups of files ant has nice way to select groups of files most handily using to indicate directory tree cvs all files immediately under cvs directory mydir mysubdir all files recursively under mysubdir more examples can be seen here http ant apache org manual dirtasks html how would you implement this in python so that you could do something like files get files cvs for file in files print file cvs repository mydir mysubdir cvs entries mydir mysubdir foo bar cvs entries
as soon as you come across you are going to have to recurse through the whole directory structure so think at that point the easiest method is to iterate through the directory with os walk construct path and then check if it matches the pattern you can probably convert to regex by something like def glob to regex pat dirsep os sep dirsep re escape dirsep print re escape pat regex re escape pat replace dirsep replace replace dirsep replace dirsep return re compile regex though note that this is not that fully featured it does not support style glob patterns for instance though this could probably be added the first match is to cover cases like cvs matching cvs as well as having just to match at the tail however obviously you do not want to recurse through everything below the current dir when not processing pattern so think you will need two phase approach have not tried implementing the below and there are probably few corner cases but think it should work split the pattern on your directory seperator ie pat split cvs recurse through the directories and look at the relevant part of the pattern for this level ie levels deep look at pat if pat switch to the above strategy reconstruct the pattern with dirsep join pat convert to regex with glob to regex recursively os walk through the current directory building up the path relative to the level you started at if the path matches the regex yield it if pat does not match and it is the last element in the pattern then yield all files dirs matching glob glob os path join curpath pat if pat does not match and it is not the last element in the pattern then for each directory check if it matches with glob pat if so recurse down through it incrementing depth so it will look at pat
QA
most pythonic way of counting matching elements in something iterable have an iterable of entries on which would like to gather some simple statistics say the count of all numbers divisible by two and the count of all numbers divisible by three my first alternative while only iterating through the list once and avoiding the list expansion and keeping the split loop refactoring in mind looks rather bloated alt are xrange twos threes for in if twos if threes print twos print threes this looks rather nice but has the drawback of expanding the expression to list alt are xrange print len for in if print len for in if what would really like is something like function like this alt def count iterable for in iterable return are xrange print count for in if print count for in if but this looks lot like something that could be done without function the final variant is this alt are xrange print sum for in if print sum for in if and while the smallest and in my book probably the most elegant it does not feel like it expresses the intent very well so my question to you is which alternative do you like best to gather these types of stats feel free to supply your own alternative if you have something better to clear up some confusion below in reality my filter predicates are more complex than just this simple test the objects iterate over are larger and more complex than just numbers my filter functions are more different and hard to parameterize into one predicate
would choose small variant of your alt def count predicate list print sum for in list if predicate are xrange count lambda count lambda if you want to change what count does change its implementation in one place note since your predicates are complex you will probably want to define them in functions instead of lambdas and so you will probably want to put all this in class rather than the global namespace
QA
model limit choices to user user went to all the documentation also went to the irc channel by the way great community and they told me that is not possible to create model and limit choices in field where the current user is in foreignkey will try to explain this with an example class project models model name models charfield max length employees models manytomanyfield profile limit choices to active class timeworked models model project models foreignkey project limit choices to user user hours models positiveintegerfield of course that code does not work because there is no user object but that was my idea and was trying to send the object user to the model to just limit the choices where the current user has projects do not want to see projects where am not in thank you very much if you can help me or give me any advice do not want to you write all the app just tip how to deal with that have days with this in my head and cannot figure it out update the solution is here http collingrady wordpress com useful form tricks in django sending request user to model
here is the cookbook threadlocals and user
QA
python how do pass string into subprocess popen using the stdin argument if do the following import subprocess from cstringio import stringio subprocess popen grep stdout subprocess pipe stdin stringio one ntwo nthree nfour nfive nsix communicate get traceback most recent call last file stdin line in file build toolchain mac python lib python subprocess py line in init cread cwrite file build toolchain mac python lib python subprocess py line in get handles cread stdin fileno attributeerror cstringio stringi object has no attribute fileno apparently cstringio stringio object does not quack close enough to file duck to suit subprocess popen how do work around this
figured out this workaround subprocess popen grep stdout subprocess pipe stdin subprocess pipe stdin write one ntwo nthree nfour nfive nsix communicate four nfive stdin close is there better one
QA
subclassing class with private members one of the really nice things about python is the simplicity with which you can name variables that have the same name as the accessor self value def value return self value is there simple way of providing access to the private members of class that wish to subclass often wish to simply work with the raw data objects inside of class without having to use accessors and mutators all the time know this seems to go against the general idea of private and public but usually the class am trying to subclass is one of my own which am quite happy to expose the members from to subclass but not to an instance of that class is there clean way of providing this distinction
not sure of where to cite it from but the following statement in regard to access protection is pythonic canon we are all consenting adults here just as thomas wouters has stated single leading underscore is the idiomatic way of marking an attribute as being part of the object internal state two underscores just provides name mangling to prevent easy access to the attribute after that you should just expect that the client of your library will not go and shoot themselves in the foot by meddling with the private attributes
QA
python how do pass string into subprocess popen using the stdin argument if do the following import subprocess from cstringio import stringio subprocess popen grep stdout subprocess pipe stdin stringio one ntwo nthree nfour nfive nsix communicate get traceback most recent call last file stdin line in file build toolchain mac python lib python subprocess py line in init cread cwrite file build toolchain mac python lib python subprocess py line in get handles cread stdin fileno attributeerror cstringio stringi object has no attribute fileno apparently cstringio stringio object does not quack close enough to file duck to suit subprocess popen how do work around this
apparently cstringio stringio object does not quack close enough to file duck to suit subprocess popen am afraid not the pipe is low level os concept so it absolutely requires file object that is represented by an os level file descriptor your workaround is the right one
QA
wpf alternative for python is there any alternative for wpf windows presentation foundation in python http msdn microsoft com en us library aa aspx programming with wpf
you might want to look at pygtk and glade here is tutorial there is long list of alternatives on the python wiki
QA
wpf alternative for python is there any alternative for wpf windows presentation foundation in python http msdn microsoft com en us library aa aspx programming with wpf
here is list of python gui toolkits also you can use ironpython to work with wpf directly
QA
wpf alternative for python is there any alternative for wpf windows presentation foundation in python http msdn microsoft com en us library aa aspx programming with wpf
try pyqt which binds python to qt graphics library there are some other links at the end of that article anygui pygtk fxpy wxpython win ui
QA
wpf alternative for python is there any alternative for wpf windows presentation foundation in python http msdn microsoft com en us library aa aspx programming with wpf
if you are on windows and you want to use wpf as opposed to an alternative you can use it with ironpython net version of python here is quick example http stevegilham blogspot com hello wpf in ironpython html
QA
can list display in django modeladmin display attributes of foreignkey fields have person model that has foreign key relationship to book book has number of fields but am most concerned about author standard charfield with that being said in my personadmin model would like to display book author using list display have tried all of the obvious methods for doing so see below but nothing seems to work any suggestions class personadmin admin modeladmin list display book author
according to the documentation you can only display the unicode representation of foreignkey http docs djangoproject com en dev ref contrib admin list display seems odd that it does not support the book author style format which is used everywhere else in the db api turns out there is ticket for this feature which is marked as will not fix
QA
how do deploy python desktop application have started on personal python application that runs on the desktop am using wxpython as gui toolkit should there be demand for this type of application would possibly like to commercialize it have no knowledge of deploying real life python applications though have used py exe in the past with varied success how would obfuscate the code can somehow deploy only the bytecode an ideal solution would not jeopardize my intellectual property source code would not require direct installation of python though am sure it will need to have some embedded interpreter and would be cross platform windows mac and linux does anyone know of any tools or resources in this area thanks
wow there are lot of questions in there it is possible to run the bytecode pyc file directly from the python interpreter but have not seen any bytecode obfuscation tools available am not aware of any all in one deployment solution but for windows you could use nsis http nsis sourceforge net main page the problem here is that while osx nix comes with python windows does not if you are not willing to build binary with py exe am not sure what the licensing issues would be surrounding distribution of the python runtime environment not to mention the technical ones you could package up the os distribution using the bundle format and nix has it is own conventions for installing software typically make install script hope that was helpful
QA
how do deploy python desktop application have started on personal python application that runs on the desktop am using wxpython as gui toolkit should there be demand for this type of application would possibly like to commercialize it have no knowledge of deploying real life python applications though have used py exe in the past with varied success how would obfuscate the code can somehow deploy only the bytecode an ideal solution would not jeopardize my intellectual property source code would not require direct installation of python though am sure it will need to have some embedded interpreter and would be cross platform windows mac and linux does anyone know of any tools or resources in this area thanks
you can distribute the compiled python bytecode pyc files instead of the source you cannot prevent decompilation in python or any other language really you could use an obfuscator like pyobfuscate to make it more annoying for competitors to decipher your decompiled source as alex martelli says in this thread if you want to keep your code secret you should not run it on other people machines iirc the last time used cx freeze it created dll for windows that removed the necessity for native python installation this is at least worth checking out
QA
apache sockets not closing have web application written using cherrypy which is run locally on we use mod rewrite and mod proxy to have apache act as reverse proxy apache also handles our ssl encryption and may eventually be used to transfer all of our static content this all works just fine for small workloads however recently used urllib to write stress testing script that would simulate workload of clients after some time each client gets error from apache indicating that apache cannot connect to cherrypy is functioning properly but my apache error log reveals lines like the following thu oct error os only one usage of each socket address protocol network address port is normally permitted proxy http attempt to connect to failed googling for this error reveals that apache has probably run out of socket file descriptors since only have clients running this implies that the connections are not being closed either between my urllib connection and apache am definitely calling close on the return value of urlopen or between apache and cherrypy have confirmed that my urllib request is sending an http connection close header although apache is configured with keepalive on if that matters in case it matters am using python apache cherrypy and the server is running on windows server so what is my next step to stop this problem
you might run the netstat command and see if you have bunch of sockets in the time wait state depending on your maxuserport setting you might be severly limited in the number of ports available to use in addition the tcptimedwaitdelay is usually set to seconds so any sockets that are used cannot be reused for four minutes there is more good information here http smallvoid com article winnt tcpip max limit html
QA
change django templates based on user agent have made django site but have drank the koolaid and want to make an iphone version after putting much thought into have come up with two options make whole other site like xxxx com tie it into the same database using django sites framework find some time of middleware that reads the user agent and changes the template directories dynamically would really prefer option however have some reservations mainly because the django documentation discourages changing settings on the fly found snippet that would do the what would like my main issue is having it as seamless as possible would like it to be automagic and transparent to the user has anyone else come across the same issue would anyone care to share about how they have tackled making iphone versions of django sites update went with combination of middleware and tweaking the template call for the middleware used minidetector like it because it detects plethora of mobile user agents all have to do is check request mobile in my views for the template call tweak def check mobile request template name if request mobile return mobile template name return template name use this for any view that know have both versions todo figure out how to access request mobile in an extended version of render to response so do not have to use check mobile template name html using the previous automagically fallback to the regular template if no mobile version exists
rather than changing the template directories dynamically you could modify the request and add value that let us your view know if the user is on an iphone or not then wrap render to response or whatever you are using for creating httpresponse objects to grab the iphone version of the template instead of the standard html version if they are using an iphone