prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
change django templates based on user agent have made django site but have drank the koolaid and want to make an iphone version after putting much thought into have come up with two options make whole other site like xxxx com tie it into the same database using django sites framework find some time of middleware that reads the user agent and changes the template directories dynamically would really prefer option however have some reservations mainly because the django documentation discourages changing settings on the fly found snippet that would do the what would like my main issue is having it as seamless as possible would like it to be automagic and transparent to the user has anyone else come across the same issue would anyone care to share about how they have tackled making iphone versions of django sites update went with combination of middleware and tweaking the template call for the middleware used minidetector like it because it detects plethora of mobile user agents all have to do is check request mobile in my views for the template call tweak def check mobile request template name if request mobile return mobile template name return template name use this for any view that know have both versions todo figure out how to access request mobile in an extended version of render to response so do not have to use check mobile template name html using the previous automagically fallback to the regular template if no mobile version exists
|
how about redirecting user to xxx com after parsing his ua in some middleware highly doubt that mobile users care how url look like still they can access your site using main url
|
QA
|
can list display in django modeladmin display attributes of foreignkey fields have person model that has foreign key relationship to book book has number of fields but am most concerned about author standard charfield with that being said in my personadmin model would like to display book author using list display have tried all of the obvious methods for doing so see below but nothing seems to work any suggestions class personadmin admin modeladmin list display book author
|
as another option you can do look ups like class useradmin admin modeladmin list display get author def get author self obj return obj book author get author short description author get author admin order field book author
|
QA
|
programmatically launching standalone adobe flashplayer on linux the standalone flashplayer takes no arguments other than swf file when you launch it from the command line need the player to go full screen no window borders and such this can be accomplished by hitting ctrl once the program has started want to do this programmatically as need it to launch into full screen without any human interaction my guess is that need to some how get handle to the window and then send it an event that looks like the ctrl keystroke if it makes any difference it looks like flashplayer is gtk application and have python with pygtk installed update the solution used thanks to ypnos answer flashplayer http example com example swf sleep xsendkey window adobe flash player control
|
have actually done this long time ago but it was not petty what we did is use the sawfish window manager and wrote hook to recognize the flashplayer window then strip all the decorations and snap it full screen this may be possible without using the window manager by registering for window creation events from an external application but am not familiar enough with to tell you how that would be done another option would be to write pygtk application that embedded the standalone flash player inside gtk socket and then resized itself after bit of thought this might be your best bet
|
QA
|
subclassing class with private members one of the really nice things about python is the simplicity with which you can name variables that have the same name as the accessor self value def value return self value is there simple way of providing access to the private members of class that wish to subclass often wish to simply work with the raw data objects inside of class without having to use accessors and mutators all the time know this seems to go against the general idea of private and public but usually the class am trying to subclass is one of my own which am quite happy to expose the members from to subclass but not to an instance of that class is there clean way of providing this distinction
|
know this seems to go against the general idea of private and public not really against just different from and java private as implemented in and java is not very useful concept it helps sometimes to isolate implementation details but it is way overused python names beginning with two are special and you should not as normal thing be defining attributes with names like this names with are special and part of the implementation and exposed for your use names beginning with one are private sometimes they are concealed little most of the time the consenting adults rule applies do not use them foolishly they are subject to change without notice we put private in quotes because it is just an agreement between you and your users you have marked things with your users and yourself should honor that often we have method function names with leading to indicate that we consider them to be private and subject to change without notice the endless getters and setters that java requires are not as often used in python python introspection is more flexible you have access to an object internal dictionary of attribute values and you have first class functions like getattr and setattr further you have the property function which is often used to bind getters and setters to single name that behaves like simple attribute but is actually well defined method function calls
|
QA
|
apache sockets not closing have web application written using cherrypy which is run locally on we use mod rewrite and mod proxy to have apache act as reverse proxy apache also handles our ssl encryption and may eventually be used to transfer all of our static content this all works just fine for small workloads however recently used urllib to write stress testing script that would simulate workload of clients after some time each client gets error from apache indicating that apache cannot connect to cherrypy is functioning properly but my apache error log reveals lines like the following thu oct error os only one usage of each socket address protocol network address port is normally permitted proxy http attempt to connect to failed googling for this error reveals that apache has probably run out of socket file descriptors since only have clients running this implies that the connections are not being closed either between my urllib connection and apache am definitely calling close on the return value of urlopen or between apache and cherrypy have confirmed that my urllib request is sending an http connection close header although apache is configured with keepalive on if that matters in case it matters am using python apache cherrypy and the server is running on windows server so what is my next step to stop this problem
|
setenv proxy nokeepalive would probably tell you right away if the problem is keepalive between apache and cp see the mod proxy docs for more info
|
QA
|
how do get the key value of db referenceproperty without database hit is there way to get the key or id value of db referenceproperty without dereferencing the actual entity it points to have been digging around it looks like the key is stored as the property name preceeded with an but have been unable to get any code working examples would be much appreciated thanks edit here is what have unsuccessfully tried class comment db model series db referenceproperty reference class series def series id self return self series and in my template href games view series html series comment series id comm comment key id more the result href games view series html series comm more
|
actually the way that you are advocating accessing the key for referenceproperty might well not exist in the future attributes that begin with in python are generally accepted to be protected in that things that are closely bound and intimate with its implementation can use them but things that are updated with the implementation must change when it changes however there is way through the public interface that you can access the key for your reference property so that it will be safe in the future will revise the above example class comment db model series db referenceproperty reference class series def series id self return comment series get value for datastore self when you access properties via the class it is associated you get the property object itself which has public method that can get the underlying values
|
QA
|
how would package and sell django app currently am hosting django app developed myself for my clients but am now starting to look at selling it to people for them to host themselves my question is this how can package up and sell django app while protecting its code from pirating or theft distributing bunch of py files does not sound like good idea as the people sell it to too could just make copies of them and pass them on think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same lamp setup
|
the way would go about it is this encrypt all of the code write an installer that contacts the server with the machine hostname and license file and gets the decryption key then decrypts the code and compiles it to python bytecode add in the installer module that checks the machine hostname and license file on import and dies if it does not match this way the user only has to contact the server when the hostname changes and on first install but you get small layer of security you could change the hostname to something more complex but there is really no need anyone that wants to pirate this will do so but simple mechanism like that will keep honest people honest
|
QA
|
how would package and sell django app currently am hosting django app developed myself for my clients but am now starting to look at selling it to people for them to host themselves my question is this how can package up and sell django app while protecting its code from pirating or theft distributing bunch of py files does not sound like good idea as the people sell it to too could just make copies of them and pass them on think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same lamp setup
|
you could package the whole thing up as an amazon machine instance ami and then have them run your app on amazon ec the nice thing about this solution is that amazon will take care of billing for you and since you are distributing the entire machine image you can be certain that all your clients are using the same lamp stack the ami is an encrypted machine image that is configured however you want it you can have amazon bill the client with one time fee usage based fee or monthly fee of course this solution requires that your clients host their app at amazon and pay the appropriate fees
|
QA
|
how would package and sell django app currently am hosting django app developed myself for my clients but am now starting to look at selling it to people for them to host themselves my question is this how can package up and sell django app while protecting its code from pirating or theft distributing bunch of py files does not sound like good idea as the people sell it to too could just make copies of them and pass them on think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same lamp setup
|
do not try and obfuscate or encrypt the code it will never work would suggest selling the django application as service either host it for them or sell them the code and support write up contract that forbids them from redistributing it that said if you were determined to obfuscate the code in some way you can distribute python applications entirely as pyc python compiled byte code it is how py app works it will still be re distributable but it will be very difficult to edit the files so you could add some basic licensing stuff and not have it foiled by few as said do not think you will succeed in anti piracy via encryption or obfuscation etc depending on your clients simple contract and maybe some really basic checks will go long much further than some complicated decryption system and make the experience of using your application better instead of hopefully not any worse
|
QA
|
programmatically launching standalone adobe flashplayer on linux the standalone flashplayer takes no arguments other than swf file when you launch it from the command line need the player to go full screen no window borders and such this can be accomplished by hitting ctrl once the program has started want to do this programmatically as need it to launch into full screen without any human interaction my guess is that need to some how get handle to the window and then send it an event that looks like the ctrl keystroke if it makes any difference it looks like flashplayer is gtk application and have python with pygtk installed update the solution used thanks to ypnos answer flashplayer http example com example swf sleep xsendkey window adobe flash player control
|
you can use dedicated application which sends the keystroke to the window manager which should then pass it to flash if the window starts as being the active window on the screen this is quite error prone though due to delays between starting flash and when the window will show up for example your script could do something like this flashplayer swf sleep xsendkey control the application xsendkey can be found here http people csail mit edu adonovan hacks xsendkey html without given specific window it will send it to the root window which is handled by your window manager you could also try to figure out the window id first using xprop or something related to it another option is window manager which is able to remember your settings and automatically apply them fluxbos for example provides this feature you could set fluxbox to make the window decor less and stretch it over the whole screen if flashplayer supports being resized this is also not so nice as it would probably affect all the flashplayer windows you open ever
|
QA
|
what is the difference between ruby and python versions of self have done some python but have just now starting to use ruby could use good explanation of the difference between self in these two languages obvious on first glance self is not keyword in python but there is self like value no matter what you call it python methods receive self as an explicit argument whereas ruby does not ruby sometimes has methods explicitly defined as part of self using dot notation initial googling reveals http rubylearning com satishtalim ruby self html http www ibiblio org swap byteofpython read self html
|
despite webmat claim guido wrote that explicit self is not an implementation hack it is semantic device the reason for explicit self in method definition signatures is semantic consistency if you write class def foo self this really is the same as writing class pass def foo self foo foo this was an intentional design decision not result of introducing oo behaviour at latter date everything in python is an object including literals see also why must self be used explicitly in method definitions and calls
|
QA
|
what is the best way to sample profile pyobjc application sampling with activity monitor instruments shark will show stack traces full of functions for the python interpreter would be helpful to see the corresponding python symbol names is there some dtrace magic that can do that python cprofile module can be useful for profiling individual subtrees of python calls but not so much for getting picture of what is going on with the whole application in response to user events
|
the answer is dtrace but it will not work on sufficiently old macs http tech marshallfamily com au archives python dtrace on os leopard part http tech marshallfamily com au archives python dtrace on os leopard part
|
QA
|
python how do pass string into subprocess popen using the stdin argument if do the following import subprocess from cstringio import stringio subprocess popen grep stdout subprocess pipe stdin stringio one ntwo nthree nfour nfive nsix communicate get traceback most recent call last file stdin line in file build toolchain mac python lib python subprocess py line in init cread cwrite file build toolchain mac python lib python subprocess py line in get handles cread stdin fileno attributeerror cstringio stringi object has no attribute fileno apparently cstringio stringio object does not quack close enough to file duck to suit subprocess popen how do work around this
|
popen communicate documentation note that if you want to send data to the process stdin you need to create the popen object with stdin pipe similarly to get anything other than none in the result tuple you need to give stdout pipe and or stderr pipe too replacing os popen pipe os popen cmd bufsize pipe popen cmd she will true bufsize bufsize stdin pipe stdin warning use communicate rather than stdin write stdout read or stderr read to avoid deadlocks due to any of the other os pipe buffers filling up and blocking the child process so your example could be written as follows from subprocess import popen pipe stdout popen grep stdout pipe stdin pipe stderr stdout grep stdout communicate input one ntwo nthree nfour nfive nsix print grep stdout decode four five
|
QA
|
python object attributes methodology for access suppose have class with some attributes how is it best in the pythonic oop sense to access these attributes just like obj attr or perhaps write get accessors what are the accepted naming styles for such things edit can you elaborate on the best practices of naming attributes with single or double leading underscore see in most modules that single underscore is used if this question has already been asked and have hunch it has though searching did not bring results please point to it and will close this one
|
think most just access them directly no need for get set methods class myclass hello class inst myclass class inst hello class inst world class inst world by the way you can use the dir function to see what attributes methods are attached to your instance dir class inst doc module two leading underbars are used to make attribute or function private for other conventions refer to pep http www python org dev peps pep
|
QA
|
python object attributes methodology for access suppose have class with some attributes how is it best in the pythonic oop sense to access these attributes just like obj attr or perhaps write get accessors what are the accepted naming styles for such things edit can you elaborate on the best practices of naming attributes with single or double leading underscore see in most modules that single underscore is used if this question has already been asked and have hunch it has though searching did not bring results please point to it and will close this one
|
python does not need to define accessors right from the beginning since converting attributes into properties is quick and painless see the following for vivid demonstration recovery from addiction
|
QA
|
python object attributes methodology for access suppose have class with some attributes how is it best in the pythonic oop sense to access these attributes just like obj attr or perhaps write get accessors what are the accepted naming styles for such things edit can you elaborate on the best practices of naming attributes with single or double leading underscore see in most modules that single underscore is used if this question has already been asked and have hunch it has though searching did not bring results please point to it and will close this one
|
the generally accepted way of doing things is just using simple attributes like so class myclass myattribute myclass myattribute myattribute myattribute if you do find yourself needing to be able to write getters and setters then what you want to look for is python class properties and ryan tomayko article on getters setters fuxors is great place to start albeit little long
|
QA
|
python object attributes methodology for access suppose have class with some attributes how is it best in the pythonic oop sense to access these attributes just like obj attr or perhaps write get accessors what are the accepted naming styles for such things edit can you elaborate on the best practices of naming attributes with single or double leading underscore see in most modules that single underscore is used if this question has already been asked and have hunch it has though searching did not bring results please point to it and will close this one
|
there is no real point of doing getter setters in python you cannot protect stuff anyway and if you need to execute some extra code when getting setting the property look at the property builtin python help property
|
QA
|
sleeping in batch file when writing batch file to automate something on windows box have needed to pause its execution for several seconds usually in test wait loop waiting for process to start at the time the best solution could find uses ping kid you not to achieve the desired effect have found better write up of it here which describes callable wait bat implemented as follows ping nul ping nul you can then include calls to wait bat in your own batch file passing in the number of seconds to sleep apparently the windows resource kit provides unix like sleep command at last in the meantime for those of us still using windows xp windows or sadly windows nt is there better way modified the sleep py script in the accepted answer so that it defaults to one second if no arguments are passed on the command line import time sys time sleep float sys argv if len sys argv else
|
the resource kit has always included this at least since windows also the cygwin package has sleep plop that into your path and include the cygwin dll or whatever it is called and way to go
|
QA
|
detecting mouse clicks in windows using python how can detect mouse clicks regardless of the window the mouse is in perferabliy in python but if someone can explain it in any langauge might be able to figure it out found this on microsoft site http msdn microsoft com en us library ms vs aspx but do not see how can detect or pick up the notifications listed tried using pygame pygame mouse get pos function as follows import pygame pygame init while true print pygame mouse get pos this just returns am not familiar with pygame is something missing in anycase would prefer method without the need to install rd party module other than pywin http sourceforge net projects pywin
|
the windows way of doing it is to handle the wm lbuttondblclk message for this to be sent your window class needs to be created with the cs dblclks class style am afraid do not know how to apply this in python but hopefully it might give you some hints
|
QA
|
sleeping in batch file when writing batch file to automate something on windows box have needed to pause its execution for several seconds usually in test wait loop waiting for process to start at the time the best solution could find uses ping kid you not to achieve the desired effect have found better write up of it here which describes callable wait bat implemented as follows ping nul ping nul you can then include calls to wait bat in your own batch file passing in the number of seconds to sleep apparently the windows resource kit provides unix like sleep command at last in the meantime for those of us still using windows xp windows or sadly windows nt is there better way modified the sleep py script in the accepted answer so that it defaults to one second if no arguments are passed on the command line import time sys time sleep float sys argv if len sys argv else
|
sleep exe is included in most resource kits the windows server resource kit which can be installed on windows xp too usage sleep time to sleep in seconds sleep time to sleep in milliseconds sleep commited memory ratio
|
QA
|
python object attributes methodology for access suppose have class with some attributes how is it best in the pythonic oop sense to access these attributes just like obj attr or perhaps write get accessors what are the accepted naming styles for such things edit can you elaborate on the best practices of naming attributes with single or double leading underscore see in most modules that single underscore is used if this question has already been asked and have hunch it has though searching did not bring results please point to it and will close this one
|
edit can you elaborate on the best practices of naming attributes with single or double leading underscore see in most modules that single underscore is used single underscore does not mean anything special to python it is just best practice to tell hey you probably do not want to access this unless you know what you are doing double underscore however makes python mangle the name internally making it accessible only from the class where it is defined double leading and trailing underscore denotes special function such as add which is called when using the operator read more in pep especially the naming conventions section
|
QA
|
sleeping in batch file when writing batch file to automate something on windows box have needed to pause its execution for several seconds usually in test wait loop waiting for process to start at the time the best solution could find uses ping kid you not to achieve the desired effect have found better write up of it here which describes callable wait bat implemented as follows ping nul ping nul you can then include calls to wait bat in your own batch file passing in the number of seconds to sleep apparently the windows resource kit provides unix like sleep command at last in the meantime for those of us still using windows xp windows or sadly windows nt is there better way modified the sleep py script in the accepted answer so that it defaults to one second if no arguments are passed on the command line import time sys time sleep float sys argv if len sys argv else
|
faced similar problem but just knocked up very short console application to do the same thing just run mysleep exe perhaps easier than downloading installing the whole resource kit include tchar include stdio include windows int tmain int argc tchar argv if argc tprintf sleeping for ms argv sleep tstoi argv else tprintf wrong number of arguments return
|
QA
|
python object attributes methodology for access suppose have class with some attributes how is it best in the pythonic oop sense to access these attributes just like obj attr or perhaps write get accessors what are the accepted naming styles for such things edit can you elaborate on the best practices of naming attributes with single or double leading underscore see in most modules that single underscore is used if this question has already been asked and have hunch it has though searching did not bring results please point to it and will close this one
|
with regards to the single and double leading underscores both indicate the same concept of privateness that is to say people will know the attribute be it method or normal data attribute or anything else is not part of the public api of the object people will know that to touch it directly is to invite disaster on top of that the double leading underscore attributes but not the single leading underscore attributes are name mangled to make accessing them by accident from subclasses or anywhere else outside the current class less likely you can still access them but not as trivially for example class classa def init self self single single self double double def getsingle self return self single def getdouble self return self double class classb classa def getsingle self return self single def getdouble self return self double classa classb you can now trivially access single and single and get the single attribute created by classa single single single single getsingle getsingle getsingle single single single but trying to access the double attribute on the or instance directly will not work double traceback most recent call last file stdin line in module attributeerror classa instance has no attribute double double traceback most recent call last file stdin line in module attributeerror classb instance has no attribute double and though methods defined in classa can get at it directly when called on either instance getdouble getdouble double double methods defined on classb can not getdouble traceback most recent call last file stdin line in module file stdin line in getdouble attributeerror classb instance has no attribute classb double and right in that error you get hint about what is happening the double attribute name when accessed inside class is being name mangled to include the name of the class that it is being accessed in when classa tries to access self double it actually turns at compiletime into an access of self classa double and likewise for classb if method in classb were to assign to double not included in the code for brevity it would therefor not touch classa double but create new attribute there is no other protection of this attribute so you can still access it directly if you know the right name classa double classa double double double so why is this problem well it is problem any time you want to inherit and change the behaviour of any code dealing with this attribute you either have to reimplement everything that touches this double underscore attribute directly or you have to guess at the class name and mangle the name manually the problem gets worse when this double underscore attribute is actually method overriding the method or calling the method in subclass means doing the name mangling manually or reimplementing all the code that calls the method to not use the double underscore name not to mention accessing the attribute dynamically with getattr you will have to manually mangle there too on the other hand because the attribute is only trivially rewritten it offers only superficial protection any piece of code can still get at the attribute by manually mangling although that will make their code dependant on the name of your class and efforts on your side to refactor your code or rename your class while still keeping the same user visible name common practice in python would needlessly break their code they can also trick python into doing the name mangling for them by naming their class the same as yours notice how there is no module name included in the mangled attribute name and lastly the double underscore attribute is still visible in all attribute lists and all forms of introspection that do not take care to skip attributes starting with single underscore so if you use double underscore names use them exceedingly sparingly as they can turn out quite inconvenient and never use them for methods or anything else subclass may ever want to reimplement override or access directly and realize that double leading underscore name mangling offers no real protection in the end using single leading underscore wins you just as much and gives you less potential future pain use single leading underscore
|
QA
|
detecting mouse clicks in windows using python how can detect mouse clicks regardless of the window the mouse is in perferabliy in python but if someone can explain it in any langauge might be able to figure it out found this on microsoft site http msdn microsoft com en us library ms vs aspx but do not see how can detect or pick up the notifications listed tried using pygame pygame mouse get pos function as follows import pygame pygame init while true print pygame mouse get pos this just returns am not familiar with pygame is something missing in anycase would prefer method without the need to install rd party module other than pywin http sourceforge net projects pywin
|
windows mfc including gui programming is accessible with python using the python for windows extensions by mark hammond an reilly book excerpt from hammond and robinson book shows how to hook mouse messages self hookmessage self onmousemove win con wm mousemove raw mfc is not easy or obvious but searching the web for python examples may yield some usable examples
|
QA
|
sleeping in batch file when writing batch file to automate something on windows box have needed to pause its execution for several seconds usually in test wait loop waiting for process to start at the time the best solution could find uses ping kid you not to achieve the desired effect have found better write up of it here which describes callable wait bat implemented as follows ping nul ping nul you can then include calls to wait bat in your own batch file passing in the number of seconds to sleep apparently the windows resource kit provides unix like sleep command at last in the meantime for those of us still using windows xp windows or sadly windows nt is there better way modified the sleep py script in the accepted answer so that it defaults to one second if no arguments are passed on the command line import time sys time sleep float sys argv if len sys argv else
|
the usage of ping is good as long as you just want to wait for bit this since you are dependent on other functions underneath like your network working and the fact that there is nothing answering on maybe it is not very likely it fails but it is not impossible if you want to be sure that you are waiting exactly the specified time you should use the sleep functionality which also have the advantage that it does not use cpu power or wait for network to become ready to find an already made executable for sleep is the most convenient way just drop it into your windows folder or any other part of your standard path and it is always available otherwise if you have compiling environment you can easily make one yourself the sleep function is available in kernel dll so you just need to use that one for vb vba declare the following in the beginning of your source to declare sleep function private declare sub sleep lib kernel alias sleep byval dwmilliseconds as long for dllimport kernel dll static extern void sleep uint dwmilliseconds you will find here more about this functionality available since windows in sleep function msdn in standard sleep is included in the standard library and in microsoft visual studio the function is named sleep if memory serves me those two takes the argument in seconds not in milliseconds as the two previous declarations
|
QA
|
how can capture all exceptions from wxpython application am writing little debug app for bit of kit we are developing and would like to roll it out to few users to see if they can provoke any crashes does anyone know way of effectively wrapping wxpython app to catch any and all unhandled exceptions that would cause the app to crash ideally would want to capture all output not just errors and log it to file any unhandled exceptions ought to log to the current file and then allow the exception to pass on as per usual the logging process ought to be transparent am sure someone must have done something along these lines before but have not managed to turn up anything that looks useful via google
|
there are various ways you can put try catch block in the wxapplication oninit however that would not always work with gtk nice alternative would be to override the application handleevent in your wxapplication derived class and write code like this void application handleevent wxevthandler handler wxeventfunction func wxevent event const try wxappconsole handleevent handler func event catch const std exception wxmessagebox std wx what unhandled error wxok wxicon error wxgettoplevelparent wxgetactivewindow it is example but you can surely translate to python easily
|
QA
|
how can capture all exceptions from wxpython application am writing little debug app for bit of kit we are developing and would like to roll it out to few users to see if they can provoke any crashes does anyone know way of effectively wrapping wxpython app to catch any and all unhandled exceptions that would cause the app to crash ideally would want to capture all output not just errors and log it to file any unhandled exceptions ought to log to the current file and then allow the exception to pass on as per usual the logging process ought to be transparent am sure someone must have done something along these lines before but have not managed to turn up anything that looks useful via google
|
for logging standard output you can use stdout wrapper such as this one from future import with statement class outwrapper object def init self realoutput logfilename self realoutput realoutput self logfilename logfilename def log self text with open self logfilename as logfile logfile write text def write self text self log text self realoutput write text you then have to initialize it in your main python file the one that runs everything import sys sys stdout outwrapper sys stdout temp log txt as to logging exceptions the easiest thing to do is to wrap mainloop method of wx app in try except then extract the exception information save it in some way and then re raise the exception through raise try app mainloop except exc info sys exc info saveexcinfo exc info this method you have to write yourself raise
|
QA
|
sleeping in batch file when writing batch file to automate something on windows box have needed to pause its execution for several seconds usually in test wait loop waiting for process to start at the time the best solution could find uses ping kid you not to achieve the desired effect have found better write up of it here which describes callable wait bat implemented as follows ping nul ping nul you can then include calls to wait bat in your own batch file passing in the number of seconds to sleep apparently the windows resource kit provides unix like sleep command at last in the meantime for those of us still using windows xp windows or sadly windows nt is there better way modified the sleep py script in the accepted answer so that it defaults to one second if no arguments are passed on the command line import time sys time sleep float sys argv if len sys argv else
|
if you have python installed or do not mind installing it it has other uses too just create the following sleep py script and add it somewhere in your path import time sys time sleep float sys argv it will allow sub second pauses sec etc should you have such need if you want to call it as sleep rather than sleep py then you can add the py extension to your pathext environment variable in xp you can edit it in my computer properties menu advanced tab environment variables button system variables frame
|
QA
|
how do deploy python desktop application have started on personal python application that runs on the desktop am using wxpython as gui toolkit should there be demand for this type of application would possibly like to commercialize it have no knowledge of deploying real life python applications though have used py exe in the past with varied success how would obfuscate the code can somehow deploy only the bytecode an ideal solution would not jeopardize my intellectual property source code would not require direct installation of python though am sure it will need to have some embedded interpreter and would be cross platform windows mac and linux does anyone know of any tools or resources in this area thanks
|
maybe ironpython can provide something for you bet those exe dll files can be pretty locked down not sure how such features work on mono thus no idea how this works on linux os
|
QA
|
clearing list find it annoying that cannot clear list in this example append append the second time initialize to blank list it creates new instance of list which is in different place in memory so cannot use it to reference the first not to mention it is inefficient the only way can see of retaining the same pointer is doing something like the following for in range len pop this seems pretty long winded though is there better way of solving this
|
you are looking for del
|
QA
|
clearing list find it annoying that cannot clear list in this example append append the second time initialize to blank list it creates new instance of list which is in different place in memory so cannot use it to reference the first not to mention it is inefficient the only way can see of retaining the same pointer is doing something like the following for in range len pop this seems pretty long winded though is there better way of solving this
|
am not sure why you are worried about the fact that you are referencing new empty list in memory instead of the same pointer your other list is going to be collected sooner or later and one of the big perks about working in high level garbage collected language is that you do not normally need to worry about stuff like this
|
QA
|
django mod python apache and wacky sessions am running django through mod python on apache on linux box have custom authentication backend and middleware that requires authentication for all pages except static content my problem is that after log in will still randomly get the log in screen now and again it seems to me that each apache process has it is own python process which in turn has it is own internals so as long as get served by the same process logged in to everything is fine and dandy but if my request gets served by different apache process am no longer authenticated have checked the http headers send with firebug and they are the same each time ie same cookie is this known issue and are there workarounds fixes edit have page that displays lot of generated images some off these will not display this is because they are too behind the authenticating middleware so they will randomly put up login image however refreshing this page enough times and it will eventually work meaning all processes recognize my session
|
do you have standard database driven sessions is caching enabled in settings
|
QA
|
finding local ip addresses using python stdlib how can find local ip addresses or in python platform independently and using only the standard library
|
import socket socket gethostbyname socket gethostname this will not work always returns on machines having the hostname in etc hosts as paliative would be what gimel shows use socket getfqdn instead of course your machine needs resolvable hostname
|
QA
|
finding local ip addresses using python stdlib how can find local ip addresses or in python platform independently and using only the standard library
|
am afraid there are not any good platform independent ways to do this other than connecting to another computer and having it send you your ip address for example findmyipaddress note that this will not work if you need an ip address that is behind nat unless the computer you are connecting to is behind nat as well here is one solution that works in linux get the ip address associated with network interface
|
QA
|
django mod python apache and wacky sessions am running django through mod python on apache on linux box have custom authentication backend and middleware that requires authentication for all pages except static content my problem is that after log in will still randomly get the log in screen now and again it seems to me that each apache process has it is own python process which in turn has it is own internals so as long as get served by the same process logged in to everything is fine and dandy but if my request gets served by different apache process am no longer authenticated have checked the http headers send with firebug and they are the same each time ie same cookie is this known issue and are there workarounds fixes edit have page that displays lot of generated images some off these will not display this is because they are too behind the authenticating middleware so they will randomly put up login image however refreshing this page enough times and it will eventually work meaning all processes recognize my session
|
you are correct about how apache handles the processes and sometimes you will get served by different process you can see this when you make change to your site new processes will pick up the change but old processes will give you the old site to get consistency you have to restart apache assuming restart does not fix the problem would guess it is something in the custom authentication backend storing part of the authentication in memory which will not work very well for web server would try setting maxrequestsperchild to in your apache config and seeing if you still get the login screen if you do something is being stored in memory maybe model not being saved hope that helps just out of curiosity why are you using custom authentication backend and middleware to ensure the user is logged in it seems django contrib auth and login required would be easier
|
QA
|
finding public facing ip address in python how can find the public facing ip for my net work in python
|
this will fetch your remote ip address import urllib ip urllib urlopen http automation whatismyip com asp read if you do not want to rely on someone else then just upload something like this php script php echo server remote addr and change the url in the python or if you prefer asp dim useripaddress useripaddress request servervariables remote addr note do not know asp but figured it might be useful to have here so googled
|
QA
|
finding public facing ip address in python how can find the public facing ip for my net work in python
|
whatismyip org is better it just tosses back the ip as plaintext with no extraneous crap import urllib ip urllib urlopen http whatismyip org read but yeah it is impossible to do it easily without relying on something outside the network itself
|
QA
|
finding local ip addresses using python stdlib how can find local ip addresses or in python platform independently and using only the standard library
|
just found this but it seems bit hackish however they say tried it on nix and did on windows and it worked import socket socket socket socket af inet socket sock dgram connect gmail com print getsockname close this assumes you have an internet access and that there is no local proxy
|
QA
|
finding local ip addresses using python stdlib how can find local ip addresses or in python platform independently and using only the standard library
|
you can use the netifaces module just type easy install netifaces in your command she will and it will install itself on default python installation then you can use it like this from netifaces import interfaces ifaddresses af inet for ifacename in interfaces addresses addr for in ifaddresses ifacename setdefault af inet addr no ip addr print ifacename join addresses on my computer it printed bdc be de fbc ae bf author of this module claims it should work on windows unix and mac os
|
QA
|
how to build and deploy python web applications have python web application consisting of several python packages what is the best way of building and deploying this to the servers currently am deploying the packages with capistrano installing the packages into virtualenv with bash and configuring the servers with puppet but would like to go for more python based solution have been looking bit into zc buildout but it is not clear for me what can should use it for
|
would scons do what you want http www scons org
|
QA
|
finding local ip addresses using python stdlib how can find local ip addresses or in python platform independently and using only the standard library
|
if you do not want to use external packages and do not want to rely on outside internet servers this might help it is code sample that found on google code search and modified to return required information def getipaddresses from ctypes import structure windll sizeof from ctypes import pointer byref from ctypes import ulong uint ubyte char max adapter description length max adapter name length max adapter address length class ip addr string structure pass lp ip addr string pointer ip addr string ip addr string fields next lp ip addr string ipaddress char ipmask char context ulong class ip adapter info structure pass lp ip adapter info pointer ip adapter info ip adapter info fields next lp ip adapter info comboindex ulong adaptername char max adapter name length description char max adapter description length addresslength uint address ubyte max adapter address length index ulong type uint dhcpenabled uint currentipaddress lp ip addr string ipaddresslist ip addr string gatewaylist ip addr string dhcpserver ip addr string havewins uint primarywinsserver ip addr string secondarywinsserver ip addr string leaseobtained ulong leaseexpires ulong getadaptersinfo windll iphlpapi getadaptersinfo getadaptersinfo restype ulong getadaptersinfo argtypes lp ip adapter info pointer ulong adapterlist ip adapter info buflen ulong sizeof adapterlist rc getadaptersinfo byref adapterlist byref buflen if rc for in adapterlist adnode ipaddresslist while true ipaddr adnode ipaddress if ipaddr yield ipaddr adnode adnode next if not adnode break usage for addr in getipaddresses print addr as it relies on windll this will work only on windows
|
QA
|
removing subset of dict from within list this is really only easy to explain with an example so to remove the intersection of list from within dict usually do something like this exclusion have to build up new list or the iteration breaks toremove for var in iterkeys if var in exclusion toremove append var for var in toremove del var this might seem like an unusual example but it is surprising the number of times have had to do something like this doing this with sets would be much nicer but clearly want to retain the values for the dict this method is annoying because it requires two loops and an extra array is there cleaner and more efficient way of doing this
|
consider dict pop for key in exclusion pop key none the none keeps pop from raising an exception when key is not key
|
QA
|
removing subset of dict from within list this is really only easy to explain with an example so to remove the intersection of list from within dict usually do something like this exclusion have to build up new list or the iteration breaks toremove for var in iterkeys if var in exclusion toremove append var for var in toremove del var this might seem like an unusual example but it is surprising the number of times have had to do something like this doing this with sets would be much nicer but clearly want to retain the values for the dict this method is annoying because it requires two loops and an extra array is there cleaner and more efficient way of doing this
|
why not just use the keys method instead of iterkeys that way you can do it in one loop because it returns list not an iterator
|
QA
|
removing subset of dict from within list this is really only easy to explain with an example so to remove the intersection of list from within dict usually do something like this exclusion have to build up new list or the iteration breaks toremove for var in iterkeys if var in exclusion toremove append var for var in toremove del var this might seem like an unusual example but it is surprising the number of times have had to do something like this doing this with sets would be much nicer but clearly want to retain the values for the dict this method is annoying because it requires two loops and an extra array is there cleaner and more efficient way of doing this
|
dict key value for key value in iteritems if key not in exclusion
|
QA
|
calling python in php have python script recently wrote that call using the command line with some options now want very thin web interface to call this script locally on my mac do not want to go through the minor trouble of installing mod python or mod wsgi on my mac so was just going to do system or popen from php to call the python script any better ideas thanks in advance
|
depending on what you are doing system or popen may be perfect use system if the python script has no output or if you want the python script output to go directly to the browser use popen if you want to write data to the python script standard input or read data from the python script standard output in php popen will only let you read or write but not both if you want both check out proc open but with two way communication between programs you need to be careful to avoid deadlocks where each program is waiting for the other to do something if you want to pass user supplied data to the python script then the big thing to be careful about is command injection if you are not careful your user could send you data like evilcommand and make your program execute arbitrary commands against your will escapeshellarg and escapeshellcmd can help with this but personally like to remove everything that is not known good character using something like preg replace za str
|
QA
|
calling python in php have python script recently wrote that call using the command line with some options now want very thin web interface to call this script locally on my mac do not want to go through the minor trouble of installing mod python or mod wsgi on my mac so was just going to do system or popen from php to call the python script any better ideas thanks in advance
|
do this kind of thing all the time for quick and dirty scripts it is quite common to have cgi or php script that just uses system popen to call some external program just be extra careful if your web server is open to the internet at large be sure to sanitize your get post input in this case so as to not allow attackers to run arbitrary commands on your machine
|
QA
|
how would package and sell django app currently am hosting django app developed myself for my clients but am now starting to look at selling it to people for them to host themselves my question is this how can package up and sell django app while protecting its code from pirating or theft distributing bunch of py files does not sound like good idea as the people sell it to too could just make copies of them and pass them on think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same lamp setup
|
you will never be able to keep the source code from people who really want it it is best to come to grips with this fact now and save yourself the headache later
|
QA
|
removing subset of dict from within list this is really only easy to explain with an example so to remove the intersection of list from within dict usually do something like this exclusion have to build up new list or the iteration breaks toremove for var in iterkeys if var in exclusion toremove append var for var in toremove del var this might seem like an unusual example but it is surprising the number of times have had to do something like this doing this with sets would be much nicer but clearly want to retain the values for the dict this method is annoying because it requires two loops and an extra array is there cleaner and more efficient way of doing this
|
you could change your exclusion list to set then just use intersection to get the overlap exclusion set for key in exclusion intersection del key
|
QA
|
how do enter pound sterling character into the python interactive she will on mac os update thanks for the suggestions guys after further research ve reformulated the question here python editline on os sign seems to be bound to ed prev word on mac os can enter pound sterling sign into the python interactive she will mac os python jan european keyboard is shift when type press shift at an empty python she will nothing appears if ve already typed some characters then pressing shift will make the cursor position itself after the most recent space or the start of the line if there are no spaces left between the cursor and the start of the line in normal bash she will pressing shift types as expected any idea how can type literal in the python interactive she will
|
must be your setup can use the also european keyboard under idle or the python command line just fine python edit am using windows so mayby its problem with the how python works under the mac os
|
QA
|
how do enter pound sterling character into the python interactive she will on mac os update thanks for the suggestions guys after further research ve reformulated the question here python editline on os sign seems to be bound to ed prev word on mac os can enter pound sterling sign into the python interactive she will mac os python jan european keyboard is shift when type press shift at an empty python she will nothing appears if ve already typed some characters then pressing shift will make the cursor position itself after the most recent space or the start of the line if there are no spaces left between the cursor and the start of the line in normal bash she will pressing shift types as expected any idea how can type literal in the python interactive she will
|
in unicode it is with the unicode escape it would be you edit patrick mcelhaney said you might need to use
|
QA
|
how do enter pound sterling character into the python interactive she will on mac os update thanks for the suggestions guys after further research ve reformulated the question here python editline on os sign seems to be bound to ed prev word on mac os can enter pound sterling sign into the python interactive she will mac os python jan european keyboard is shift when type press shift at an empty python she will nothing appears if ve already typed some characters then pressing shift will make the cursor position itself after the most recent space or the start of the line if there are no spaces left between the cursor and the start of the line in normal bash she will pressing shift types as expected any idea how can type literal in the python interactive she will
|
would imagine that the terminal emulator is eating the keystroke as control code maybe see if it has config file you can mess around with
|
QA
|
how do enter pound sterling character into the python interactive she will on mac os update thanks for the suggestions guys after further research ve reformulated the question here python editline on os sign seems to be bound to ed prev word on mac os can enter pound sterling sign into the python interactive she will mac os python jan european keyboard is shift when type press shift at an empty python she will nothing appears if ve already typed some characters then pressing shift will make the cursor position itself after the most recent space or the start of the line if there are no spaces left between the cursor and the start of the line in normal bash she will pressing shift types as expected any idea how can type literal in the python interactive she will
|
not the best solution but you could type pound you then you have it in variable you can use in the rest of your session
|
QA
|
problem with python sockets how to get reliably posted data whatever the browser wrote small python ajax programs listed at the end with socket module to study the comet concept of asynchronous communications the idea is to allow browsers to send messages real time each others via my python program the trick is to let the get messages connexion opened waiting for message to answer back my problem is mainly on the reliability of what have via socket recv when post from firefox it is working well when post from chrome or ie the data get in python is empty does anybody know about this problem between browsers are some browsers injecting some eof or else characters killing the receiving of recv is there any solution known to this problem thanks for your help the server py in python import socket connected def inrequest text content if text get method get else method post len text while and text and text content text text text text index url text text index return method method url url content content mysocket socket socket socket af inet socket sock stream mysocket bind mysocket listen while true channel details mysocket accept data channel recv req inrequest data url req url if url client html or url clientie html open async url channel send http ok read close channel close elif messages in url if req method post target url if target in connected connected target send http ok req content print req content sent to target connected target close channel close elif req method get user url connected user channel print user is connected the client html in html javascript html head script var user function post el if window xmlhttprequest var text el value var req new xmlhttprequest el value var target document getelementbyid to value else if window activexobject var text el content var req new activexobject microsoft xmlhttp el content else return req open post messages target true req send text function get you if user user you value var req new xmlhttprequest req open get messages user true req onload function var message document createelement message innerhtml req responsetext document getelementbyid messages appendchild message get user req send null script head body span from span input id user input type button value sign in onclick get document getelementbyid user span to span input id to span span input id message input type button value post onclick post document getelementbyid message div id messages div body html
|
would recommend using js ajax library on the client side just to eliminate the possibility of cross browser issues with your code for the same reason would recommend using python http server library like simplehttpserver or something from twisted if the former does not allow low level control another idea use something like wireshark to check what is been sent by the browsers
|
QA
|
how do enter pound sterling character into the python interactive she will on mac os update thanks for the suggestions guys after further research ve reformulated the question here python editline on os sign seems to be bound to ed prev word on mac os can enter pound sterling sign into the python interactive she will mac os python jan european keyboard is shift when type press shift at an empty python she will nothing appears if ve already typed some characters then pressing shift will make the cursor position itself after the most recent space or the start of the line if there are no spaces left between the cursor and the start of the line in normal bash she will pressing shift types as expected any idea how can type literal in the python interactive she will
|
you pound sign if you are using ipython put execute pound you pound sign in your ipythonrc file in section python code to execute this way you will always have pound defined as the pound symbol in the interactive she will
|
QA
|
what is best way to remove duplicate lines matching regex from string using python this is pretty straight forward attempt have not been using python for too long seems to work but am sure have much to learn someone let me know if am way off here needs to find patterns write the first line which matches and then add summary message for remaining consecutive lines which match pattern and return modified string just to be clear regex dog would take cat dog my dog her dog mouse and return cat dog pattern dog repeats more times mouse usr bin env python import re import types def remove repeats string regex take string remove similar lines and replace with summary message regex accepts strings and tuples convert string to tuple if type regex types stringtype regex regex for in regex are for in string splitlines true if startswith pattern are are else if re search if line matches regex if if this is first match in set of lines add line to file are are elif else update the message string pattern repeats str more times else if write the message string if it has value are are are are if write the message if loop ended in pattern are are string are reset string to modified string return string
|
the rematcher function seems to do what you want def rematcher re str iterable matcher re compile re str in match for item in iterable if matcher match item if in match yield item in match else if in match yield repeats more times re str in match in match yield item if in match yield repeats more times re str in match import sys re for line in rematcher dog sys stdin sys stdout write line edit in your case the final string should be final string join rematcher dog your initial string split
|
QA
|
what is best way to remove duplicate lines matching regex from string using python this is pretty straight forward attempt have not been using python for too long seems to work but am sure have much to learn someone let me know if am way off here needs to find patterns write the first line which matches and then add summary message for remaining consecutive lines which match pattern and return modified string just to be clear regex dog would take cat dog my dog her dog mouse and return cat dog pattern dog repeats more times mouse usr bin env python import re import types def remove repeats string regex take string remove similar lines and replace with summary message regex accepts strings and tuples convert string to tuple if type regex types stringtype regex regex for in regex are for in string splitlines true if startswith pattern are are else if re search if line matches regex if if this is first match in set of lines add line to file are are elif else update the message string pattern repeats str more times else if write the message string if it has value are are are are if write the message if loop ended in pattern are are string are reset string to modified string return string
|
updated your code to be bit more effective usr bin env python import re import types def remove repeats string regex take string remove similar lines and replace with summary message regex accepts strings patterns or tuples of strings patterns convert string pattern to tuple if not hasattr regex iter regex regex ret last regex none count for line in string splitlines true if last regex previus line matched one of the regexes if re match last regex line this one does too count continue skip to next line elif count ret append pattern repeats more times last regex count count last regex none ret append line look for other patterns that could match for regex in regex if re match regex line found one last regex regex count break exit inner loop return join ret
|
QA
|
naming conventions in python library am implementing search algorithm let us call it myalg in python package since the algorithm is super duper complicated the package has to contain an auxiliary class for algorithm options currently am developing the entire package by myself and am not programmer however expect programmers to join the project later this would be my first project that will involve external programmers thus in order to make their lifes easier how should name this class options optionsmyalg myalgoptions or anything else what would you suggest me to read in this topic except for http www joelonsoftware com articles wrong html thank you yuri cross posted from here http discuss joelonsoftware com default asp design will update the answers in both places
|
suggest you read pep styleguide for python code
|
QA
|
naming conventions in python library am implementing search algorithm let us call it myalg in python package since the algorithm is super duper complicated the package has to contain an auxiliary class for algorithm options currently am developing the entire package by myself and am not programmer however expect programmers to join the project later this would be my first project that will involve external programmers thus in order to make their lifes easier how should name this class options optionsmyalg myalgoptions or anything else what would you suggest me to read in this topic except for http www joelonsoftware com articles wrong html thank you yuri cross posted from here http discuss joelonsoftware com default asp design will update the answers in both places
|
just naming it options should be fine the python standard library generally takes the philosophy that namespaces make it easy and manageable for different packages to have identically named things for example open is both builtin and function in the os module several different modules define an error exception class and so on this is why it is generally considered bad form to say from some module import since it makes it unclear to which open your code refers etc
|
QA
|
naming conventions in python library am implementing search algorithm let us call it myalg in python package since the algorithm is super duper complicated the package has to contain an auxiliary class for algorithm options currently am developing the entire package by myself and am not programmer however expect programmers to join the project later this would be my first project that will involve external programmers thus in order to make their lifes easier how should name this class options optionsmyalg myalgoptions or anything else what would you suggest me to read in this topic except for http www joelonsoftware com articles wrong html thank you yuri cross posted from here http discuss joelonsoftware com default asp design will update the answers in both places
|
if it all fits in one file name the class options then your users can write import myalg searchopts myalg options searchopts whatever mysearcher myalg searchalg searchopts mysearcher search where is waldo note the python style guide referenced in another answer suggests that packages should be named with all lowercase letters
|
QA
|
django how do create generic url routing to views have pretty standard django app and am wondering how to set the url routing so that do not have to explicitly map each url to view for example let us say that have the following views project links profile contact would rather not have my urlpatterns look like this project mysite app views project links mysite app views links profile mysite app views profile contact mysite app views contact and so on in pylons it would be as simple as map connect controller action id and it would automatically grab the right controller and function is there something similar in django
|
mods project links profile contact urlpatterns patterns mysite app views lower for in mods
|
QA
|
how do you get directory listing sorted by creation date in python what is the best way to get list of all files in directory sorted by date created modified using python on windows machine
|
have done this in the past for python script to determine the last updated files in directory import glob import os search dir mydir remove anything from the list that is not file directories symlinks thanks to sebastion for pointing out that the requirement was list of files presumably not including directories files filter os path isfile glob glob search dir files sort key lambda os path getmtime that should do what you are looking for based on file mtime edit note that you can also use os listdir in place of glob glob if desired the reason used glob in my original code was that was wanting to use glob to only search for files with particular set of file extensions which glob was better suited to to use listdir here is what it would look like import os search dir mydir os chdir search dir files filter os path isfile os listdir search dir files os path join search dir for in files add path to each file files sort key lambda os path getmtime
|
QA
|
how do you get directory listing sorted by creation date in python what is the best way to get list of all files in directory sorted by date created modified using python on windows machine
|
here is one liner import os import time from pprint import pprint pprint time ctime st ctime for in sorted fn os stat fn for fn in os listdir key lambda st ctime this calls os listdir to get list of the filenames then calls os stat for each one to get the creation time then sorts against the creation time note that this method only calls os stat once for each file which will be more efficient than calling it for each comparison in sort
|
QA
|
how do you get directory listing sorted by creation date in python what is the best way to get list of all files in directory sorted by date created modified using python on windows machine
|
here is my version def getfiles dirpath for in os listdir dirpath if os path isfile os path join dirpath sort key lambda os path getmtime os path join dirpath return first we build list of the file names isfile is used to skip directories it can be omitted if directories should be included then we sort the list in place using the modify date as the key
|
QA
|
python how do convert an os level handle to an open file to file object tempfile mkstemp returns tuple containing an os level handle to an open file as would be returned by os open and the absolute pathname of that file in that order how do convert that os level handle to file object the documentation for os open states to wrap file descriptor in file object use fdopen so tried import tempfile tup tempfile mkstemp import os os fdopen tup write foo traceback most recent call last file stdin line in ioerror errno bad file descriptor
|
you can use os write tup foo to write to the handle if you want to open the handle for writing you need to add the mode os fdopen tup write foo
|
QA
|
django how do create generic url routing to views have pretty standard django app and am wondering how to set the url routing so that do not have to explicitly map each url to view for example let us say that have the following views project links profile contact would rather not have my urlpatterns look like this project mysite app views project links mysite app views links profile mysite app views profile contact mysite app views contact and so on in pylons it would be as simple as map connect controller action id and it would automatically grab the right controller and function is there something similar in django
|
unless you have really huge number of views writing them down explicitly is not too bad from style perspective you can shorten your example though by using the prefix argument of the patterns function urlpatterns patterns mysite app views project project links links profile profile contact contact
|
QA
|
python how do convert an os level handle to an open file to file object tempfile mkstemp returns tuple containing an os level handle to an open file as would be returned by os open and the absolute pathname of that file in that order how do convert that os level handle to file object the documentation for os open states to wrap file descriptor in file object use fdopen so tried import tempfile tup tempfile mkstemp import os os fdopen tup write foo traceback most recent call last file stdin line in ioerror errno bad file descriptor
|
you forgot to specify the open mode in fdopen the default is causing the write call to fail think mkstemp creates the file for reading only calling fdopen with probably reopens it for writing you can reopen the file created by mkstemp
|
QA
|
django how do create generic url routing to views have pretty standard django app and am wondering how to set the url routing so that do not have to explicitly map each url to view for example let us say that have the following views project links profile contact would rather not have my urlpatterns look like this project mysite app views project links mysite app views links profile mysite app views profile contact mysite app views contact and so on in pylons it would be as simple as map connect controller action id and it would automatically grab the right controller and function is there something similar in django
|
you might be able to use special view function along these lines def router request function module import module globals locals function lower try return dict function lower request except keyerror raise http and then urlconf like this function router module mysite app views this code is untested but the general idea should work even though you should remember explicit is better than implicit
|
QA
|
how do you get directory listing sorted by creation date in python what is the best way to get list of all files in directory sorted by date created modified using python on windows machine
|
sorted filter os path isfile os listdir key lambda os stat st mtime you could use os walk next instead of filtering with os path isfile but that leaves dead symlinks in the list and os stat will fail on them
|
QA
|
calling python in php have python script recently wrote that call using the command line with some options now want very thin web interface to call this script locally on my mac do not want to go through the minor trouble of installing mod python or mod wsgi on my mac so was just going to do system or popen from php to call the python script any better ideas thanks in advance
|
there is also php extension pip python in php which have never tried but had it bookmarked for just such an occasion
|
QA
|
python how do convert an os level handle to an open file to file object tempfile mkstemp returns tuple containing an os level handle to an open file as would be returned by os open and the absolute pathname of that file in that order how do convert that os level handle to file object the documentation for os open states to wrap file descriptor in file object use fdopen so tried import tempfile tup tempfile mkstemp import os os fdopen tup write foo traceback most recent call last file stdin line in ioerror errno bad file descriptor
|
what is your goal here is tempfile temporaryfile inappropriate for your purposes
|
QA
|
now that python is out what modules currently in the language should every programmer know about lot of useful features in python are somewhat hidden inside modules named tuples new in python for instance are found in the collections module the library documentation page will give you all the modules in the language but newcomers to python are likely to find themselves saying oh did not know could have done it this way using python unless the important features in the language are pointed out by the experienced developers am not specifically looking for new modules in python but modules that can be found in this latest release
|
may be pep and what is new in can provide elements of answer this last article explains the new features in python released on october
|
QA
|
now that python is out what modules currently in the language should every programmer know about lot of useful features in python are somewhat hidden inside modules named tuples new in python for instance are found in the collections module the library documentation page will give you all the modules in the language but newcomers to python are likely to find themselves saying oh did not know could have done it this way using python unless the important features in the language are pointed out by the experienced developers am not specifically looking for new modules in python but modules that can be found in this latest release
|
the most impressive new module is probably the multiprocessing module first because it let us you execute functions in new processes just as easily and with roughly the same api as you would with the threading module but more importantly because it introduces lot of great classes for communicating between processes such as queue class and lock class which are each used just like those objects would be in multithreaded code as well as some other classes for sharing memory between processes you can find the documentation at http docs python org library multiprocessing html
|
QA
|
now that python is out what modules currently in the language should every programmer know about lot of useful features in python are somewhat hidden inside modules named tuples new in python for instance are found in the collections module the library documentation page will give you all the modules in the language but newcomers to python are likely to find themselves saying oh did not know could have done it this way using python unless the important features in the language are pointed out by the experienced developers am not specifically looking for new modules in python but modules that can be found in this latest release
|
the new json module is real boon to web programmers it was known as simplejson before being merged into the standard library it is ridiculously easy to use json dumps obj encodes built in type python object to json string while json loads string decodes json string into python object really really handy
|
QA
|
detecting mouse clicks in windows using python how can detect mouse clicks regardless of the window the mouse is in perferabliy in python but if someone can explain it in any langauge might be able to figure it out found this on microsoft site http msdn microsoft com en us library ms vs aspx but do not see how can detect or pick up the notifications listed tried using pygame pygame mouse get pos function as follows import pygame pygame init while true print pygame mouse get pos this just returns am not familiar with pygame is something missing in anycase would prefer method without the need to install rd party module other than pywin http sourceforge net projects pywin
|
the only way to detect mouse events outside your program is to install windows hook using setwindowshookex the pyhook module encapsulates the nitty gritty details here is sample that will print the location of every mouse click import pyhook import pythoncom def onclick event print event position return true hm pyhook hookmanager hm subscribemouseallbuttonsdown onclick hm hookmouse pythoncom pumpmessages hm unhookmouse you can check the example py script that is installed with the module for more info about the event parameter pyhook might be tricky to use in pure python script because it requires an active message pump from the tutorial any application that wishes to receive notifications of global input events must have windows message pump the easiest way to get one of these is to use the pumpmessages method in the win extensions package for python when run this program just sits idle and waits for windows events if you are using gui toolkit wxpython this loop is unnecessary since the toolkit provides its own
|
QA
|
python how do write decorator that restores the cwd how do write decorator that restores the current working directory to what it was before the decorated function was called in other words if use the decorator on function that does an os chdir the cwd will not be changed after the function is called
|
def preserve cwd function def decorator args kwargs cwd os getcwd result function args kwargs os chdir cwd return result return decorator here is how it is used preserve cwd def test print was os getcwd os chdir print now os getcwd print os getcwd users dspitzer test was users dspitzer now print os getcwd users dspitzer
|
QA
|
python how do write decorator that restores the cwd how do write decorator that restores the current working directory to what it was before the decorated function was called in other words if use the decorator on function that does an os chdir the cwd will not be changed after the function is called
|
the answer for decorator has been given it works at the function definition stage as requested with python you also have an option to do that at the function call stage using context manager from future import with statement needed for python import contextlib os contextlib contextmanager def remember cwd curdir os getcwd try yield finally os chdir curdir which can be used if needed at the function call time as print getcwd before os getcwd with remember cwd walk around the filesystem print getcwd after os getcwd it is nice option to have edit added error handling as suggested by codeape since my answer has been voted up it is fair to offer complete answer all other issues aside
|
QA
|
how can compress folder and email the compressed file in python would like to compress folder and all its sub folders files and email the zip file as an attachment what would be the best way to achieve this with python
|
look at zipfile for compressing folder and it is subfolders look at smtplib for an email client
|
QA
|
how can compress folder and email the compressed file in python would like to compress folder and all its sub folders files and email the zip file as an attachment what would be the best way to achieve this with python
|
you can use zipfile that ships with python and here you can find an example of sending an email with attachments with the standard smtplib
|
QA
|
how can compress folder and email the compressed file in python would like to compress folder and all its sub folders files and email the zip file as an attachment what would be the best way to achieve this with python
|
you can use the zipfile module to compress the file using the zip standard the email module to create the email with the attachment and the smtplib module to send it all using only the standard library python batteries included if you do not feel like programming and would rather ask question on stackoverflow org instead or as suggested in the comments left off the homework tag well here it is import smtplib import zipfile import tempfile from email import encoders from email message import message from email mime base import mimebase from email mime multipart import mimemultipart def send file zipped the file recipients sender you you com zf tempfile temporaryfile prefix mail suffix zip zip zipfile zipfile zf zip write the file zip close zf seek create the message themsg mimemultipart themsg subject file the file themsg to join recipients themsg from sender themsg preamble am not using mime aware mail reader message mimebase application zip message set payload zf read encoders encode base message message add header content disposition attachment filename the file zip themsg attach message themsg themsg as string send the message smtp smtplib smtp smtp connect smtp sendmail sender recipients themsg smtp close with this function you can just do send file zipped result txt me me org you are welcome
|
QA
|
initializing cherrypy session early love cherrypy api for sessions except for one detail instead of saying cherrypy session spam would like to be able to just say session spam unfortunately cannot simply have global from cherrypy import session in one of my modules because the cherrypy session object is not created until the first time page request is made is there some way to get cherrypy to initialize its session object immediately instead of on the first page request have two ugly alternatives if the answer is no first can do something like this def import session global session while not hasattr cherrypy session sleep session cherrypy session thread target import session start this feels like big kludge but really hate writing cherrypy session spam every time so to me it is worth it my second solution is to do something like class sessionkludge def getitem self name return cherrypy session name def setitem self name val cherrypy session name val session sessionkludge but this feels like an even bigger kludge and would need to do more work to implement the other dictionary functions such as get so would definitely prefer simple way to initialize the object myself does anyone know how to do this
|
for cherrypy you would need to find the right subclass of session run its setup classmethod and then set cherrypy session to threadlocalproxy that all happens in cherrypy lib sessions init in the following chunks find the storage class and call setup first time only storage class storage type title session storage class globals storage class if not hasattr cherrypy session if hasattr storage class setup storage class setup kwargs create cherrypy session which will proxy to cherrypy serving session if not hasattr cherrypy session cherrypy session cherrypy threadlocalproxy session reducing replace filesession with the subclass you want filesession setup kwargs cherrypy session cherrypy threadlocalproxy session the kwargs consist of timeout clean freq and any subclass specific entries from tools sessions config
|
QA
|
animation in python am writing simulator in python and am curious about options and opinions regarding basic animations by animation am referring to rendering on the fly not displaying prerendered images am currently using matplotlib wxagg backend and it is possible that will be able to continue using it but suspect it will not be able to sufficiently scale in terms of performance or capabilities requirements are cross platform linux macos windows low complexity overhead plays well with wxpython at least will not step on each other toes unduly interactivity detect when objects are clicked on moused over etc note that high performance is not on the list but the ability to handle bitmap objects on the screen would be good your thoughts
|
am fan of pyglet which is completely self contained library for doing graphical work under win linux and os it has very low overhead and you can see this for yourself from the tutorial on the website it should play well with wxpython or at least seem to recall posts to the mailing list about wxpython and pyglet being used together it however does not offer selection of objects via mouse clicks this you will have to handle yourself generally speaking for application this is not too difficult to do mactorii is an os application of mine written in pure python pyglet and has some basic animation scrolling and click detection it does not use wxpython but perhaps it will give you an idea of what is involved note however mactorii is using the old pyglet api so the run loop have in there is obsolete will get around to updating it one day
|
QA
|
how to package twisted program with py exe tried to package twisted program with py exe but once run the exe file built got no module named resource error and found the py exe said the following modules appear to be missing fcntl openssl email generator email iterators email utils pkg resources pywintypes resource win api win con win event win file win pipe win process win security so how do solve this problem thanks
|
have seen this before py exe for some reason is not detecting that these modules are needed inside the zip archive and is leaving them out you can explicitly specify modules to include on the py exe command line python setup py py exe win com twisted web resource something like that read up on the options and experiment
|
QA
|
problem with python sockets how to get reliably posted data whatever the browser wrote small python ajax programs listed at the end with socket module to study the comet concept of asynchronous communications the idea is to allow browsers to send messages real time each others via my python program the trick is to let the get messages connexion opened waiting for message to answer back my problem is mainly on the reliability of what have via socket recv when post from firefox it is working well when post from chrome or ie the data get in python is empty does anybody know about this problem between browsers are some browsers injecting some eof or else characters killing the receiving of recv is there any solution known to this problem thanks for your help the server py in python import socket connected def inrequest text content if text get method get else method post len text while and text and text content text text text text index url text text index return method method url url content content mysocket socket socket socket af inet socket sock stream mysocket bind mysocket listen while true channel details mysocket accept data channel recv req inrequest data url req url if url client html or url clientie html open async url channel send http ok read close channel close elif messages in url if req method post target url if target in connected connected target send http ok req content print req content sent to target connected target close channel close elif req method get user url connected user channel print user is connected the client html in html javascript html head script var user function post el if window xmlhttprequest var text el value var req new xmlhttprequest el value var target document getelementbyid to value else if window activexobject var text el content var req new activexobject microsoft xmlhttp el content else return req open post messages target true req send text function get you if user user you value var req new xmlhttprequest req open get messages user true req onload function var message document createelement message innerhtml req responsetext document getelementbyid messages appendchild message get user req send null script head body span from span input id user input type button value sign in onclick get document getelementbyid user span to span input id to span span input id message input type button value post onclick post document getelementbyid message div id messages div body html
|
the problem you have is that your tcp socket handling is not reading as much as it should your http handling is not complete recommend the following lectures rfc the sockets networking api by stevens see the example below for working http server that can process posts index html head head body form action method post textarea name foo textarea button type submit post button form data posted div div body html bufsize import socket import re from urlparse import urlparse class headers object def init self headers self dict update headers def getitem self name return getattr self name def get self name default none return getattr self name default class request object header re re compile za re def init self sock header off data while header off data sock recv bufsize header off data find header string data header off self content data header off lines self header re findall header string self method path lines pop path protocol path split self headers headers name lower replace value for name value in lines if self method in post put content length int self headers get content length while len self content content length self content sock recv bufsize self query urlparse path acceptor socket socket socket af inet socket sock stream acceptor setsockopt socket sol socket socket so reuseaddr acceptor bind acceptor listen if name main while true sock info acceptor accept request request sock sock send http ok index request content sock close
|
QA
|
how do build and install python for mac os have been unable to build python for an intel mac os these are my steps downloaded python tgz from http filehost perforce com perforce tools and expanded it into python downloaded api tar from http filehost perforce com perforce bin macosx and expanded it into api placed api into python and edited setup cfg to set api api added the line extra link args framework carbon to setup py after elif unameout darwin unix macosx release platform self architecture unameout ran python setup py build and got python setup py build api release running build running build py running build ext building api extension gcc fno strict aliasing wno long double no cpp precomp mno fused madd dndebug wall wstrict prototypes did os macosx did rel did patch did api did did did api api include build toolchain mac python include python api cpp build temp darwin api dos macosx dos macosx dos macosxx dos macosx cc plus warning command line option wstrict prototypes is valid for objc but not for api cpp in function int adapter init adapter pyobject pyobject api cpp error py ssize was not declared in this scope api cpp error expected before pos api cpp error pos was not declared in this scope api cpp in function pyobject adapter run adapter pyobject api cpp error py ssize was not declared in this scope api cpp error expected before api cpp error was not declared in this scope error command gcc failed with exit status which gcc returns usr bin gcc and gcc returns using built in specs target apple darwin configured with var tmp gcc gcc src configure disable checking enable werror prefix usr mandir share man enable languages objc obj program transform name cg with gxx include dir include with slibdir usr lib build apple darwin with arch apple with tune generic host apple darwin target apple darwin thread model posix gcc version apple inc build python returns python
|
from http bugs mymediasystem org do details task id suggests that py ssize was added in python so it will not work without some modifications with python either install compile your own copy of python or work out how to change python or look for an alternative python perforce library
|
QA
|
python how do write decorator that restores the cwd how do write decorator that restores the current working directory to what it was before the decorated function was called in other words if use the decorator on function that does an os chdir the cwd will not be changed after the function is called
|
the given answers fail to take into account that the wrapped function may raise an exception in that case the directory will never be restored the code below adds exception handling to the previous answers as decorator def preserve cwd function functools wraps function def decorator args kwargs cwd os getcwd try return function args kwargs finally os chdir cwd return decorator and as context manager contextlib contextmanager def remember cwd curdir os getcwd try yield finally os chdir curdir
|
QA
|
how to generate all permutations of list in python how do you generate all the permutations of list in python independently of the type of elements in that list for example permutations permutations permutations permutations edit eliben pointed to solution that is similar to mine although simpler so am choosing it as the accepted answer although python has builtin solution in the itertools module import itertools itertools permutations
|
the following code with python and above only first import itertools import itertools permutation order matters print list itertools permutations combination order does not matter print list itertools combinations cartesian product with several iterables print list itertools product cartesian product with one iterable and itself print list itertools product repeat
|
QA
|
problem with python sockets how to get reliably posted data whatever the browser wrote small python ajax programs listed at the end with socket module to study the comet concept of asynchronous communications the idea is to allow browsers to send messages real time each others via my python program the trick is to let the get messages connexion opened waiting for message to answer back my problem is mainly on the reliability of what have via socket recv when post from firefox it is working well when post from chrome or ie the data get in python is empty does anybody know about this problem between browsers are some browsers injecting some eof or else characters killing the receiving of recv is there any solution known to this problem thanks for your help the server py in python import socket connected def inrequest text content if text get method get else method post len text while and text and text content text text text text index url text text index return method method url url content content mysocket socket socket socket af inet socket sock stream mysocket bind mysocket listen while true channel details mysocket accept data channel recv req inrequest data url req url if url client html or url clientie html open async url channel send http ok read close channel close elif messages in url if req method post target url if target in connected connected target send http ok req content print req content sent to target connected target close channel close elif req method get user url connected user channel print user is connected the client html in html javascript html head script var user function post el if window xmlhttprequest var text el value var req new xmlhttprequest el value var target document getelementbyid to value else if window activexobject var text el content var req new activexobject microsoft xmlhttp el content else return req open post messages target true req send text function get you if user user you value var req new xmlhttprequest req open get messages user true req onload function var message document createelement message innerhtml req responsetext document getelementbyid messages appendchild message get user req send null script head body span from span input id user input type button value sign in onclick get document getelementbyid user span to span input id to span span input id message input type button value post onclick post document getelementbyid message div id messages div body html
|
thank you very much florian your code is working reuse the template and complete the main with my comet mecanism and it is working much better chrome and firefox are working perfectly well ie has still problem with the long get system when it received the answer to the get it does not stop to re executing the loop to print the messages investigating right now the question here is my updated code for very basic jquery python cross browser system the python program based on florian code bufsize import socket import re from urlparse import urlparse connected class headers object def init self headers self dict update headers def getitem self name return getattr self name def get self name default none return getattr self name default class request object header re re compile za re def init self sock header off data while header off data sock recv bufsize header off data find header string data header off self content data header off furl header string header string index self url furl furl index lines self header re findall header string self method path lines pop path protocol path split self headers headers name lower replace value for name value in lines if self method in post put content length int self headers get content length while len self content content length self content sock recv bufsize self query urlparse path acceptor socket socket socket af inet socket sock stream acceptor setsockopt socket sol socket socket so reuseaddr acceptor bind acceptor listen if name main while true sock info acceptor accept request request sock request method you request url if get and you client html or you jquery js open async you sock send http ok read close sock close elif messages in you if post target you if target in connected connected target send http ok request content connected target close sock close elif get user you connected user sock print user is connected and the html with jquery compacted html head style input width px span font size px button font size px style script type text javascript src jquery js script script var user function post el post messages to val message val function get you if user user you value get messages user function data data appendto messages get user script head body span from span input id user button onclick get document getelementbyid user log button span to span input id to span span input id message button onclick post post button div id messages div body html
|
QA
|
how do write to log from mod python under apache seem to only be able to write to the apache error log via stderr anyone know of more structured logging architecture that could use from my python web project like commons
|
have used the builtin python logging module in non web projects in the past with success it should work in web hosted environment as well
|
QA
|
usb driver development on mac using python would like to write driver to talk to my suunto watch in python on mac my day job is doing basic web work in so my familiarity with python and developing on mac is limited can you suggest how one would start doing driver development in general and then more specifically on mac how to easily see what data is being transmitted to the device have python macports up and running
|
if the watch supports standard usb device class specification such as hid or serial communication there might already be macintosh driver for it built into the os otherwise you are going to have to get information about the vendor commands used to communicate with it from one of three sources the manufacturer reverse engineering the protocol used by the windows driver or from others who have already reverse engineered the protocol in order to support the device on linux or bsd usb is packet based bus and it is very important to understand the various transaction types reading the usb specification is good place to start you can see what data is being transmitted to the device using usb bus analyzer which is an expensive proposition for hobbyist but is well within the reach of most businesses doing usb development for example the catalyst conquest is another established manufacturer is lecroy formerly catc there are also software usb analyzers that hook into the os usb stack but they do not show all of the traffic on the bus and may not be as reliable am not mac expert so take this paragraph with grain of salt apple has driver development kit called the kit which apparently requires you to write your driver in unless they also have some sort of user mode driver framework if you are writing it in python it will probably be more like python library that interfaces to someone else apple generic usb driver
|
QA
|
django signals vs overriding save method am having trouble wrapping my head around this right now have some models that looks kind of like this def review models model fields overall score models floatfield blank true def score models model review models foreignkey review question models textfield grade models integerfield review is has several scores the overall score is the average of the scores when review or score is saved need to recalculate the overall score average right now am using overridden save method would there be any benefits to using django signal dispatcher
|
if you will use signals you would be able to update review score each time related score model gets saved but if do not need such functionality do not see any reason to put this into signal that is pretty model related stuff
|
QA
|
what is the best way to duplicate fork in windows how do implement some logic that will allow me to reproduce on windows the functionality that have on linux with the fork system call using python am specifically trying to execute method on the sapi com component while continuing the other logic in the main thread without blocking or waiting
|
fork has in fact been duplicated in windows under cygwin but it is pretty hairy the fork call in cygwin is particularly interesting because it does not map well on top of the win api this makes it very difficult to implement correctly see the the cygwin user guide for description of this hack
|
QA
|
usb driver development on mac using python would like to write driver to talk to my suunto watch in python on mac my day job is doing basic web work in so my familiarity with python and developing on mac is limited can you suggest how one would start doing driver development in general and then more specifically on mac how to easily see what data is being transmitted to the device have python macports up and running
|
the mac already has the underlying infrastructure to support usb so you will need python library that can take advantage of it for any python project that needs serial support whether it is usb rs or gpib would recommend the pyvisa library at sourceforge see http pyvisa sourceforge net if your device does not have visa driver you will have to deal with the usb system directly you can use another library on sourceforge for that http pyusb berlios de
|
QA
|
django signals vs overriding save method am having trouble wrapping my head around this right now have some models that looks kind of like this def review models model fields overall score models floatfield blank true def score models model review models foreignkey review question models textfield grade models integerfield review is has several scores the overall score is the average of the scores when review or score is saved need to recalculate the overall score average right now am using overridden save method would there be any benefits to using django signal dispatcher
|
it is kind sort of denormalisation look at this pretty solution in place composition field definition
|
QA
|
how do write to log from mod python under apache seem to only be able to write to the apache error log via stderr anyone know of more structured logging architecture that could use from my python web project like commons
|
there is not any built in support for mod python logging to apache currently if you really want to work within the apache logs you can check out this thread make sure you get the second version of the posted code rather than the first http www dojoforum com node http www modpython org pipermail mod python october html if you are just looking to use more structured logging system the python standard logging module referred to by blair is very feature complete aside from the python org docs blair linked here is more in depth look at the module features from onlamp http www onlamp com pub python logging html and for quickie example usage http hackmap blogspot com note to self using python logging html
|
QA
|
iron python beautiful soup win app does beautiful soup work with iron python if so with which version of iron python how easy is it to distribute windows desktop app on net using iron python mostly calling some python code for parsing html
|
was asking myself this same question and after struggling to follow advice here and elsewhere to get ironpython and beautifulsoup to play nicely with my existing code decided to go looking for an alternative native net solution beautifulsoup is wonderful bit of code and at first it did not look like there was anything comparable available for net but then found the html agility pack and if anything think have actually gained some maintainability over beautifulsoup it takes clean or crufty html and produces elegant xml dom from it that can be queried via xpath with couple lines of code you can even get back raw xdocument and then craft your queries in linq to xml honestly if web scraping is your goal this is about the cleanest solution you are likely to find edit here is simple read not robust at all example that parses out the us house of representatives holiday schedule using system using system collections generic using htmlagilitypack namespace govparsingtest class program static void main string args htmlweb hw new htmlweb string url http www house gov house house calendar shtml htmldocument doc hw load url htmlnode docnode doc documentnode htmlnode div docnode selectsinglenode div id primary htmlnodecollection tablerows div selectnodes tr foreach htmlnode row in tablerows htmlnodecollection cells row selectnodes td htmlnode datenode cells htmlnode eventnode cells while eventnode haschildnodes eventnode eventnode firstchild console writeline datenode innertext console writeline eventnode innertext console writeline console writeline div innerhtml console readkey
|
QA
|
unix she will written in reasonable language has anyone ever heard of unix she will written in reasonable language like python
|
well there is emacs which is arguably she will written in lisp seriously though are you looking for reimplementation of an existing she will design in different language such as python or are you looking for new implementation of she will language that looks similar to your language of choice
|
QA
|
unix she will written in reasonable language has anyone ever heard of unix she will written in reasonable language like python
|
ipython python and rush ruby are shells that are designed for more advanced languages there is also hotwire which is sort of weird integrated she will terminal emulator
|
QA
|
sorting music so over the years have bought music off itunes urge and rhapsody and all these files are lying mixed with my non drm mp files that have ripped off my cds now some of these files have licenses that have expired and some of them have valid licenses want to sort my music by various drm license restrictions that they have on them this will make it easier for my to delete the music that do not have subscription to and all know which files can carry on which music player does anyone know if this is possible in net perl python are there any libraries available that will help me do this
|
do all the files have different extensions if so this might work wrote it all off the top of my head so its not tested import os music dir home johnbloggs music note the forward slashes and the trailing slash output dir home johnbloggs sorted music for file in os listdir music dir if file find mp if os path exists output dir mp os system cp music dir file output dir mp elif file find wma if os path exists output dir wma os system cp music dir file output dir wma etc this is written with linux in mind if you are looking to actually read the license type from inside the file that will be considerably more difficult
|
QA
|
unix she will written in reasonable language has anyone ever heard of unix she will written in reasonable language like python
|
tclsh is pretty nice assuming you like tcl of course
|
QA
|
unix she will written in reasonable language has anyone ever heard of unix she will written in reasonable language like python
|
eshell is bash like she will in emacs lisp ipython can be used as system she will though the syntax is bit weird supporting all of python plus basic sh constructs fish has core written in but much of its functionality is implemented in itself unlike many rare shells it can be used as your login she will hotwire deserves another mention its basic design appears to be powershell in python but it also does some clever things with ui the last release was in zoidberg is written in perl and uses perl syntax nice looking project shame it seems to have stalled scsh would be pain to use as login she will an example command from the docs run strings find name print but it looks like good perl in scheme
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.