prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
how do calculate number of days betwen two dates using python if have two dates ex and what is the best way to get the difference measured in days
using the power of datetime from datetime import datetime date format datetime strptime date format datetime strptime date format delta print delta days that is it
QA
how do calculate number of days betwen two dates using python if have two dates ex and what is the best way to get the difference measured in days
days until christmas import datetime today datetime date today someday datetime date different someday today different days more arithmetic here
QA
how do calculate number of days betwen two dates using python if have two dates ex and what is the best way to get the difference measured in days
you want the datetime module from datetime import datetime datetime datetime datetime timedelta or other example python feb gcc apple computer inc build on darwin type help copyright credits or license for more information import datetime today datetime date today print today last year datetime date print today last year days as pointed out here
QA
send file using post from python script this is an almost duplicate of http stackoverflow com questions send file using post from python script but would like to add caveat need something that properly handles the encoding of fields and attached files the solutions have been able to find blow up when you throw unicode strings containing non ascii characters into the mix also most of the solutions do not base encode data to keep things bit clean
best thing can think of is to encode it yourself how about this subroutine from urllib import request urlopen from binascii import base def open url postdata req request url base postdata headers content transfer encoding base return urlopen req conn open http www whatever com script cgi you libert galit fraternit returns file like object okay so this code just sends post data but you apparently want multipart encoded data as if you clicked an upload file button right well it is pretty straightforward combination of what have here and the answers from the question you linked
QA
send file using post from python script this is an almost duplicate of http stackoverflow com questions send file using post from python script but would like to add caveat need something that properly handles the encoding of fields and attached files the solutions have been able to find blow up when you throw unicode strings containing non ascii characters into the mix also most of the solutions do not base encode data to keep things bit clean
pycurl provides an interface to curl from python http curl haxx se libcurl python curl will do all you need it can transfer binary files properly and supports many encodings however you have to make sure that the proper character encoding as custom header when posting files specifically you may need to do file upload style post http curl haxx se docs httpscripting html section with curl or any other http client you may have to set the content encoding content type text html charset utf also be aware that the request headers must be ascii and this includes the url so make sure you properly escape your possibly unicode urls there are unicode escapes for the http headers this was recently fixed in python http bugs python org issue hope this helps there is more info on the topic including setting your default character set on your server etc
QA
errors with python mechanize module am using the mechanize module to execute some web queries from python want my program to be error resilient and handle all kinds of errors wrong urls responsese gracefully however cannot find in mechanize documentation the errors exceptions it throws for various errors just call it with self browser mechanize browser self browser addheaders user agent browser header self browser open query url self result page self browser response read how can know what errors exceptions can be thrown here and handle them
found this in their docs one final thing to note is that there are some catch all bare except statements in the module which are there to handle unexpected bad input without crashing your program if this happens it is bug in mechanize so please mail me the warning text so guess they do not raise any exceptions you can also search the source code for exception subclasses and see how they are used
QA
how do configure the ip address with cherrypy am using python and cherrypy to create simple internal website that about people use use the built in webserver with cherrypy quickstart and never messed with the config files recently changed machines so installed the latest python and cherrypy and when run the site can access it from localhost but not through the ip or the windows machine name it could be machine configuration difference or newer version of cherrypy or python any ideas how can bind to the correct ip address edit to make it clear currently do not have config file at all
server socket host would also work that is ipv inaddr any which means listen on all interfaces in config file the syntax is global server socket host in code cherrypy server socket host
QA
how do manipulate bits in python in could for example zero out bit in bit unsigned value like so unsigned long value xdeadbeef value how do do that in python
you should also check out bitarray which is nice interface for dealing with sequences of bits
QA
is it ok to inspect properties beginning with underscore have been working on very simple crud generator for pylons came up with something that inspects someclass sa class manager mapper is it ok to inspect this or to call methods begining with underscore always kind of assumed this is legal though frowned upon as it relies heavily on the internal structure of class object but hey since python does not really have interfaces in the java sense maybe it is ok
if it works why not you could have problems though when sa class manager gets restructured binding yourself to this specific version of sqlalchemy or creating more work to track the changes as sqlalchemy is fast moving target you may be there in year already the preferable way would be to integrate your desired api into sqlalchemy itself
QA
is it ok to inspect properties beginning with underscore have been working on very simple crud generator for pylons came up with something that inspects someclass sa class manager mapper is it ok to inspect this or to call methods begining with underscore always kind of assumed this is legal though frowned upon as it relies heavily on the internal structure of class object but hey since python does not really have interfaces in the java sense maybe it is ok
it is intentional in python that there are no private scopes it is convention that anything that starts with an underscore should not ideally be used and hence you may not complain if its behavior or definition changes in next version
QA
get other running processes window sizes in python this is not as malicious as it sounds want to get the current size of their windows not look at what is in them the purpose is to figure out that if every other window is fullscreen then should start up like that too or if all the other processes are only despite there being huge resolution then that is probably what the user wants why make them waste time and energy resizing my window to match all the others they have am primarily windows devoloper but it would not upset me in the least if there was cross platform way to do this
check out the win gui module in the windows extensions for python it may provide some of the functionality you are looking for
QA
is it ok to inspect properties beginning with underscore have been working on very simple crud generator for pylons came up with something that inspects someclass sa class manager mapper is it ok to inspect this or to call methods begining with underscore always kind of assumed this is legal though frowned upon as it relies heavily on the internal structure of class object but hey since python does not really have interfaces in the java sense maybe it is ok
in general this usually indicates that the method is effectively internal rather than part of the documented interface and should not be relied on future versions of the library are free to rename or remove such methods so if you care about future compatability without having to rewrite avoid doing it
QA
how do upgrade python to python rc on ubuntu linux would like to how to upgrade the default python installation supplied with ubuntu to python rc would like to make the default python version on the system and migrate all the other useful installed python libraries installed on to python rc please let me know how can achieve this thanks dirk
it would not be wise to change the default version of python what you get when you type python into she will however you can have multiple versions of python installed the trick is to make sure that the program named python on the path is the system supplied version if you want to run your install of python you would then type python into she will to start it download the package and unzip it then run configure make sudo make install ls usr local bin you should see python and python file both created on the day you ran make install delete the python file then when python is launched the standard system python version from usr bin will be run and when python is run you get your shiny new python rc python displays the version when it starts an interactive interpreter
QA
svg rendering in pygame application in pygame application would like to render resolution free gui widgets described in svg what tool and or library can use to reach this goal like the ocemp gui toolkit but it seems to be bitmap dependent for its rendering
pygamesvg seems to do what you want though have not tried it
QA
looking for regular expression including aplhanumeric and here is the problem split re compile works fine when dealing with regular words but there are occasions where need the expression to include words like auml ytt auml amlauml what should add to the regex to include the and characters
you probably want to take the problem reverse finding all the character without the spaces or you want to add the extra characters za in case you want to match html entities you should try something like
QA
looking for regular expression including aplhanumeric and here is the problem split re compile works fine when dealing with regular words but there are occasions where need the expression to include words like auml ytt auml amlauml what should add to the regex to include the and characters
you should make character class that would include the extra characters for example split re compile this should do the trick for your information lower case matches word characters alphanumeric capital is negated character class meaning it matches any non alphanumeric character matches or more times and matches one or more times so will match anything even if there are no characters there
QA
looking for regular expression including aplhanumeric and here is the problem split re compile works fine when dealing with regular words but there are occasions where need the expression to include words like auml ytt auml amlauml what should add to the regex to include the and characters
would treat the entities as unit since they also can contain numerical character codes resulting in the following regular expression fa this matches either word character including or an html entity consisting of the character the character the character followed by at least one hexadecimal digit or at least one decimal digit or at least one letter named entity semicolon at least once edit thanks to for pointing out an error
QA
nswindow launched from statusitem menuitem does not appear as active window have statusitem application written in pyobjc the statusitem has menuitem which is supposed to launch new window when it is clicked create statusitem statusitem nsstatusbar systemstatusbar statusitemwithlength nsvariablestatusitemlength statusitem sethighlightmode true statusitem setenabled true statusitem retain create menuitem menu nsmenu alloc init menuitem nsmenuitem alloc initwithtitle action keyequivalent preferences launchpreferences menu additem menuitem statusitem setmenu menu the launchpreferences method is def launchpreferences self notification preferences preferences alloc initwithwindownibname preferences preferences showwindow self preferences is an nswindowcontroller class class preferences nswindowcontroller when run the application in xcode build go this works fine however when run the built app file externally from xcode the statusitem and menuitem appear as expected but when click on the preferences menuitem the window does not appear have verified that the launchpreferences code is running by checking console output further if then double click the app file again the window appears but if change the active window away by clicking for example on finder window the preferences window disappears this seems to me to be something to do with the active window update have tried these two answers but neither work if add in to the launchpreferences method preferences makekeyandorderfront or preferences setlevel nsnormalwindowlevel then just get an error preferences object has no attribute
you need to send the application an activateignoringotherapps message and then send the window makekeyandorderfront in objective this would be nsapp activateignoringotherapps yes self window makekeyandorderfront self
QA
nswindow launched from statusitem menuitem does not appear as active window have statusitem application written in pyobjc the statusitem has menuitem which is supposed to launch new window when it is clicked create statusitem statusitem nsstatusbar systemstatusbar statusitemwithlength nsvariablestatusitemlength statusitem sethighlightmode true statusitem setenabled true statusitem retain create menuitem menu nsmenu alloc init menuitem nsmenuitem alloc initwithtitle action keyequivalent preferences launchpreferences menu additem menuitem statusitem setmenu menu the launchpreferences method is def launchpreferences self notification preferences preferences alloc initwithwindownibname preferences preferences showwindow self preferences is an nswindowcontroller class class preferences nswindowcontroller when run the application in xcode build go this works fine however when run the built app file externally from xcode the statusitem and menuitem appear as expected but when click on the preferences menuitem the window does not appear have verified that the launchpreferences code is running by checking console output further if then double click the app file again the window appears but if change the active window away by clicking for example on finder window the preferences window disappears this seems to me to be something to do with the active window update have tried these two answers but neither work if add in to the launchpreferences method preferences makekeyandorderfront or preferences setlevel nsnormalwindowlevel then just get an error preferences object has no attribute
have no idea of pyobjc never used that but if this was objective code would say you should call makekeyandorderfront on the window object if you want it to become the very first front window newly created window needs to be neither key nor front unless you make it either or like in this case both the other issue that worries me is that you say the window goes away gets invisible when it is not active anymore this sounds like your window is no real window have you accidentally set it to be utility window in interface builder could you try to manually set the window level using setlevel to nsnormalwindowlevel before the window is displayed on screen for the first time whether it still goes away when becoming inactive
QA
get other running processes window sizes in python this is not as malicious as it sounds want to get the current size of their windows not look at what is in them the purpose is to figure out that if every other window is fullscreen then should start up like that too or if all the other processes are only despite there being huge resolution then that is probably what the user wants why make them waste time and energy resizing my window to match all the others they have am primarily windows devoloper but it would not upset me in the least if there was cross platform way to do this
using hints from windowmover article and nattee niparnan blog post managed to create this import win con import win gui def isrealwindow hwnd return true iff given window is real windows application window if not win gui iswindowvisible hwnd return false if win gui getparent hwnd return false hasnoowner win gui getwindow hwnd win con gw owner lexstyle win gui getwindowlong hwnd win con gwl exstyle if lexstyle win con ws ex toolwindow and hasnoowner or lexstyle win con ws ex appwindow and not hasnoowner if win gui getwindowtext hwnd return true return false def getwindowsizes return list of tuples handler width height for each real window def callback hwnd windows if not isrealwindow hwnd return rect win gui getwindowrect hwnd windows append hwnd rect rect rect rect windows win gui enumwindows callback windows return windows for win in getwindowsizes print win you need the win extensions for python module for this to work edit discovered that getwindowrect gives more correct results than getclientrect source has been updated
QA
what is the canonical way to check for type in python what is the best way to check whether given object is of given type how about checking whether the object inherits from given type let us say have an object how do check whether it is str
isinstance str link
QA
what is the canonical way to check for type in python what is the best way to check whether given object is of given type how about checking whether the object inherits from given type let us say have an object how do check whether it is str
isinstance str will return true if is an str or is of type that inherits from str type str will return true if and only if is str it will return false if is of type that inherits from str
QA
what is the canonical way to check for type in python what is the best way to check whether given object is of given type how about checking whether the object inherits from given type let us say have an object how do check whether it is str
to check if the type of is exactly str type is str to check if is an instance of str or any subclass of str this would be the canonical way isinstance str the following also works and can be useful in some cases issubclass type str type in str str subclasses see built in functions in the python library reference for relevant information one more note in this case you may actually want to use isinstance basestring because this will also catch unicode strings unicode is not subclass of str both str and unicode are subclasses of basestring alternatively isinstance accepts tuple of classes this will return true if is an instance of any subclass of any of str unicode isinstance str unicode
QA
is it ok to inspect properties beginning with underscore have been working on very simple crud generator for pylons came up with something that inspects someclass sa class manager mapper is it ok to inspect this or to call methods begining with underscore always kind of assumed this is legal though frowned upon as it relies heavily on the internal structure of class object but hey since python does not really have interfaces in the java sense maybe it is ok
it is generally not good idea for reasons already mentioned however python deliberately allows this behaviour in case there is no other way of doing something for example if you have closed source compiled python library where the author did not think you would need direct access to certain object internal state but you really do you can still get at the information you need you have the same problems mentioned before of keeping up with different versions if you are lucky enough that it is still maintained but at least you can actually do what you wanted to do
QA
in django where is the best place to put short snippets of html formatted data this question is related to but perhaps not quite the same as http stackoverflow com questions does django have html helpers my problem is this in django am constantly reproducing the basic formatting for low level database objects here is an example have two classes person and address there are multiple addresses for each person setup likeso in their respective models py class person models model class address models model contact models foreignkey person now whenever look at person want to see all their addresses so suppose persons views py has something likeso def detail request person id person get object or person pk person id return render to response persons details html title unicode person addresses person address set all and have template persons details html with code for example like so extends base html for address in addresses address name address type br address street br address street br address city address stateprov address postalcode br address country hr endfor am repeating this code quite bit often with minor variations such when it is in table and then br must be substituted by td td other times do not want street to display or the br after it all to say there is fundamental logic that want to express that am even more loath to tote around with block and copy what want is persons details html with for example the following extends base html for address in addresses address as html endfor and if want inline table something likeso guess extends base html table tr for address in addresses tr td address as html td td td tr endfor table the question is then where is the best place to put the formatting the logic django seem to have the following plausible options put the formatting in models py put the logic formatting in views py put the logic formatting in some other sub class of person or address addresses html py create custom tags help insight much appreciated
think template filter will be useful too you can pass filter on each object for example value linebreaks standard django filter will produce if value is joel nis slug the output will be joel br is slug see django built in template tags and filters complete reference
QA
is there an easy way to populate slugfield from charfield class foo models model title models charfield max length slug models slugfield is there built in way to get the slug field to autopopulate based on the title perhaps in the admin and outside of the admin
you can also use pre save django signal to populate slug outside of django admin code see django signals documentation ajax slug uniqueness validation will be useful too see as you type slug uniqueness validation irrational exuberance
QA
what is the canonical way to check for type in python what is the best way to check whether given object is of given type how about checking whether the object inherits from given type let us say have an object how do check whether it is str
think the cool thing about using dynamic language like python is you really should not have to check something like that would just call the required methods on your object and catch an attributeerror later on this will allow you to call your methods with other seemingly unrelated objects to accomplish different tasks such as mocking an object for testing have used this alot when getting data off the web with urllib urlopen which returns file like object this can in turn can be passed to almost any method that reads from file because is implements the same read method as real file but am sure there is time and place for using isinstance otherwise it probably would not be there
QA
extension functions and help when call help mod cls mod is extension module get the output help on method descriptor doc string what do need to do so that the help output is of the form help on method in module mod doc string like it is for random random shuffle for example my pymethoddef entry is currently meth varargs doc string
you cannot the inspect module which is what pydoc and help use has no way of figuring out what the exact signature of function is the best you can do is what the builtin functions do include the signature in the first line of the docstring help range help on built in function range in module builtin range range start stop step list of integers the reason random shuffle docstring looks correct is that it is not function it is function written in python
QA
authenticating against active directory using python ldap how do authenticate against ad using python ldap am currently using the python ldap library and all it is producing is tears cannot even bind to perform simple query import sys import ldap server ldap my ldap server dn secret un sys argv base dc mydomain dc co dc uk scope ldap scope subtree filter objectclass user samaccountname un attrs displayname ldap initialize server protocol version print simple bind dn secret are search base scope filter attrs type user result name attrs user if hasattr attrs has key and attrs has key displayname displayname attrs displayname print displayname sys exit running this with myusername mydomain co uk password username gives me one of two errors invalid credentials when mistype or intentionally use wrong credentials it fails to authenticate ldap invalid credentials info ldaperr dsid comment acceptsecuritycontext error data vece desc invalid credentials or ldap operations error info ldaperr dsid comment in order to perform this operation successful bind must be completed on the connection data vece desc operations error what am missing out to bind properly am getting the same errors on fedora and windows
see your comment to johan buret about the dn not fixing your problem but also believe that is what you should look into given your example the dn for the default administrator account in ad will be cn administrator cn users dc mydomain dc co dc uk please try that
QA
how to iterate over timespan after days hours weeks and months in python how do iterate over timespan after days hours weeks or months something like for date in foo from date to date delta hours print date where foo is function returning an iterator have been looking at the calendar module but that only works for one specific year or month not between dates
do not think there is method in python library but you can easily create one yourself using datetime module from datetime import date datetime timedelta def datespan startdate enddate delta timedelta days currentdate startdate while currentdate enddate yield currentdate currentdate delta then you could use it like this for day in datespan date date delta timedelta days print day or if you wish to make your delta smaller for timestamp in datespan datetime datetime delta timedelta hours print timestamp
QA
what is the preferred way to redirect request in pylons without losing form data am trying to redirect forward pylons request the problem with using redirect to is that form data gets dropped need to keep the post form data intact as well as all request headers is there simple way to do this
receiving data from post depends on the web browser sending data along when the web browser receives redirect it does not resend that data along one solution would be to url encode the data you want to keep and use that with get in the worst case you could always add the data you want to keep to the session and pass it that way
QA
project structure for google app engine started an application in google app engine right when it came out to play with the technology and work on pet project that had been thinking about for long time but never gotten around to starting the result is bowlsk however as it has grown and features have been added it has gotten really difficult to keep things organized mainly due to the fact that this is my first python project and did not know anything about it until started working what have main level contains all py files did not know how to make packages work all html templates for main level pages subdirectories separate folders for css images js etc folders that hold html templates for subdirecty type urls example http www bowlsk com maps to homepage default package template at index html http www bowlsk com games view series html series maps to viewseriespage again default package template at games view series html it is nasty how do restructure had ideas main folder containing appdef indexes main py subfolder for code does this have to be my first package subfolder for templates folder heirarchy would match package heirarchy individual subfolders for css images js etc main folder containing appdef indexes main py subfolder for code templates this way have the handler class right next to the template because in this stage am adding lots of features so modifications to one mean modifications to the other again do have to have this folder name be the first package name for my classes would like the folder to be src but do not want my classes to be src whateverpage is there best practice with django on the horizon is there something can do now to improve my ability to integrate with it when it becomes the official gae templating engine would simply start trying these things and seeing which seems better but pydev refactoring support does not seem to handle package moves very well so it will likely be non trivial task to get all of this working again
my usual layout looks something like this app yaml index yaml request py contains the basic wsgi app lib init py common functionality including request handler base class controllers contains all the handlers request yaml imports these templates all the django templates used by the controllers model all the datastore model classes static static files css images etc mapped to static by app yaml can provide examples of what my app yaml request py lib init py and sample controllers look like if this is not clear
QA
python gui application redistribution need to develop small medium sized desktop gui application preferably with python as language of choice because of time constraints what gui library choices do have which allow me to redistribute my application standalone assuming that the users do not have working python installation and obviously do not have the gui libraries am using either also how would go about packaging everything up in binaries of reasonable size for each target os my main targets are windows and mac os addition have been looking at wxpython but have found plenty of horror stories of packaging it with cx freeze and getting mb binaries and no real advice on how to actually do the packaging and how trust worthy it is
this may help http stackoverflow com questions what is the best way to make an exe file from python program
QA
python gui application redistribution need to develop small medium sized desktop gui application preferably with python as language of choice because of time constraints what gui library choices do have which allow me to redistribute my application standalone assuming that the users do not have working python installation and obviously do not have the gui libraries am using either also how would go about packaging everything up in binaries of reasonable size for each target os my main targets are windows and mac os addition have been looking at wxpython but have found plenty of horror stories of packaging it with cx freeze and getting mb binaries and no real advice on how to actually do the packaging and how trust worthy it is
have used py exe myself it is really easy at least for small apps
QA
python gui application redistribution need to develop small medium sized desktop gui application preferably with python as language of choice because of time constraints what gui library choices do have which allow me to redistribute my application standalone assuming that the users do not have working python installation and obviously do not have the gui libraries am using either also how would go about packaging everything up in binaries of reasonable size for each target os my main targets are windows and mac os addition have been looking at wxpython but have found plenty of horror stories of packaging it with cx freeze and getting mb binaries and no real advice on how to actually do the packaging and how trust worthy it is
http wiki wxpython org creatingstandaloneexecutables it should not be that large unless you have managed to include the debug build of wx seem to rememebr about mb for the python dll and similair for wx
QA
python gui application redistribution need to develop small medium sized desktop gui application preferably with python as language of choice because of time constraints what gui library choices do have which allow me to redistribute my application standalone assuming that the users do not have working python installation and obviously do not have the gui libraries am using either also how would go about packaging everything up in binaries of reasonable size for each target os my main targets are windows and mac os addition have been looking at wxpython but have found plenty of horror stories of packaging it with cx freeze and getting mb binaries and no real advice on how to actually do the packaging and how trust worthy it is
http gajim org for windows uses python and pygtk you can check how they did it also there is pyqt for gui and wxpython mentioned earlier
QA
how to iterate over timespan after days hours weeks and months in python how do iterate over timespan after days hours weeks or months something like for date in foo from date to date delta hours print date where foo is function returning an iterator have been looking at the calendar module but that only works for one specific year or month not between dates
for iterating over months you need different recipe since timedeltas cannot express one month from datetime import date def jump by month start date end date month step current date start date while current date end date yield current date carry new month divmod current date month month step new month current date current date replace year current date year carry month new month nb you have to subtract from the month for the modulus operation then add it back to new month since months in datetime dates start at
QA
extension functions and help when call help mod cls mod is extension module get the output help on method descriptor doc string what do need to do so that the help output is of the form help on method in module mod doc string like it is for random random shuffle for example my pymethoddef entry is currently meth varargs doc string
thomas answer is right on of course would simply add that many extension modules have python wrapper around them so that they can support standard function signatures and other dynamic language features such as the descriptor protocol
QA
what is the canonical way to check for type in python what is the best way to check whether given object is of given type how about checking whether the object inherits from given type let us say have an object how do check whether it is str
the most pythonic way to check the type of an object is not to check it since python encourages duck typing you should just try to use the object methods the way you want to use them so if your function is looking for writable file object do not check that it is subclass of file just try to use its write method of course sometimes these nice abstractions break down and isinstance obj cls is what you need but use sparingly
QA
python gui application redistribution need to develop small medium sized desktop gui application preferably with python as language of choice because of time constraints what gui library choices do have which allow me to redistribute my application standalone assuming that the users do not have working python installation and obviously do not have the gui libraries am using either also how would go about packaging everything up in binaries of reasonable size for each target os my main targets are windows and mac os addition have been looking at wxpython but have found plenty of horror stories of packaging it with cx freeze and getting mb binaries and no real advice on how to actually do the packaging and how trust worthy it is
python has an embedded gui toolkit named tkinter which is based on tk library from tcl programming language it is very basic and does not have all the functionality you expect in windows forms or gtk for example but if you must have platform independent toolkit see no other choice taking in mind that you also do not want to grow that much the binary tkinter is not hard at all to use since it does not have millions of widgets controls and options and is the default toolkit included in most python distributions at least on windows osx and linux gtk and qt are prettier and more powerful but they have one big disadvantage for you they are heavy and deppend upon third libraries especially gtk which has lot of dependencies that makes it little hard to distribute it embeded in your software as for the binary creation know there is py exe which converts python code to win executable code exe but am not sure if there is something similar for osx are you worried because people could see the source code or just so you can bundle all in single package if you just want to bundle everything you do not need to create standalone executable you could easily create an installer creating distributable in python that is guide on how to distribute your software when it is done
QA
how to avoid pyc files can run the python interpreter without generating the compiled pyc files
as far as know python will compile all modules you import however python will not compile python script run using python script py it will however compile any modules that the script imports the real questions is why you do not want python to compile the modules you could probably automate way of cleaning these up if they are getting in the way
QA
how to avoid pyc files can run the python interpreter without generating the compiled pyc files
you could make the directories that your modules exist in read only for the user that the python interpreter is running as do not think there is more elegant option pep appears to have been an attempt to introduce simple option for this but it appears to have been abandoned imagine there is probably some other problem you are trying to solve for which disabling py co would appear to be workaround but it will probably be better to attack whatever this original problem is instead
QA
is timsort general purpose or python specific timsort is an adaptive stable natural mergesort it has supernatural performance on many kinds of partially ordered arrays less than lg comparisons needed and as few as yet as fast as python previous highly tuned samplesort hybrid on random arrays have you seen timsort used outside of cpython does it make sense
the description you linked looks completely general
QA
how to avoid pyc files can run the python interpreter without generating the compiled pyc files
in there is no way to suppress it other than measures like not giving users write access to the directory in python and however there may be setting in the sys module called dont write bytecode that can be set to suppress this this can also be set by passing the option or setting the environment variable pythondontwritebytecode
QA
how to avoid pyc files can run the python interpreter without generating the compiled pyc files
from what new in python interpreter changes python can now be prevented from writing pyc or pyo files by supplying the switch to the python interpreter or by setting the pythondontwritebytecode environment variable before running the interpreter this setting is available to python programs as the sys dont write bytecode variable and python code can change the value to modify the interpreter behaviour update python addresses the issue of cluttering source folders with pyc files by introducing special pycache subfolder see what is new in python pyc repository directories
QA
how to avoid pyc files can run the python interpreter without generating the compiled pyc files
there actually is way to do it in python but it is bit esoteric do not know if you realize this but you can do the following unzip tmp example zip archive tmp example zip length date time name jwzthreading py file python python aug import sys sys path insert tmp example zip add zip file to front of path import jwzthreading jwzthreading file tmp example zip jwzthreading py according to the zipimport library any files may be present in the zip archive but only files py and py co are available for import zip import of dynamic modules pyd so is disallowed note that if an archive only contains py files python will not attempt to modify the archive by adding the corresponding pyc or pyo file meaning that if zip archive does not contain pyc files importing may be rather slow thus all you have to do is zip the files up add the zipfile to your sys path and then import them if you are building this for unix you might also consider packaging your script using this recipe unix zip executable but note that you might have to tweak this if you plan on using stdin or reading anything from sys args it can be done without too much trouble in my experience performance does not suffer too much because of this but you should think twice before importing any very large modules this way
QA
runnning python web server as service in windows have small web server application have written in python that goes and gets some data from database system and returns it to the user as xml that part works fine can run the python web server application from the command line and can have clients connect to it and get data back at the moment to run the web server have to be logged in to our server as the administrator user and have to manually start the web server want to have the web server automatically start on system start as service and run in the background using code from activestate site and stackoverflow have pretty good idea of how to go about creating service and think have got that bit sorted can install and start my web server as windows service cannot however figure out how to stop the service again my web server is created from basehttpserver server basehttpserver httpserver simsapiserverhandler server serve forever the serve forever call naturally enough makes the web server sit in an infinite loop and wait for http connections or ctrl break keypress not useful for service get the idea from the example code above that your main function is supposed to sit in an infinite loop and only break out of it when it comes accross stop condition my main calls serve forever have svcstop function def svcstop self self reportservicestatus win service service stop pending exit which seems to get called when do python myservice stop from the command line can put debug line in there that produces output to file but does not actually exit the whole service subsequent calls to python myservice start gives me an error error starting service an instance of the service is already running and subsequent calls to stop gives me error stopping service the service cannot accept control messages at this time think need either some replacement for serve forever serve until stop received or whatever or need some way of modifying svcstop so it stops the whole service here is full listing have trimmed includes comments to save space class simsapiserverhandler basehttpserver basehttprequesthandler def do get self try reporttuple self path partition if len reporttuple return if reporttuple return os system programs simsapi runcommandreporter bat reporttuple open programs simsapi out xml rb self send response self send header content type application xml self end headers self wfile write read close the output from commandreporter is simply dumped to out xml which we read write to the user then remove os unlink programs simsapi out xml return except ioerror self send error file not found self path class simsapi win serviceutil serviceframework svc name simsapi svc display name simple web server svc description serves xml data produced by sims commandreporter def init self args win serviceutil serviceframework init self args self hwaitstop win event createevent none none def svcstop self self reportservicestatus win service service stop pending exit def svcdorun self import servicemanager servicemanager logmsg servicemanager eventlog information type servicemanager pys service started self svc name self timeout while server basehttpserver httpserver simsapiserverhandler server serve forever def ctrlhandler ctrltype return true if name main win api setconsolectrlhandler ctrlhandler true win serviceutil handlecommandline simsapi
this is what do instead of instancing directly the class basehttpserver httpserver write new descendant from it that publishes an stop method class apphttpserver socketserver threadingmixin basehttpserver httpserver def serve forever self self stop serving false while not self stop serving self handle request def stop self self stop serving true and then in the method svcstop that you already have call that method to break the serve forever loop def svcstop self self reportservicestatus win service service stop pending self httpd stop self httpd is the instance of apphttpserver that implements the webserver if you use setdaemon correctly on the background threads and interrupt correctly all the loops in the service then the instruction exit in svcstop should not be necessary
QA
is timsort general purpose or python specific timsort is an adaptive stable natural mergesort it has supernatural performance on many kinds of partially ordered arrays less than lg comparisons needed and as few as yet as fast as python previous highly tuned samplesort hybrid on random arrays have you seen timsort used outside of cpython does it make sense
it does not look particularly familiar but smart mergesorts are pretty common out in the wide world of software as for whether it makes sense that depends on what you are sorting and the relative cost of comparisons vs memory allocation sort that requires up to bytes of extra memory is not going to be good choice in memory constrained environment
QA
character reading from file in python in text file there is string do not like this however when read it into string it becomes don xe like this understand that is the unicode representation of use open file text read command to do the reading now is it possible to read the string in such way that when it is read into the string it is do not like this instead of don xe like this like this second edit have seen some people use mapping to solve this problem but really is there no built in conversion that does this kind of ansi to unicode and vice versa conversion
leaving aside the fact that your text file is broken you is left quotation mark not an apostrophe iconv can be used to transliterate unicode characters to ascii you will have to google for iconvcodec since the module seems not to be supported anymore and cannot find canonical home page for it import iconvcodec from locale import setlocale lc all setlocale lc all you encode ascii translit alternatively you can use the iconv command line utility to clean up your file xxd foo iconv ascii translit foo xxd
QA
python module for wiki markup is there python module for converting wiki markup to other languages html similar question was asked here what is the easiest way to convert wiki markup to html but no python modules are mentioned just curious cheers
mwlib provides ways of converting mediawiki formatted text into html pdf docbook and openoffice formats
QA
is timsort general purpose or python specific timsort is an adaptive stable natural mergesort it has supernatural performance on many kinds of partially ordered arrays less than lg comparisons needed and as few as yet as fast as python previous highly tuned samplesort hybrid on random arrays have you seen timsort used outside of cpython does it make sense
the algorithm is pretty generic but the benefits are rather python specific unlike most sorting routines what python list sort which is what uses timsort cares about is avoiding unnecessary comparisons because generally comparisons are lot more expensive than swapping items which is always just set of pointer copies or even allocating some extra memory because it is always just an array of pointers and the overhead is small compared to the average overhead in any python operation if you are under similar constraints then it may be suitable have yet to see any other case where comparisons are really that expensive though
QA
python gui application redistribution need to develop small medium sized desktop gui application preferably with python as language of choice because of time constraints what gui library choices do have which allow me to redistribute my application standalone assuming that the users do not have working python installation and obviously do not have the gui libraries am using either also how would go about packaging everything up in binaries of reasonable size for each target os my main targets are windows and mac os addition have been looking at wxpython but have found plenty of horror stories of packaging it with cx freeze and getting mb binaries and no real advice on how to actually do the packaging and how trust worthy it is
combination that am familiar with wxpython py exe upx the key to resolving your last concern about the size of the distribution is using upx to compress the dlls it looks like they support macos executables you will pay an initial decompression penalty when the dlls are first loaded
QA
python module for wiki markup is there python module for converting wiki markup to other languages html similar question was asked here what is the easiest way to convert wiki markup to html but no python modules are mentioned just curious cheers
you should look at good parser for creole syntax creole py it can convert creole which is common wiki markup language to be used across different wikis to html
QA
errors with python mechanize module am using the mechanize module to execute some web queries from python want my program to be error resilient and handle all kinds of errors wrong urls responsese gracefully however cannot find in mechanize documentation the errors exceptions it throws for various errors just call it with self browser mechanize browser self browser addheaders user agent browser header self browser open query url self result page self browser response read how can know what errors exceptions can be thrown here and handle them
perl ne print qq if all init py grep error browserstateerror contenttooshorterror formnotfounderror gophererror httpdefaulterrorhandler httperror httperrorprocessor linknotfounderror loaderror parseerror robotexclusionerror urlerror or import mechanize filter lambda error in dir mechanize browserstateerror contenttooshorterror formnotfounderror gophererror httpdefaulterrorhandler httperror httperrorprocessor linknotfounderr or loaderror parseerror robotexclusionerror urlerror
QA
python gui application redistribution need to develop small medium sized desktop gui application preferably with python as language of choice because of time constraints what gui library choices do have which allow me to redistribute my application standalone assuming that the users do not have working python installation and obviously do not have the gui libraries am using either also how would go about packaging everything up in binaries of reasonable size for each target os my main targets are windows and mac os addition have been looking at wxpython but have found plenty of horror stories of packaging it with cx freeze and getting mb binaries and no real advice on how to actually do the packaging and how trust worthy it is
do not have any experience building stand alone apps for any platform other than windows that said tkinter works fine with py exe python megawidgets an expansion library for tkinter works fine also but it does funky things with dynamic imports so you need to combine all the components into big file pmw py and add it to your project well you will also have pmwblt py and pmwcolor py there are instructions for how to do this somewhere either on py exe wiki or in the pmw docs tix an extension to tk that you can use with tkinter does not work with py exe or at least that was my experience about four years ago wxpython also works fine with py exe just checked an app have the whole distribution came to around mb most of that was the wx dlls and pyd files but cannot see how you would avoid that if you are targetting windows xp you need to include manifest in your setup py or else it will look ugly see this email for details
QA
how to iterate over timespan after days hours weeks and months in python how do iterate over timespan after days hours weeks or months something like for date in foo from date to date delta hours print date where foo is function returning an iterator have been looking at the calendar module but that only works for one specific year or month not between dates
use dateutil and its rrule implementation like so from dateutil import rrule from datetime import datetime timedelta now datetime now hundreddayslater now timedelta days for dt in rrule rrule rrule monthly dtstart now until hundreddayslater print dt output is replace monthly with any of yearly monthly weekly daily hourly minutely or secondly replace dtstart and until with whatever datetime object you want this recipe has the advantage for working in all cases including monthly only caveat could find is that if you pass day number that does not exist for all months it skips those months
QA
python module for wiki markup is there python module for converting wiki markup to other languages html similar question was asked here what is the easiest way to convert wiki markup to html but no python modules are mentioned just curious cheers
django uses the following libraries for markup markdown textile restructuredtext you can see how they are used in django
QA
get other running processes window sizes in python this is not as malicious as it sounds want to get the current size of their windows not look at what is in them the purpose is to figure out that if every other window is fullscreen then should start up like that too or if all the other processes are only despite there being huge resolution then that is probably what the user wants why make them waste time and energy resizing my window to match all the others they have am primarily windows devoloper but it would not upset me in the least if there was cross platform way to do this
am big fan of autoit they have com version which allows you to use most of their functions from python import win com client oautoitx win com client dispatch autoitx control oautoitx opt wintitlematchmode match text anywhere in window title width oautoitx wingetclientsizewidth firefox height oautoitx wingetclientsizeheight firefox print width height
QA
programmatically focusing hippo canvasentry consider this python program which uses pygtk and hippo canvas to display clickable text label clicking the text label replaces it with hippo canvasentry widget which contains the text of the label import pygtk pygtk require import gtk hippo def textclicked text event row input hippo canvasentry input set property text text get property text parent text get parent parent insert after input text parent remove text def main canvas hippo canvas root hippo canvasbox canvas set root root text hippo canvastext text you some text text connect button press event textclicked text root append text window gtk window window connect destroy lambda ignored gtk main quit window add canvas canvas show window show gtk main if name main main how can the canvasentry created when the text label is clicked be automatically focused at creation time
underneath the canvasentry there is regular old gtk entry which you need to request the focus as soon as it is made visible here is modified version of your textclicked function which does just that def textclicked text event row input hippo canvasentry input set property text text get property text entry input get property widget def grabit widget entry grab focus entry connect realize grabit parent text get parent parent insert after input text parent remove text
QA
get timer ticks in python am just trying to time piece of code the pseudocode looks like start get ticks do long code print it took get ticks start seconds how does this look in python more specifically how do get the number of ticks since midnight or however python organizes that timing
what you need is time function from time module import time start time time do long code print it took time time start seconds you can use timeit module for more options though
QA
get timer ticks in python am just trying to time piece of code the pseudocode looks like start get ticks do long code print it took get ticks start seconds how does this look in python more specifically how do get the number of ticks since midnight or however python organizes that timing
import datetime start datetime datetime now do long code finish datetime datetime now delta finish start print delta seconds from midnight import datetime midnight datetime datetime now replace hour minute second microsecond now datetime datetime now delta now midnight print delta seconds
QA
get timer ticks in python am just trying to time piece of code the pseudocode looks like start get ticks do long code print it took get ticks start seconds how does this look in python more specifically how do get the number of ticks since midnight or however python organizes that timing
the time module in python gives you access to the clock function which returns time in seconds as floating point different systems will have different accuracy based on their internal clock setup ticks per second but it is generally at least under milliseconds and in some cases better than few microseconds
QA
get all items from thread queue have one thread that writes results into queue in another thread gui periodically in the idle event check if there are results in the queue like this def queue get all items while try items append get nowait except empty break return items is this good way to do it edit am asking because sometimes the waiting thread gets stuck for few seconds without taking out new results the stuck problem turned out to be because was doing the processing in the idle event handler without making sure that such events are actually generated by calling wx wakeupidle as is recommended
see you are using get nowait which according to the documentation return an item if one is immediately available else raise the empty exception now you happen to break out of the loop when an empty exception is thrown thus if there is no result immediately available in the queue your function returns an empty items list is there reason why you are not using the get method instead it may be the case that the get nowait fails because the queue is servicing put request at that same moment
QA
how to skip the docstring using regex am trying to insert some import lines into python source file but would ideally like to place them right after the initial docstring let us say load the file into the lines variable like this lines open filename py readlines how to find the line number where the docstring ends
if you are using the standard docstring format you can do something like this count for line in lines if line startswith count if count before or during end of the docstring continue line is after docstring might need some adaptation for files with no docstrings but if your files are formatted consistently it should be easy enough
QA
python dependency injection framework is there framework equivalent to guice http code google com google guice for python
have not used it but the spring python framework is based on spring and implements inversion of control there also appears to be guice in python project snake guice
QA
get all items from thread queue have one thread that writes results into queue in another thread gui periodically in the idle event check if there are results in the queue like this def queue get all items while try items append get nowait except empty break return items is this good way to do it edit am asking because sometimes the waiting thread gets stuck for few seconds without taking out new results the stuck problem turned out to be because was doing the processing in the idle event handler without making sure that such events are actually generated by calling wx wakeupidle as is recommended
if you are always pulling all available items off the queue is there any real point in using queue rather than just list with lock ie from future import with statement import threading class itemstore object def init self self lock threading lock self items def add self item with self lock self items append item def getall self with self lock items self items self items return items if you are also pulling them individually and making use of the blocking behaviour for empty queues then you should use queue but your use case looks much simpler and might be better served by the above approach edit would missed the fact that you are polling the queue from an idle loop and from your update see that the problem is not related to contention so the below approach is not really relevant to your problem have left it in in case anyone finds blocking variant of this useful for cases where you do want to block until you get at least one result you can modify the above code to wait for data to become available through being signalled by the producer thread eg class itemstore object def init self self cond threading condition self items def add self item with self cond self items append item self cond notify wake thread waiting on cond if any def getall self blocking false with self cond if blocking is true always return at least item while blocking and len self items self cond wait items self items self items return items
QA
beautifulsoup python compatibility does beautifulsoup work with python if not how soon will there be port will there be port at all google does not turn up anything to me maybe it is because am looking for the wrong thing
there is release candidate for python available so you can always test beautifulsoup compatibility yourself
QA
python dependency injection framework is there framework equivalent to guice http code google com google guice for python
besides that zope component architekture pycontainer
QA
get all items from thread queue have one thread that writes results into queue in another thread gui periodically in the idle event check if there are results in the queue like this def queue get all items while try items append get nowait except empty break return items is this good way to do it edit am asking because sometimes the waiting thread gets stuck for few seconds without taking out new results the stuck problem turned out to be because was doing the processing in the idle event handler without making sure that such events are actually generated by calling wx wakeupidle as is recommended
would be very surprised if the get nowait call caused the pause by not returning if the list was empty could it be that you are posting large number of maybe big items between checks which means the receiving thread has large amount of data to pull out of the queue you could try limiting the number you retrieve in one batch def queue get all items maxitemstoretreive for numofitemsretrieved in range maxitemstoretreive try if numofitemsretrieved maxitemstoretreive break items append get nowait except empty break return items this would limit the receiving thread to pulling up to items at time
QA
how would you make comma separated string from list what would be your preferred way to concatenate strings from sequence such that between each two consecutive pair comma is added that is how do you map for instance to the cases and should be mapped to and respectively usually end up using something like join map lambda but also feeling somewhat unsatisfied edit am both ashamed and happy that the solution is so simple obviously have hardly clue as to what am doing probably needed simple concatenation in the past and somehow memorised join as shorthand for
here is alternative solution in python which allows non string list items alist standard way join map str alist the alternative solution import io io stringio print alist file sep end getvalue note the space after comma is intentional
QA
customized command line parsing in python am writing she will for project of mine which by design parses commands that looks like this command name arg long value arg arg me me com my problem is that python command line parsing libraries getopt and optparse forces me to use or in front of the arguments this behavior does not match my requirements any ideas how can this be solved any existing library for this
without fairly intensive surgery on optparse or getopt do not believe you can sensibly make them parse your format you can easily parse your own format though or translate it into something optparse could handle parser optparse optionparser parser add option arg dest arg help parser add option newargs sys argv for idx arg in enumerate sys argv parts arg split if len parts end of options do not translate the rest newargs extend sys argv idx break argname argvalue parts newargs extend argname argvalue parser parse args newargs
QA
customized command line parsing in python am writing she will for project of mine which by design parses commands that looks like this command name arg long value arg arg me me com my problem is that python command line parsing libraries getopt and optparse forces me to use or in front of the arguments this behavior does not match my requirements any ideas how can this be solved any existing library for this
you could split them up with shlex split which can handle the quoted values you have and pretty easily parse this with very simple regular expression or you can just use regular expressions for both splitting and parsing or simply use split args for arg in shlex split cmdln args key value arg split args key value
QA
best way to access table instances when using sqlalchemy declarative syntax all the docs for sqlalchemy give insert and update examples using the local table instance tablename update doing this seems difficult with the declarative syntax need to reference base metadata tables tablename to get the table reference am supposed to do this another way is there different syntax for insert and update recommended when using the declarative syntax should just switch to the old way
well it works for me class users base tablename users table args autoload true users users print users table select select users
QA
how to skip the docstring using regex am trying to insert some import lines into python source file but would ideally like to place them right after the initial docstring let us say load the file into the lines variable like this lines open filename py readlines how to find the line number where the docstring ends
rather than using regex or relying on specific formatting you could use python tokenize module import tokenize open filename insert index none for tok text srow scol erow ecol in tokenize generate tokens readline if tok tokenize comment continue elif tok tokenize string insert index erow ecol break else break no docstring found this way you can even handle pathological cases like comment not the real docstring this is the module docstring containing and having code on the same line following it this is code excactly as python would handle them
QA
order by is not working how it should how expect it to in my django project am using product objects all order by order in view but it does not seem to be working properly this is it is output product name sort evolution polarity jumbulaya kalidascope it should look like this product name sort polarity evolution jumbulaya kalidascope but it does not any ideas my view for that output def debug request order product objects all order by order return render to response cms debug html order order name name and the view responsible for saving the order field def manage all request if request method post postentries len request post while postentries product objects get pk order int request post get str print itr str save print product order saved return httpresponse saved and the model without the boring bits class product models model name models charfield max length order models integerfield blank true null true here is live example of the page http massiveatom com debug please note that that is only running on the dev server so it may not always be up have asked in django and they did not seem to know what was going on one thought was that the database django was being confused by the sql command it is generating select from table where order by order but would prefer not to change the order field in the model and know there should be back ticks surrounding order in the above sql command but the syntax parsing thingy kind of hated on it edit each object has the correct value so do not really know why it is not sorting it properly edit do not know what was going on but it turns out putting save in the loop fixed it all
your saving loop is wrong you save product outside of the loop it should be if request method post postentries len request post while postentries product objects get pk order int request post get str print itr str save note here saving in loop instead of outside print product order saved return httpresponse saved
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
if you are using gnu emacs or before or xemacs use python mode el the gnu emacs python el will not work on them on gnu emacs python el does work and ties in better with gnu emacs own symbol parsing and completion eldoc etc use xemacs myself so do not use it and have heard people complain that it did not work very nicely in the past but there are updates available that fix some of the issues for instance on the emacswiki page you link and you would hope some were integrated upstream by now if were the gnu emacs kind would use python el until found specific reasons not to the python mode el single biggest problem as far as have seen is that it does not quite understand triple quoted strings it treats them as single quoted meaning that single quote inside triple quoted string will throw off the syntax highlighting it will think the string has ended there you may also need to change your auto mode alist to turn on python mode for py files do not remember if that is still the case but my init el has been setting auto mode alist for many years now as for other addons nothing would consider essential xemacs func menu is sometimes useful it gives you little function class browser menu for the current file do not remember if gnu emacs has anything similar have rst mode for restructuredtext editing as that is used in some projects tying into whatever vc you use if any may be useful to you but there is builtin support for most and easily downloaded el files for the others
QA
customized command line parsing in python am writing she will for project of mine which by design parses commands that looks like this command name arg long value arg arg me me com my problem is that python command line parsing libraries getopt and optparse forces me to use or in front of the arguments this behavior does not match my requirements any ideas how can this be solved any existing library for this
small pythonic variation on ironforggy shlex answer args dict arg split for arg in shlex split cmdln args oops corrected thanks sebastian got to remember those single argument generator expressions
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
you could use the filter function it filters list or strictly an iterable producing new list containing only the items for which the specified function evaluates to true are xrange def is div two return def is div three return print len filter is div two print len filter is div three this is good as it allows you keep your statistics logic contained in function and the intent of the filter should be pretty clear
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 definitely be looking at numpy array instead of an iterable list if you just have numbers you will almost certainly be able to do what you want with some terse arithmetic on the array
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
well you could do one list comprehension expression to get set of tuples with that stat test in them and then reduce that down to get the sums xrange for in are def add tuples return tuple for in zip sums reduce add tuples is starting amount print sums sum of numbers divisible by print sums sum of numbers divisible by using generator expression etc should mean you will only run through the iterator once unless reduce does anything odd basically you would be doing map reduce
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
not as terse as you are looking for but more efficient it actually works with any iterable not just iterables you can loop over multiple times and you can expand the things to check for without complicating it further are xrange counts for in for in counts if not counts or more obscure counts not for in counts print counts
QA
customized command line parsing in python am writing she will for project of mine which by design parses commands that looks like this command name arg long value arg arg me me com my problem is that python command line parsing libraries getopt and optparse forces me to use or in front of the arguments this behavior does not match my requirements any ideas how can this be solved any existing library for this
try to follow standards for command line interfaces convert your arguments as thomas suggested to optionparser format parser parse args if in else for in sys argv if command line arguments are not in sys argv or similar list but in string then as ironfroggy suggested use shlex split parser parse args if in else for in shlex split argsline
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 but maybe you should refactor the code to function that takes an argument which should contain the divisible number two and three and then you could have better functionname def methodname divnumber return sum for in if divnumber print methodname xrange print methodname xrange
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
having to iterate over the list multiple times is not elegant imho would probably create function that allows doing twos threes countmatching xrange lambda lambda starting point would be something like this def countmatching iterable predicates len predicates for in iterable for in enumerate predicates if return tuple by the way itertools recipes has recipe for doing much like your alt def quantify seq pred none count how many times the predicate is true in the sequence return sum imap pred seq
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
from itertools import groupby from collections import defaultdict def multiples return if else if else none defaultdict list for values in groupby range multiples if is not none extend values
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
have you tried cheetah do not have direct experience running it under jython but there seem to be some people that do
QA
get timer ticks in python am just trying to time piece of code the pseudocode looks like start get ticks do long code print it took get ticks start seconds how does this look in python more specifically how do get the number of ticks since midnight or however python organizes that timing
in the time module there are two timing functions time and clock time gives you wall time if this is what you care about however the python docs say that clock should be used for benchmarking note that clock behaves different in separate systems on ms windows it uses the win function queryperformancecounter with resolution typically better than microsecond it has no special meaning it is just number it starts counting the first time you call clock in your process ms windows time clock do something time clock is wall seconds elapsed floating point on nix clock reports cpu time now this is different and most probably the value you want since your program hardly ever is the only process requesting cpu time even if you have no other processes the kernel uses cpu time now and then so this number which typically is smaller than the wall time time time is more meaningful when benchmarking code linux time clock do something time clock is cpu seconds elapsed floating point apart from all that the timeit module has the timer class that is supposed to use what is best for benchmarking from the available functionality unless threading gets in the way python there are time perf counter and time process time perf counter is being used by the timeit module
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
time clock only measures wallclock time on windows on other systems time clock actually measures cpu time on those systems time time is more suitable for wallclock time and it has as high resolution as python can manage which is as high as the os can manage usually using gettimeofday microsecond resolution or ftime millisecond resolution other os restrictions actually make the real resolution lot higher than that datetime datetime now uses time time so time time directly will not be better for the record if use datetime datetime now in loop see about second resolution from looking at your data you have much much coarser resolution than that am not sure if there is anything python as such can do although you may be able to convince the os to do better through other means seem to recall that on windows time clock is actually slightly more accurate than time time but it measures wallclock since the first call to time clock so you have to remember to initialize it first
QA
python dictionary key sort have dictionary of items the keys are strings and the values are integers what is the best most pythonic way to print the items sorted by descending value then ascending key key sort keyc keyb keya items sort key lambda sort key lambda reverse true print keyb keya keyc
you cannot sort dictionaries you have to sort the list of items previous versions were wrong when you have numeric value it is easy to sort in reverse order these will do that but this is not general this only works because the value is numeric key another key items sort key lambda print here is an alternative using an explicit function instead of lambda and the cmp instead of the key option def valuekeycmp return cmp sort cmp valuekeycmp print the more general solution is actually two separate sorts sort key lambda reverse true sort key lambda print
QA
python dictionary key sort have dictionary of items the keys are strings and the values are integers what is the best most pythonic way to print the items sorted by descending value then ascending key key sort keyc keyb keya items sort key lambda sort key lambda reverse true print keyb keya keyc
the most pythonic way to do it would be to know little more about the actual data specifically the maximum value you can have and then do it like this def sortkey return maxval items thedict items items sort key sortkey but unless you already know the maximum value searching for the maximum value means looping through the dict an extra time with max thedict itervalues which may be expensive alternatively keyfunc version of lott solution def sortkey return items thedict items items sort key sortkey an alternative that does not care about the types would be comparison function def sortcmp ak av bk bv compare values in reverse are cmp bv av if not and then keys normally are cmp ak bk return items thedict items items sort cmp sortcmp and this solution actually works for any type of key and value that you want to mix ascending and descending sorting with in the same key if you value brevity you can write sortcmp as def sortcmp ak av bk bv return cmp bk av ak bv
QA
python dictionary key sort have dictionary of items the keys are strings and the values are integers what is the best most pythonic way to print the items sorted by descending value then ascending key key sort keyc keyb keya items sort key lambda sort key lambda reverse true print keyb keya keyc
you can use something like this dic aaa aab aaf aac aad aae def sort compare cmp dic dic if return return cmp for in sorted dic keys cmp sort compare print dic do not know how pythonic it is however
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
the idea here is to use reduction to avoid repeated iterations also this does not create any extra data structures if memory is an issue for you you start with dictionary with your counters div div and increment them along the iteration def increment stats stats if stats div if stats div return stats are xrange stats reduce increment stats div div print stats if you want to count anything more complicated than divisors it would be appropriate to use more object oriented approach with the same advantages encapsulating the logic for stats extraction class stats def init self div div self div div self div div def increment self if self div if self div return self def repr self return stats self div self div are xrange stats reduce lambda stats stats increment stats print stats please point out any mistakes henrik think the first approach is less maintainable since you have to control initialization of the dictionary in one place and update in another as well as having to use strings to refer to each stat instead of having attributes and do not think oo is overkill in this case for you said the predicates and objects will be complex in your application in fact if the predicates were really simple would not even bother to use dictionary single fixed size list would be just fine cheers
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
here is thread about python timing accuracy http stackoverflow com questions python timeclock vs timetime accuracy
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
you are unlikely to get sufficiently fine grained control that you can completely eliminate the possibility of duplicate timestamps you would need resolution smaller than the time it takes to generate datetime object there are couple of other approaches you might take to deal with it deal with it leave your timestamps non unique as they are but rely on python sort being stable to deal with reordering problems sorting on timestamp first then something else will retain the timestamp ordering you just have to be careful to always start from the timestamp ordered list every time rather than doing multiple sorts on the same list append your own value to enforce uniqueness eg include an incrementing integer value as part of the key or append such value only if timestamps are different eg the following will guarantee unique timestamp values class timestamper object def init self self lock threading lock self prev none self count def gettimestamp self with self lock ts str datetime now if ts self prev ts self count self count else self prev ts self count return ts for multiple processes rather than threads it gets bit trickier though
QA
how can parse comma delimited string into list caveat need to be able to take string like foo bar one two three four into foo bar one two three four have an feeling with hints from python that the solution is going to involve the shlex module
would say regular expression would be what you are looking for here though am not terribly familiar with python regex engine assuming you use lazy matches you can get set of matches on string which you can put into your array
QA
python dictionary key sort have dictionary of items the keys are strings and the values are integers what is the best most pythonic way to print the items sorted by descending value then ascending key key sort keyc keyb keya items sort key lambda sort key lambda reverse true print keyb keya keyc
data keyc keyb keya for key value in sorted data items key lambda print key value
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
timestamp should be accurate relative to each other why time why not sequence number if it is any client of client server application network latency makes timestamps kind of random are you matching some external source of information say log on another application again if there is network those times will not be too close if you must match things between separate apps consider passing guid around so that both apps log the guid value then you could be absolutely sure they match irrespective of timing differences if you want the relative order to be exactly right maybe it is enough for your logger to assign sequence number to each message in the order they were received
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
there are several rot utilities written in python on the net just google for them rot encode the string offline copy it into the source decode at point of transmission but this is really weak protection
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 encoding is in the standard library and will do to stop shoulder surfers import base print base encode password cgfzc dvcmq print base decode cgfzc dvcmq password
QA
python dictionary key sort have dictionary of items the keys are strings and the values are integers what is the best most pythonic way to print the items sorted by descending value then ascending key key sort keyc keyb keya items sort key lambda sort key lambda reverse true print keyb keya keyc
building on thomas wouters and ricardo reyes solutions def combine cmps sequence comparisons def comparator for cmp in cmps result cmp if result return result return return comparator def reverse cmp invert comparison def comparator return cmp return comparator def compare nth cmp compare the th item from two sequences def comparator return cmp return comparator rev val key cmp combine compare values decreasing reverse compare nth cmp compare keys increasing compare nth cmp data keyc keyb keya for key value in sorted data items cmp rev val key cmp print key value