prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
capture the contents of regex and delete them efficiently situation text string regex that matches part of the string this might be expensive to calculate want to both delete the matches from the text and see what they actually contain currently do this like import re ab re re compile ab text abcdedfe falijbijie bbbb laifsjelifjl ab re findall text ab re sub text cdedfe flijijie lifsjelifjl this runs the regex twice near as can tell is there technique to do it all on pass perhaps using re split it seems like with split based solutions would need to do the regex at least twice as well
you could use split with capturing parantheses if you do then the text of all groups in the pattern are also returned as part of the resulting list from python doc so the code would be import re ab re re compile ab text abcdedfe falijbijie bbbb laifsjelifjl matches ab re split text matches cdedfe lij ijie ifsjelifjl now extract the matches rmatches remaining for in range len matches rmatches append matches rmatches for in range len matches remaining append matches remainingtext join remaining remainingtext cdedfe flijijie lifsjelifjl
QA
capture the contents of regex and delete them efficiently situation text string regex that matches part of the string this might be expensive to calculate want to both delete the matches from the text and see what they actually contain currently do this like import re ab re re compile ab text abcdedfe falijbijie bbbb laifsjelifjl ab re findall text ab re sub text cdedfe flijijie lifsjelifjl this runs the regex twice near as can tell is there technique to do it all on pass perhaps using re split it seems like with split based solutions would need to do the regex at least twice as well
import re are re compile ab text abcdedfe falijbijie bbbb laifsjelifjl matches replaced pos for in finditer text matches append group replaced append text pos start pos end replaced append text pos print matches print join replaced outputs cdedfe flijijie lifsjelifjl
QA
is there function in python to print all the current properties and values of an object so what am looking for here is something like php print function this is so can debug my scripts by seeing what is the state of the object in question
in most cases using dict or dir will get you the info you are wanting if you should happen to need more details the standard library includes the inspect module which allows you to get some impressive amount of detail some of the real nuggests of info include names of function and method parameters class hierarchies source code of the implementation of functions class objects local variables out of frame object if you are just looking for what attribute values does my object have then dir and dict are probably sufficient if you are really looking to dig into the current state of arbitrary objects keeping in mind that in python almost everything is an object then inspect is worthy of consideration
QA
capture the contents of regex and delete them efficiently situation text string regex that matches part of the string this might be expensive to calculate want to both delete the matches from the text and see what they actually contain currently do this like import re ab re re compile ab text abcdedfe falijbijie bbbb laifsjelifjl ab re findall text ab re sub text cdedfe flijijie lifsjelifjl this runs the regex twice near as can tell is there technique to do it all on pass perhaps using re split it seems like with split based solutions would need to do the regex at least twice as well
my revised answer using re split which does things in one regex pass import re text abcdedfe falijbijie bbbb laifsjelifjl ab re re compile ab tokens ab re split text non matches tokens matches tokens edit here is complete function version def split matches text compiled re given compiled re split text into matching and nonmatching sections returns two lists tokens compiled re split text matches tokens non matches tokens return matches non matches nm split matches text ab re join nm equivalent to ab re sub text
QA
capture the contents of regex and delete them efficiently situation text string regex that matches part of the string this might be expensive to calculate want to both delete the matches from the text and see what they actually contain currently do this like import re ab re re compile ab text abcdedfe falijbijie bbbb laifsjelifjl ab re findall text ab re sub text cdedfe flijijie lifsjelifjl this runs the regex twice near as can tell is there technique to do it all on pass perhaps using re split it seems like with split based solutions would need to do the regex at least twice as well
what about this import re text abcdedfe falijbijie bbbb laifsjelifjl matches ab re re compile ab def verbosetest matches append group return textwithoutmatches ab re sub verbosetest text print matches print textwithoutmatches cdedfe flijijie lifsjelifjl the repl argument of the re sub function can be function so you can report or save the matches from there and whatever the function returns is what sub will substitute the function could easily be modified to do lot more too check out the re module documentation on docs python org for more information on what else is possible
QA
is it possible to compile python natively beyond pyc byte code wonder if it is possible to create an executable module from python script need to have the most performance and the flexibility of python script without needing to run in the python environment would use this code to load on demand user modules to customize my application
you can use something like py exe to compile your python script into an exe or freeze for linux binary see http stackoverflow com questions an executable python app
QA
is it possible to compile python natively beyond pyc byte code wonder if it is possible to create an executable module from python script need to have the most performance and the flexibility of python script without needing to run in the python environment would use this code to load on demand user modules to customize my application
there is pyrex that compiles python like source to python extension modules rpython which allows you to compile python with some restrictions to various backends like llvm net etc there is also she would skin which translates python to but cannot say if it is any good pypy implements jit compiler which attempts to optimize runtime by translating pieces of what is running at runtime to machine code if you write for the pypy interpreter that might be feasible path the same author that is working on jit in pypy wrote psyco previously which optimizes python in the cpython interpreter
QA
sometimes cannot delete an oracle database row using django have unit test which contains the following line of code site objects get name unittest delete and this has worked just fine until now however that statement is currently hanging it will sit there forever trying to execute the delete if just say print site objects get name unittest then it works so know that it can retrieve the site no other program is connected to oracle so it is not like there are two developers stepping on each other somehow assume that some sort of table lock has not been released so short of shutting down the oracle database and bringing it back up how do release that lock or whatever is blocking me would like to not resort to database shutdown because in the future that may be disruptive to some of the other developers edit justin suggested that look at the dba blockers and dba waiters tables unfortunately do not understand these tables at all and am not sure what am looking for so here is the information that seemed relevant to me the dba waiters table has entries with lock type dml the dba blockers table has entries whose session ids all correspond to the username used by our application code since this needs to get resolved am going to just restart the web server but would still appreciate any suggestions about what to do if this problem repeats itself am real novice when it comes to oracle administration and have mostly just used mysql in the past so am definitely out of my element edit it turns out that despite what thought another programmer was indeed accessing the database at the same time as me so what is the best way to detect this in the future perhaps should have shut down my program and then queried the dba waiters and dba blockers tables to make sure they were empty
from separate session can you query the dba blockers and dba waiters data dictionary tables and post the results that will tell you if your session is getting blocked by lock held by some other session as well as what other session is holding the lock
QA
starting new database driven python web application would you use javascript widget framework if so which framework am starting new web application project want to use python as am using it at my bread and butter job however do not want to reinvent the wheel some things have thought about ajax would be nice if it not too much of hazzle it is best if the licensing allows commercialization but is not crucial at this point it could also be funny to try out the google app engine if the tools will let me should be using javascript ui framework or should go for standard html forms which framework would you recommend
heartily suggest django prototype think they cover most of the bases you are looking at and they are very straight forward to get started with also you could use them on the gae if that is the route you decide to take although you should keep in mind that the gae does not support cron jobs which can limit your functionality
QA
starting new database driven python web application would you use javascript widget framework if so which framework am starting new web application project want to use python as am using it at my bread and butter job however do not want to reinvent the wheel some things have thought about ajax would be nice if it not too much of hazzle it is best if the licensing allows commercialization but is not crucial at this point it could also be funny to try out the google app engine if the tools will let me should be using javascript ui framework or should go for standard html forms which framework would you recommend
would take look at web py it is full stack framework that requires no configuration and is easy to try out everything can be driven via web interface if you choose have dabbled with other frameworks and it is by far the easiest to setup and includes lots of helpful things for free the documentation is good and there is howto for getting it to work under google app engine it comes with libraries and howto for ajax as far as remember the licence does not restrict using it in commercial applications
QA
what would you recommend for high traffic ajax intensive website for website like reddit with lots of up down votes and lots of comments per topic what should go with lighttpd php or lighttpd cherrypy genshi sqlalchemy and for database what would scale better be fastest mysql or or postgresql
on the db question would say postgresql scales better and has better data integrity than mysql for small site mysql might be faster but from what have heard it slows significantly as the size of the database grows note have never used mysql for large database so you should probably get second opinion about its scalability but postgresql definitely scales well and would be good choice for high traffic site
QA
starting new database driven python web application would you use javascript widget framework if so which framework am starting new web application project want to use python as am using it at my bread and butter job however do not want to reinvent the wheel some things have thought about ajax would be nice if it not too much of hazzle it is best if the licensing allows commercialization but is not crucial at this point it could also be funny to try out the google app engine if the tools will let me should be using javascript ui framework or should go for standard html forms which framework would you recommend
take look at extjs it is got the best widget library out there they offer commercial license and an open source license there are several python developers in the community and there is some integration with google apis
QA
starting new database driven python web application would you use javascript widget framework if so which framework am starting new web application project want to use python as am using it at my bread and butter job however do not want to reinvent the wheel some things have thought about ajax would be nice if it not too much of hazzle it is best if the licensing allows commercialization but is not crucial at this point it could also be funny to try out the google app engine if the tools will let me should be using javascript ui framework or should go for standard html forms which framework would you recommend
jquery though its ui components are perhaps not up to the very best but lots of work appears to be done in that area jquery itself seems to be on track to become the de facto js standard library it is both mit or gpl licensed so commercial use is ok and costless
QA
how can check the syntax of python code in emacs without actually executing it python idle has check module alt to check the syntax which can be called without needing to run the code is there an equivalent way to do this in emacs instead of running and executing the code
you can use pylint for such things and there seems to be way to integrate it into emacs but have never done the latter am vim user
QA
any good team chat websites are there any good team chat websites preferably in python ideally with cherrypy or trac this is similar to http stackoverflow com questions what is good freeware collaborative ie multiuser instant messenger but few primary differences very much want to host the server do not care if smileys are included or not in the client would like two options for the users ability to host private irc like chat on my trac page or link to such page allow remote clients to also interact
campfire from signals the rails guys edit it does not meet your requirements but it has some great features
QA
how do execute program from python os system fails due to spaces in path have python script that needs to execute an external program but for some reason fails if have the following script import os os system temp notepad exe raw input then it fails with the following error temp is not recognized as an internal or external command operable program or batch file if escape the program with quotes import os os system temp notepad exe raw input then it works however if add parameter it stops working again import os os system temp notepad exe test txt raw input what is the right way to execute program and wait for it to complete do not need to read output from it as it is visual program that does job and then just exits but need to wait for it to complete also note moving the program to non spaced path is not an option either edit this does not work either import os os system temp notepad exe raw input note the swapped single double quotes with or without parameter to notepad here it fails with the error message the filename directory name or volume label syntax is incorrect
here is different way of doing it if you are using windows the following acts like double clicking the file in explorer or giving the file name as an argument to the dos start command the file is opened with whatever application if any its extension is associated filepath textfile txt import os os startfile filepath example import os os startfile textfile txt this will open textfile txt with notepad if notepad is associted with txt files
QA
how do get python markdown to additionally urlify links when formatting plain text markdown is great tool for formatting plain text into pretty html but it does not turn plain text links into urls automatically like this one http www google com how do get markdown to add tags to urls when format block of text
was using the django framework which has filter called urlize which does exactly what wanted however it only works on plain text so could not pass is through the output of markdown followed this guide to create custom filter called urlify which works on html and passed the text through this filter div class news post autoescape off post content markdown urlify endautoescape div the urlify py filter from django import template import re register template library urlfinder re compile news telnet nttp file http ftp https www ftp za za za register filter urlify def urlify value return urlfinder sub href value
QA
how can check the syntax of python code in emacs without actually executing it python idle has check module alt to check the syntax which can be called without needing to run the code is there an equivalent way to do this in emacs instead of running and executing the code
you can use pyflakes together with flymake in order to get instant notification when your python code is valid and avoids few common pitfalls as well
QA
why do attribute references act like this with python inheritance the following seems strange basically the somedata attribute seems shared between all the classes that inherited from the base class class the base class somedata somedata was false in base false class subclassthing the base class def init self print self somedata first subclassthing was false in base false first somedata was false in base true second subclassthing was false in base true del first del second third subclassthing was false in base true defining self somedata in the init function is obviously the correct way to get around this so each class has it is own somedata dict but when is such behavior desirable
you are right somedata is shared between all instances of the class and it is subclasses because it is created at class definition time the lines somedata somedata was false in base false are executed when the class is defined when the interpreter encounters the class statement not when the instance is created think static initializer blocks in java if an attribute does not exist in class instance the class object is checked for the attribute at class definition time you can run arbritrary code like this import sys class test object if sys platform linux def hello self print hello linux else def hello self print hello linux on linux system test hello will print hello linux on all other systems the other string will be printed in constrast objects in init are created at instantiation time and belong to the instance only when they are assigned to self class test object def init self self inst var objects defined on class object rather than instance can be useful in many cases for instance you might want to cache instances of your class so that instances with the same member values can be shared assuming they are supposed to be immutable class someclass object instances def new cls try return cls insts except keyerror return cls insts setdefault object new cls mostly use data in class bodies in conjunction with metaclasses or generic factory methods
QA
why do attribute references act like this with python inheritance the following seems strange basically the somedata attribute seems shared between all the classes that inherited from the base class class the base class somedata somedata was false in base false class subclassthing the base class def init self print self somedata first subclassthing was false in base false first somedata was false in base true second subclassthing was false in base true del first del second third subclassthing was false in base true defining self somedata in the init function is obviously the correct way to get around this so each class has it is own somedata dict but when is such behavior desirable
note that part of the behavior you re seeing is due to somedata being dict as opposed to simple data type such as bool for instance see this different example which behaves differently although very similar class the base class somedata false class subclassthing the base class def init self print self somedata first subclassthing false first somedata true print first somedata true second subclassthing false print first somedata true del first del second third subclassthing false the reason this example behaves differently from the one given in the question is because here first somedata is being given new value the object true whereas in the first example the dict object referenced by first somedata and also by the other subclass instances is being modified see torsten marek comment to this answer for further clarification
QA
ruby to python bridge am interested in getting some python code talking to some ruby code on windows linux and possibly other platforms specificlly would like to access classes in ruby from python and call their methods access their data create new instances and so on an obvious way to do this is via something like xml rpc or maybe corba but would be interested in any other approaches what have other people done to get code from python and ruby communicating with one another either locally on the same system or remotely accross network thanks in advance
please be advised that do not speak from personal experience here but imagine jruby and jython the ruby and python implementations in the jvm would be able to to easily talk to each other as well as java code you may want to look into that
QA
why do attribute references act like this with python inheritance the following seems strange basically the somedata attribute seems shared between all the classes that inherited from the base class class the base class somedata somedata was false in base false class subclassthing the base class def init self print self somedata first subclassthing was false in base false first somedata was false in base true second subclassthing was false in base true del first del second third subclassthing was false in base true defining self somedata in the init function is obviously the correct way to get around this so each class has it is own somedata dict but when is such behavior desirable
think the easiest way to understand this so that you can predict behavior is to realize that your somedata is an attribute of the class and not the instance of that class if you define it that way there is really only one somedata at all times because in your example you did not assign to that name but used it to look up dict and then assign an item key value to it it is gotcha that is consequence of how the python interpreter works and can be confusing at first
QA
scrape dynamic website what is the best method to scrape dynamic website where most of the content is generated by what appears to be ajax requests have previous experience with mechanize beautifulsoup and python combo but am up for something new edit for more detail am trying to scrape the cnn primary database there is wealth of information there but there does not appear to be an api
this is difficult problem because you either have to reverse engineer the javascript on per site basis or implement javascript engine and run the scripts which has its own difficulties and pitfalls it is heavy weight solution but have seen people doing this with greasemonkey scripts allow firefox to render everything and run the javascript and then scrape the elements you can even initiate user actions on the page if needed
QA
ruby to python bridge am interested in getting some python code talking to some ruby code on windows linux and possibly other platforms specificlly would like to access classes in ruby from python and call their methods access their data create new instances and so on an obvious way to do this is via something like xml rpc or maybe corba but would be interested in any other approaches what have other people done to get code from python and ruby communicating with one another either locally on the same system or remotely accross network thanks in advance
well you could try named pipes or something similar but really think that xml rpc would be the most headache free way
QA
scrape dynamic website what is the best method to scrape dynamic website where most of the content is generated by what appears to be ajax requests have previous experience with mechanize beautifulsoup and python combo but am up for something new edit for more detail am trying to scrape the cnn primary database there is wealth of information there but there does not appear to be an api
adam davis advice is solid would additionally suggest that you try to reverse engineer what the javascript is doing and instead of trying to scrape the page you issue the http requests that the javascript is issuing and interpret the results yourself most likely in json format nice and easy to parse this strategy could be anything from trivial to total nightmare depending on the complexity of the javascript the best possibility of course would be to convince the website maintainers to implement developer friendly api all the cool kids are doing it these days of course they might not want their data scraped in an automated fashion in which case you can expect cat and mouse game of making their page increasingly difficult to scrape
QA
help with event in python entry widget am writing some code in python and am having trouble when trying to retrieve content of an entry widget the thing is want to limit the characters that can be typed so am trying to clear the entry widget when reach the specific number of characters in this case but it looks like always miss the last typed character added the lost character in print to show here is the sample code from tkinter import class sampleframe def init self master self frame frame master self frame pack def get frame self return self frame class sampleclass def init self master self alabel label master text alabel width self alabel pack side left self aentry entry master width self aentry bind key lambda event self callback event self aentry self aentry pack side left def callback self event widgetname self value widgetname get event char print self value if len self value widgetname delete root tk asampleframe sampleframe root asampleclass sampleclass asampleframe get frame root mainloop any help will be much appreciated thanks in advance
at first after you do the deletion the event goes on with its normal processing the character gets inserted you need to signal to tkinter that the event should be ignored so in your code above add the marked line if len self value widgetname delete return break add this line on the other hand why do you go through the lambda an event has widget attribute which you can use so you can change your code into self aentry bind key self callback here self aentry pack side left def callback self event self value event widget get event char here print self value if len self value event widget delete here return break all the changed lines are marked with here
QA
how can check the syntax of python code in emacs without actually executing it python idle has check module alt to check the syntax which can be called without needing to run the code is there an equivalent way to do this in emacs instead of running and executing the code
or from emacs or vim you could run python import where is the name of your file minus the py extension
QA
scrape dynamic website what is the best method to scrape dynamic website where most of the content is generated by what appears to be ajax requests have previous experience with mechanize beautifulsoup and python combo but am up for something new edit for more detail am trying to scrape the cnn primary database there is wealth of information there but there does not appear to be an api
this seems like it is pretty common problem wonder why someone has not anyone developed programmatic browser am envisioning firefox you can call from the command line with url as an argument and it will load the page run all of the initial page load js events and save the resulting file mean firefox and other browsers already do this why cannot we simply strip off the ui stuff
QA
receive socket size limits good am writing program in python that will act as server and accept data from client is it good idea to impose hard limit as to the amount of data if so why more info so certain chat programs limit the amount of text one can send per send per time user presses send so the question comes down to is there legit reason for this and if yes what is it
do not know what your actual application is however setting hard limit on the total amount of data that client can send could be useful in reducing your exposure to denial of service attacks client connects and sends mb of data which could load your application unacceptably but it really depends on what you application is are you after per line limit or total per connection limit or what
QA
scrape dynamic website what is the best method to scrape dynamic website where most of the content is generated by what appears to be ajax requests have previous experience with mechanize beautifulsoup and python combo but am up for something new edit for more detail am trying to scrape the cnn primary database there is wealth of information there but there does not appear to be an api
selenium ide tool for testing is something have used for lot of screen scraping there are few things it does not handle well javascript window alert and popup windows in general but it does its work on page by actually triggering the click events and typing into the text boxes because the ide portion runs in firefox you do not have to do all of the management of sessions etc as firefox takes care of it the ide records and plays tests back it also exports php java etc code to build compiled tests scrapers that are executed on the selenium server have done that for more than few of my selenium scripts which makes things like storing the scraped data in database much easier scripts are fairly simple to write and alter being made up of things like clickandwait submitbutton worth look given what you are describing
QA
how to update tix combobox text have tix combobox with an editable text field how do force the variable holding the value for the text to update let me give more concrete explanation have combo box and button when click the button it pops up message box with the value of the combo box let us say the combo box text field currently has the value thing if type new into the box and then click on the button with my mouse it will pops up the message thing if type new in the box and then tab focus away from the combo box and then click the button the pop up message says new ho do force the combo box to update it is value to new without requiring that tab away from the combo box have included sample code import tix import tkmessagebox class app object def init self window window winfo toplevel wm title test self window window self combo tix combobox window self combo insert tix end thing self combo insert tix end thing self combo entry state normal self combo editable true self combo pack button tix button window button text go button command self go button pack def go self tkmessagebox showinfo info self combo value if name main root tix tk app root root mainloop
note copy of moe answer that can be selected as chosen answer woo solved it on my own use self combo selection instead of self combo value
QA
python difference between class and instance attributes is there any meaningful distinction between class object foo some default value vs class object def init self foo self foo foo if you are creating lot of instances is there any difference in performance or space requirements for the two styles when you read the code do you consider the meaning of the two styles to be significantly different
beyond performance considerations there is significant semantic difference in the class attribute case there is just one object referred to in the instance attribute set at instantiation there can be multiple objects referred to for instance class foo foo append foo class def init self self foo foo append foo
QA
list of ip addresses hostnames from local network in python how can get list of the ip addresses or host names from local network easily in python it would be best if it was multi platform but it needs to work on mac os first then others follow edit by local mean all active addresses within local network such as xxx xxx so if the ip address of my computer within the local network is and have three other connected computers would want it to return the ip addresses and possibly their hostnames
one of the answers in this question might help you there seems to be platform agnostic version for python but have not tried it yet
QA
list of ip addresses hostnames from local network in python how can get list of the ip addresses or host names from local network easily in python it would be best if it was multi platform but it needs to work on mac os first then others follow edit by local mean all active addresses within local network such as xxx xxx so if the ip address of my computer within the local network is and have three other connected computers would want it to return the ip addresses and possibly their hostnames
if by local you mean on the same network segment then you have to perform the following steps determine your own ip address determine your own netmask determine the network range scan all the addresses except the lowest which is your network address and the highest which is your broadcast address use your dns reverse lookup to determine the hostname for ip addresses which respond to your scan or you can just let python execute nmap externally and pipe the results back into your program
QA
extracting parenthesized python expression from string have been wondering about how hard it would be to write some python code to search string for the index of substring of the form expr for example where expr is meant to be python expression or something resembling one given such thing one could easily imagine going on to check the expression syntax with compile evaluate it against particular scope with eval and perhaps even substitute the result into the original string people must do very similar things all the time could imagine solving such problem using third party parser generator oof or by hand coding some sort of state machine eek or perhaps by convincing python own parser to do the heavy lifting somehow hmm maybe there is third party templating library somewhere that can be made to do exactly this maybe restricting the syntax of expr is likely to be worthwhile compromise in terms of simplicity or execution time or cutting down on external dependencies for example maybe all really need is something that matches any expr that has balanced curly braces what is your sense update thanks very much for your responses so far looking back at what wrote yesterday am not sure was sufficiently clear about what am asking template substitution is indeed an interesting problem and probably much more useful to many more people than the expression extraction subproblem am wondering about but brought it up only as simple example of how the answer to my question might be useful in real life some other potential applications might include passing the extracted expressions to syntax highlighter passing the result to real python parser and looking at or monkeying with the parse tree or using the sequence of extracted expressions to build up larger python program perhaps in conjunction with some information taken from the surrounding text the expr syntax mentioned is also intended as an example and in fact wonder if should not have used expr as my example instead because it makes the potential drawbacks of the obvious approach along the lines of re finditer bit easier to see python expressions can and often do contain the or character it seems possible that handling any of those cases might be much more trouble than it is worth but am not convinced of that yet please feel free to try to make this case prior to posting this question spent quite bit of time looking at python template engines hoping that one might expose the sort of low level functionality am asking about namely something that can find expressions in variety of contexts and tell me where they are rather than being limited to finding expressions embedded using single hard coded syntax always evaluating them and always substituting the results back into the original string have not figured out how to use any of them to solve my problem yet but do very much appreciate the suggestions regarding more to look at cannot believe missed that wonderful list on the wiki the api documentation for these things tends to be pretty high level and am not too familiar with the internals of any of them so am sure could use help looking at those and figuring out how to get them to do this sort of thing thanks for your patience
think your best bet is to match for all curly braced entries and then check against python itself whether or not it is valid python for which compiler would be helpful
QA
hooking up gui interface with asynchronous ftp operation trying to implement progress dialog window for file uploads that look like cross between ie download dialog and firefox download dialog with python gui library on windows what asynchronous ftp libraries are there for python ideally should be able to do file upload resumes and track the progress of each parallel file uploads if am running each file upload in separate process each how would get the upload status and display it in progress bar dialog
ftplib is the standard ftp library built in to python in python it had callback parameter added to the method used for uploading that callback is function you provide to the library it is called once for every block that is completed your function can send message to the gui perhaps on different thread process using standard inter thread or inter process communications to tell it to update its progress bar reference
QA
python difference between class and instance attributes is there any meaningful distinction between class object foo some default value vs class object def init self foo self foo foo if you are creating lot of instances is there any difference in performance or space requirements for the two styles when you read the code do you consider the meaning of the two styles to be significantly different
just an elaboration on what alex coventry said another alex martelli addressed similar question on the comp lang python newsgroup years back he examines the semantic difference of what person intended vs what he got by using instance variables http groups google com group comp lang python message aff fae hl en
QA
extracting parenthesized python expression from string have been wondering about how hard it would be to write some python code to search string for the index of substring of the form expr for example where expr is meant to be python expression or something resembling one given such thing one could easily imagine going on to check the expression syntax with compile evaluate it against particular scope with eval and perhaps even substitute the result into the original string people must do very similar things all the time could imagine solving such problem using third party parser generator oof or by hand coding some sort of state machine eek or perhaps by convincing python own parser to do the heavy lifting somehow hmm maybe there is third party templating library somewhere that can be made to do exactly this maybe restricting the syntax of expr is likely to be worthwhile compromise in terms of simplicity or execution time or cutting down on external dependencies for example maybe all really need is something that matches any expr that has balanced curly braces what is your sense update thanks very much for your responses so far looking back at what wrote yesterday am not sure was sufficiently clear about what am asking template substitution is indeed an interesting problem and probably much more useful to many more people than the expression extraction subproblem am wondering about but brought it up only as simple example of how the answer to my question might be useful in real life some other potential applications might include passing the extracted expressions to syntax highlighter passing the result to real python parser and looking at or monkeying with the parse tree or using the sequence of extracted expressions to build up larger python program perhaps in conjunction with some information taken from the surrounding text the expr syntax mentioned is also intended as an example and in fact wonder if should not have used expr as my example instead because it makes the potential drawbacks of the obvious approach along the lines of re finditer bit easier to see python expressions can and often do contain the or character it seems possible that handling any of those cases might be much more trouble than it is worth but am not convinced of that yet please feel free to try to make this case prior to posting this question spent quite bit of time looking at python template engines hoping that one might expose the sort of low level functionality am asking about namely something that can find expressions in variety of contexts and tell me where they are rather than being limited to finding expressions embedded using single hard coded syntax always evaluating them and always substituting the results back into the original string have not figured out how to use any of them to solve my problem yet but do very much appreciate the suggestions regarding more to look at cannot believe missed that wonderful list on the wiki the api documentation for these things tends to be pretty high level and am not too familiar with the internals of any of them so am sure could use help looking at those and figuring out how to get them to do this sort of thing thanks for your patience
think what you are asking about is being able to insert python code into text files to be evaluated there are several modules that already exist to provide this kind of functionality you can check the python org templating wiki page for comprehensive list some google searching also turned up few other modules you might be interested in texttemplate part of py templates project template module if you are really looking just into writing this yourself for whatever reason you can also dig into this python cookbook solution yet another python templating utility yaptu templating copying an input file to output on the fly inserting python expressions and statements is frequent need and yaptu is small but complete python module for that expressions and statements are identified by arbitrary user chosen regular expressions edit just for the heck of it whipped up severely simplistic code sample for this am sure it has bugs but it illustrates simplified version of the concept at least usr bin env python import sys import re file sys argv handle open file fcontent handle read handle close for myexpr in re finditer fcontent re re text myexpr group try exec text except syntaxerror print error unable to compile expression text tested against the following text this is some random text with embedded python like print foo and some bogus python like any thing and multiline statement just for kicks def multiline stmt foo print foo multiline stmt ahem more text here output user host exec embedded python py test txt foo error unable to compile expression any thing ahem
QA
how can check the syntax of python code in emacs without actually executing it python idle has check module alt to check the syntax which can be called without needing to run the code is there an equivalent way to do this in emacs instead of running and executing the code
you can use pylint pychecker pyflakes etc from emacs compile command compile hint bind key say to recompile
QA
which python framework to use am looking for framework which is appropriate for beginners in python and web development already found out about django and web py think that one of the most important things for me is good documentation thanks for the help dan
have written web apps with raw wsgi perhaps rolling out my own library at some point do not just like about large frameworks and such learned to hate http while writing in raw wsgi you do not really like it after you realise how much stupid parsing and interpretation you need to upload file because of wsgi python has tons of frameworks of different qualities if you want to try my way would guess you would like to know werkzeug perhaps it provides some things when you do not yet know how to do them it only has perhaps too much of framework for me in the end very well written framework ought exceed what have written in wsgi though
QA
python difference between class and instance attributes is there any meaningful distinction between class object foo some default value vs class object def init self foo self foo foo if you are creating lot of instances is there any difference in performance or space requirements for the two styles when you read the code do you consider the meaning of the two styles to be significantly different
the difference is that the attribute on the class is shared by all instances the attribute on an instance is unique to that instance if coming from attributes on the class are more like static member variables
QA
are there any ide that support python syntax recently saw an announcement and article outlining the release of the first python release candidate was wondering whether there were any commercial free open source etc ide that support its syntax
can get pydev from http pydev sourceforge net its plugin for eclipse and is more than handy not to mention benefits of the old and trusted eclipse
QA
list of ip addresses hostnames from local network in python how can get list of the ip addresses or host names from local network easily in python it would be best if it was multi platform but it needs to work on mac os first then others follow edit by local mean all active addresses within local network such as xxx xxx so if the ip address of my computer within the local network is and have three other connected computers would want it to return the ip addresses and possibly their hostnames
if you know the names of your computers you can use import socket ip socket gethostbyname socket gethostname local ip adress of your computer ip socket gethostbyname name of your computer ip adress of remote computer otherwise you will have to scan for all the ip addresses that follow the same mask as your local computer ip as stated in another answer
QA
are there any ide that support python syntax recently saw an announcement and article outlining the release of the first python release candidate was wondering whether there were any commercial free open source etc ide that support its syntax
komodo beta was released in october and has initial support for python but do not think would be using it for production code yet given that python is still very early release candidate you may have some trouble finding mature support in ides
QA
hooking up gui interface with asynchronous ftp operation trying to implement progress dialog window for file uploads that look like cross between ie download dialog and firefox download dialog with python gui library on windows what asynchronous ftp libraries are there for python ideally should be able to do file upload resumes and track the progress of each parallel file uploads if am running each file upload in separate process each how would get the upload status and display it in progress bar dialog
if you want complete example of how to use threads and events to update your gui with long running tasks using wxpython have look at this page this tutorial is quite useful and helped me perform similar program than yours
QA
ruby to python bridge am interested in getting some python code talking to some ruby code on windows linux and possibly other platforms specificlly would like to access classes in ruby from python and call their methods access their data create new instances and so on an obvious way to do this is via something like xml rpc or maybe corba but would be interested in any other approaches what have other people done to get code from python and ruby communicating with one another either locally on the same system or remotely accross network thanks in advance
this is not what your after but worth read embed python interpreter in ruby this code pretty old http www goto info waseda ac jp fukusima ruby python doc index html or why rewriting bytecodes http github com why unholy tree master
QA
hooking up gui interface with asynchronous ftp operation trying to implement progress dialog window for file uploads that look like cross between ie download dialog and firefox download dialog with python gui library on windows what asynchronous ftp libraries are there for python ideally should be able to do file upload resumes and track the progress of each parallel file uploads if am running each file upload in separate process each how would get the upload status and display it in progress bar dialog
if you data transfer runs in separate thread from the gui you can use wx callafter whenever you have to update you progress bar from the data transfer thread first using callafter is mandatory as wxpython function cannot be called from child threads second this will decouple the execution of the data transfer from the gui in the main thread note that callafter only works for threads not for separate processes in that case using the multiprocessing package should help
QA
python module that implements ftps was wondering if anybody could point me towards free ftps module for python am complete newbie to python but this is something need for work project need an ftps client to connect to rd party ftps server thanks david
have not tried it myself yes just used google and followed some links but http www lag net paramiko seems to be the recommended solution from cursory glance it is an ssh implementation in pure python which allows tunneling for things like ftp update commenter pointed out that mixed up sftp and ftps sorry still suggest at least investigating paramiko briefly to see if it matches the requirements
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
other way would be creating your own template loader that loads templates specific to user agent this is pretty generic technique and can be use to dynamically determine what template has to be loaded depending on other factors too like requested language good companion to existing django machinery django book has section on this subject
QA
python module that implements ftps was wondering if anybody could point me towards free ftps module for python am complete newbie to python but this is something need for work project need an ftps client to connect to rd party ftps server thanks david
twisted seems to have some implementation of ftps ftp over ssl under the conch sub project am no twisted expert but glyph the twisted man himself is listed in this site maybe by following his answer to another question you can find more details good luck
QA
variables as parameters in field options want to create model that will set editable false on creation and editable true on editing item thought it should be something like this home models foreignkey team editable lambda self true if self id else false but it does not work maybe something with overriding the init can help me but do not sure what can do the trick know can check for self id in save method but is too late want this kind of logic in admin app when am filling the fields
add the following small extension of this code to your admin py from django import forms class readonlywidget forms widget def init self original value display value self original value original value self display value display value super readonlywidget self init def render self name value attrs none if self display value is not none return unicode self display value return unicode self original value def value from datadict self data files name return self original value class readonlyadminfields object def get form self request obj none form super readonlyadminfields self get form request obj fields getattr self readonly if obj is not none fields getattr self readonly on edit for field name in fields if field name in form base fields if hasattr obj get display field name display value getattr obj get display field name else display value none form base fields field name widget readonlywidget getattr obj field name display value form base fields field name required false return form you can then specify that certain fields should by readonly when the object is edited class personadmin readonlyadminfields admin modeladmin readonly on edit home admin site register person personadmin
QA
how to read and write multiple files want to write program for this in folder have number of files first read one file and perform some operation then store result in separate file then read nd file perform operation again and save result in new nd file do the same procedure for number of files the program reads all files one by one and stores results of each file separately please give examples how can do it
import sys argv is your commandline arguments argv is your program name so skip it for in sys argv print print out the filename we are currently processing input open output open out do some processing input close output close then call it like foo py bar txt baz txt
QA
how to read and write multiple files want to write program for this in folder have number of files first read one file and perform some operation then store result in separate file then read nd file perform operation again and save result in new nd file do the same procedure for number of files the program reads all files one by one and stores results of each file separately please give examples how can do it
you may find the fileinput module useful it is designed for exactly this problem
QA
python module that implements ftps was wondering if anybody could point me towards free ftps module for python am complete newbie to python but this is something need for work project need an ftps client to connect to rd party ftps server thanks david
believe you could use twisted to implement ftps by simply using its ftp implementation but changing the ftpclient connectfactory attribute to be function that does something with connectssl rather than connecttcp are you sure you want ftps though sftp is different better and much more popular protocol these days twisted contains an sftp implementation as well
QA
how to read and write multiple files want to write program for this in folder have number of files first read one file and perform some operation then store result in separate file then read nd file perform operation again and save result in new nd file do the same procedure for number of files the program reads all files one by one and stores results of each file separately please give examples how can do it
think what you miss is how to retrieve all the files in that directory to do so use the glob module here is an example which will duplicate all the files with extension txt to files with extension out import glob list of files glob glob txt create the list of file for file name in list of files fi open file name fo open file name replace txt out for line in fi fo write line fi close fo close
QA
how to read and write multiple files want to write program for this in folder have number of files first read one file and perform some operation then store result in separate file then read nd file perform operation again and save result in new nd file do the same procedure for number of files the program reads all files one by one and stores results of each file separately please give examples how can do it
combined answer incorporating directory or specific list of filenames arguments import sys import os path import glob def processfile filename filehandle open filename for line in filehandle do some processing pass filehandle close def outputresults filename output filemask out filehandle open filename output filemask do some processing filehandle write processed filehandle close def processfiles args input filemask log directory args if os path isdir directory print processing directory list of files glob glob directory input filemask else print processing list of files list of files sys argv for file name in list of files print file name processfile file name outputresults file name if name main if len sys argv processfiles sys argv else print usage message
QA
framework language for new web sites and know will get thousand depends on what you are trying to do answers but seriously there really is no solid information about this online yet here are my assumptions think they are similar for alot of people right now it is now october want to start writing an application for january am willing to use beta code and such but by january would like site that does not have strange problems with that said if language is simply slower than another do not care about those things as long as the issue is linear my main concern is developer productivity will be using linux apache mysql for the application want the power to do things like run scp and ftp client functions with stable libraries only picked those two because they are not web related but at the same time represent pretty common network protocols that any larger app might use technologies like openid and oauth will be used as well experienced web developers are readily available do not have to find people from financial companies and such whatever the choice is is common and will be around for while here is kicker would like to be able to use advanced presentation layer tools languages similar to haml sass definitively want to use jquery will be creating facebook app and at some point doing things like dealing with sms messages iphone apps etc at this point the choices for language are php cake symfony zend python django ruby merb am really between django and merb at this point mostly because everybody else seems to be going that way please do not put any technologies in here that are not made for mainstream know merb is untested mostly but their stated goal is solid platform and it has alot of momentum behind it so am confident that it is workable please do not answer with how great perl is or net for future references these choices were already made debian lenny for converting cpu cycles into something useful trac for project management gliffy for wireframes and such google docs apps for documentation hosted email etc amazon ec for hosting storage cheers adam
having built apps in django can attest to its utility if only all frameworks were as elegant yes spring am looking at you however in terms of betting the farm on django one thing you need to factor in is that python will be released shortly python is not backwards compatible and there is risk that it will fork the language and end up slowing momentum for all python projects while they deal with the fallout to be fair ruby is due soon too but do not think it will be as disruptive
QA
how to base encode pdf file in python how should base encode pdf file for transport over xml rpc in python
you can do it with the base library legacy interface
QA
how to base encode pdf file in python how should base encode pdf file for transport over xml rpc in python
actually after some more digging it looks like the xmlrpclib module may have the piece need with it is binary helper class binary obj xmlrpclib binary open foo pdf read here is an example from the trac xml rpc documentation import xmlrpclib server xmlrpclib serverproxy http athomas password localhost trunk login xmlrpc server wiki putattachment wikistart py xmlrpclib binary open py read
QA
how to base encode pdf file in python how should base encode pdf file for transport over xml rpc in python
looks like you might be able to use the binascii module binascii base data convert binary data to line of ascii characters in base coding the return value is the converted line including newline char the length of data should be at most to adhere to the base standard
QA
how to make apache mod python process collect its zombies apache unix dav mod python python configured one of apache processes spawns some long running python script asynchronously and apparently does not seem to collect its child process table entry after that long run in subprocess python script finishes defunct python process has been left ps ef grep httpd root oct usr sbin httpd qa oct usr sbin httpd ps ef grep python qa python defunct what is the way to make the apache process to collect its children is it possible to do the job via mod python request handler like pythoncleanuphandler for example thanks
file bug report edit am serious leaving zombies behind is bug and there is almost certainly nothing you can do from within python upgrade to the latest versions look for bug reports post on the mailing list switch to another product
QA
is it possible to compile python natively beyond pyc byte code wonder if it is possible to create an executable module from python script need to have the most performance and the flexibility of python script without needing to run in the python environment would use this code to load on demand user modules to customize my application
think you can use jython to compile python to java bytecode and then compile that with gcj
QA
are there any ide that support python syntax recently saw an announcement and article outlining the release of the first python release candidate was wondering whether there were any commercial free open source etc ide that support its syntax
python is just not that different from python in terms of syntax per se things that will actually need to be handled differently by the parser the only major change is in the replacement of the print statement with the print function most of the features of python can be easily probed via introspection online help method completion function signatures etc so there is no reason why any python ide will require major changes to work with python expect idle and spe and the other open source ides will be support it before the final release
QA
how to base encode pdf file in python how should base encode pdf file for transport over xml rpc in python
note this is community wiki owned copy of pat notz answer this answer can be selected as the chosen answer edit freely to improve pat notz says actually after some more digging it looks like the xmlrpclib module may have the piece need with its binary helper class binary obj xmlrpclib binary open foo pdf read here is an example from the trac xml rpc documentation import xmlrpclib server xmlrpclib serverproxy http athomas password localhost trunk login xmlrpc server wiki putattachment wikistart py xmlrpclib binary open py read
QA
extracting parenthesized python expression from string have been wondering about how hard it would be to write some python code to search string for the index of substring of the form expr for example where expr is meant to be python expression or something resembling one given such thing one could easily imagine going on to check the expression syntax with compile evaluate it against particular scope with eval and perhaps even substitute the result into the original string people must do very similar things all the time could imagine solving such problem using third party parser generator oof or by hand coding some sort of state machine eek or perhaps by convincing python own parser to do the heavy lifting somehow hmm maybe there is third party templating library somewhere that can be made to do exactly this maybe restricting the syntax of expr is likely to be worthwhile compromise in terms of simplicity or execution time or cutting down on external dependencies for example maybe all really need is something that matches any expr that has balanced curly braces what is your sense update thanks very much for your responses so far looking back at what wrote yesterday am not sure was sufficiently clear about what am asking template substitution is indeed an interesting problem and probably much more useful to many more people than the expression extraction subproblem am wondering about but brought it up only as simple example of how the answer to my question might be useful in real life some other potential applications might include passing the extracted expressions to syntax highlighter passing the result to real python parser and looking at or monkeying with the parse tree or using the sequence of extracted expressions to build up larger python program perhaps in conjunction with some information taken from the surrounding text the expr syntax mentioned is also intended as an example and in fact wonder if should not have used expr as my example instead because it makes the potential drawbacks of the obvious approach along the lines of re finditer bit easier to see python expressions can and often do contain the or character it seems possible that handling any of those cases might be much more trouble than it is worth but am not convinced of that yet please feel free to try to make this case prior to posting this question spent quite bit of time looking at python template engines hoping that one might expose the sort of low level functionality am asking about namely something that can find expressions in variety of contexts and tell me where they are rather than being limited to finding expressions embedded using single hard coded syntax always evaluating them and always substituting the results back into the original string have not figured out how to use any of them to solve my problem yet but do very much appreciate the suggestions regarding more to look at cannot believe missed that wonderful list on the wiki the api documentation for these things tends to be pretty high level and am not too familiar with the internals of any of them so am sure could use help looking at those and figuring out how to get them to do this sort of thing thanks for your patience
if you want to handle arbitrary expressions like spam spam you cannot get away without full blown parser
QA
can use python as bash replacement currently do my textfile manipulation through bunch of badly remembered awk sed bash and tiny bit of perl have seen mentioned few places that python is good for this kind of thing know little and would like to know more is python good choice for this and is there good book or guide to learning how to use python to replace she will scripting awk sed and friends
python would be perfectly fine for text file manipulation for learning check here
QA
why do receive an importerror when running one of the cherrypy tutorials have installed cherrypy here is what happens when try to run tutorial cd library python site packages cherrypy tutorial python tut files py traceback most recent call last file tut files py line in module from cherrypy lib import static importerror cannot import name static the previous line in the file import cherrypy passes without error so it appears that it can find cherrypy on the path what am missing
this works for me and am also using cherrypy so am not sure what to tell you look in your library python site packages cherrypy lib directory for file named static py if this file exists then am not sure what to tell you if it does not then something has happened to your cherrypy and would advise you to reinstall if it does then you should check the value of sys path to make sure it is detecting the right version of cherrypy you can also try running the python interpreter on the command line and then doing from cherrypy lib import static to see if you get the same result
QA
howto do python command line autocompletion but not only at the beginning of string python through it is readline bindings allows for great command line autocompletion as described in here but the completion only seems to work at the beginning of strings if you want to match the middle or end of string readline does not work would like to autocomplete strings in command line python program by matching what type with any of the strings in list of available strings good example of the type of autocompletion would like to have is the type that happens in gmail when you type in the to field if you type one of your contacts last name it will come up just as well as if you typed her first name some use of the up and down arrows or some other method to select from the matched strings may be needed and not needed in the case of readline and that is fine in my case my particular use case is command line program that sends emails specific code examples would be very helpful using terminal emulators like curses would be fine it only has to run on linux not mac or windows here is an example say have the following three strings in list paul eden paul domain com eden jones ejones domain com somebody else somebody domain com would like some code that will autocomplete the first two items in the list after type eden and then allow me to pick one of them all through the command line using the keyboard
am not sure understand the problem you could use readline clear history and readline add history to set up the completable strings you want then control to search backword in the history just as if you were at she will prompt for example usr bin env python import readline readline clear history readline add history foo readline add history bar while print raw input alternatively you could write your own completer version and bind the appropriate key to it this version uses caching in case your match list is huge usr bin env python import readline values paul eden paul domain com eden jones ejones domain com somebody else somebody domain com completions def completer text state try matches completions text except keyerror matches value for value in values if text upper in value upper completions text matches try return matches state except indexerror return none readline set completer completer readline parse and bind tab menu complete while raw input print said
QA
convert hex string to int in python how do convert hex string to an int in python may have it as xffff or just ffff
int hexstring does the trick and works with and without the prefix int int xa
QA
convert hex string to int in python how do convert hex string to an int in python may have it as xffff or just ffff
for any given string int
QA
convert hex string to int in python how do convert hex string to an int in python may have it as xffff or just ffff
without the prefix you need to specify the base explicitly otherwise there is no way to tell int deadbeef with the prefix python can distinguish hex and decimal automatically print int xdeadbeef print int you must specify as the base in order to invoke this prefix guessing behavior omitting the second parameter means to assume base see the comments for more details
QA
can use python as bash replacement currently do my textfile manipulation through bunch of badly remembered awk sed bash and tiny bit of perl have seen mentioned few places that python is good for this kind of thing know little and would like to know more is python good choice for this and is there good book or guide to learning how to use python to replace she will scripting awk sed and friends
suggest the awesome online book dive into python it is how learned the language originally beyone teaching you the basic structure of the language and whole lot of useful data structures it has good chapter on file handling and subsequent chapters on regular expressions and more
QA
can use python as bash replacement currently do my textfile manipulation through bunch of badly remembered awk sed bash and tiny bit of perl have seen mentioned few places that python is good for this kind of thing know little and would like to know more is python good choice for this and is there good book or guide to learning how to use python to replace she will scripting awk sed and friends
any she will has several sets of features the essential linux unix commands all of these are available through the subprocess library this is not always the best first choice for doing all external commands look also at shutil for some commands that are separate linux commands but you could probably implement directly in your python scripts another huge batch of linux commands are in the os library you can do these more simply in python and bonus more quickly each separate linux command in the she will with few exceptions forks subprocess by using python shutil and os modules you do not fork subprocess the she will environment features this includes stuff that sets command environment current directory and environment variables and what not you can easily manage this from python directly the she will programming features this is all the process status code checking the various logic commands if while for etc the test command and all of it is relatives the function definition stuff this is all much much easier in python this is one of the huge victories in getting rid of bash and doing it in python interaction features this includes command history and what not you do not need this for writing she will scripts this is only for human interaction and not for script writing the she will file management features this includes redirection and pipelines this is trickier much of this can be done with subprocess but some things that are easy in the she will are unpleasant in python specifically stuff like something result this runs two processes in parallel with output of as input to followed by third process the output from that sequence is run in parallel with something and the output is collected into file named result that is just complex to express in any other language specific programs awk sed grep etc can often be rewritten as python modules do not go overboard replace what you need and evolve your grep module do not start out writing python module that replaces grep the best thing is that you can do this in steps replace awk and perl with python leave everything else alone look at replacing grep with python this can be bit more complex but your version of grep can be tailored to your processing needs look at replacing find with python loops that use os walk this is big win because you do not spawn as many processes look at replacing common she will logic loops decisions etc with python scripts
QA
can use python as bash replacement currently do my textfile manipulation through bunch of badly remembered awk sed bash and tiny bit of perl have seen mentioned few places that python is good for this kind of thing know little and would like to know more is python good choice for this and is there good book or guide to learning how to use python to replace she will scripting awk sed and friends
if your textfile manipulation usually is one time possibly done on the she will prompt you will not get anything better from python on the other hand if you usually have to do the same or similar task over and over and you have to write your scripts for doing that then python is great and you can easily create your own libraries you can do that with she will scripts too but it is more cumbersome very simple example to get feeling import popen stdout text stdin text popen popen your she will command here for line in stdout text if line startswith pass else jobid int line split split lstrip rstrip do something with jobid check also sys and getopt module they are the first you will need
QA
can use python as bash replacement currently do my textfile manipulation through bunch of badly remembered awk sed bash and tiny bit of perl have seen mentioned few places that python is good for this kind of thing know little and would like to know more is python good choice for this and is there good book or guide to learning how to use python to replace she will scripting awk sed and friends
your best bet is tool that is specifically geared towards your problem if it is processing text files then sed awk and perl are the top contenders python is general purpose dynamic language as with any general purpose language there is support for file manipulation but that is not what it is core purpose is would consider python or ruby if had requirement for dynamic language in particular in short learn sed and awk really well plus all the other goodies that come with your flavour of nix all the bash built ins grep tr and so forth if it is text file processing you are interested in you are already using the right stuff
QA
can use python as bash replacement currently do my textfile manipulation through bunch of badly remembered awk sed bash and tiny bit of perl have seen mentioned few places that python is good for this kind of thing know little and would like to know more is python good choice for this and is there good book or guide to learning how to use python to replace she will scripting awk sed and friends
if you want to use python as she will why not have look at ipython it is also good to learn interactively the language if you do lot of text manipulation and if you use vim as text editor you can also directly write plugins for vim in python just type help python in vim and follow the instructions or have look at this presentation it is so easy and powerfull to write functions that you will use directly in your editor
QA
are there any ide that support python syntax recently saw an announcement and article outlining the release of the first python release candidate was wondering whether there were any commercial free open source etc ide that support its syntax
emacs python el continues to be better than anything else have tried
QA
map two lists into dictionary in python imagine that you have keys name age food values monty spam what is the simplest way to produce the following dictionary dict name monty age food spam this code works but am not really proud of it dict junk map lambda dict update keys values
like this keys values dictionary dict zip keys values print dictionary voila the pairwise dict constructor and zip function are awesomely useful https docs python org library functions html func dict
QA
map two lists into dictionary in python imagine that you have keys name age food values monty spam what is the simplest way to produce the following dictionary dict name monty age food spam this code works but am not really proud of it dict junk map lambda dict update keys values
keys name age food values monty spam dict zip keys values food spam age name monty
QA
map two lists into dictionary in python imagine that you have keys name age food values monty spam what is the simplest way to produce the following dictionary dict name monty age food spam this code works but am not really proud of it dict junk map lambda dict update keys values
try this import itertools keys name age food values monty spam adict dict itertools izip keys values adict food spam age name monty it was the simplest solution could come up with ps it is also more economical in memory consumption compared to zip
QA
how to make python command line program autocomplete arbitrary things not interpreter am aware of how to setup autocompletion of python objects in the python interpreter on unix google shows many hits for explanations on how to do this unfortunately there are so many references to that it is difficult to find what need to do which is slightly different need to know how to enable tab auto completion of arbitrary items in command line program written in python my specific use case is command line python program that needs to send emails want to be able to autocomplete email addresses have the addresses on disk when the user types part of it and optionally presses the tab key do not need it to work on windows or mac just linux
here is full working version of the code that was very supplied by ephemient here thank you import readline addrs angela domain com michael domain com david test com def completer text state options for in addrs if startswith text try return options state except indexerror return none readline set completer completer readline parse and bind tab complete while raw input print you entered
QA
how to enable mysql client auto re connect with mysqldb came across php way of doing the trick my bool reconnect mysql options mysql mysql opt reconnect reconnect but no luck with mysqldb python mysql can anybody please give clue thanks
if you are using ubuntu linux there was patch added to the python mysql package that added the ability to set that same mysql opt reconnect option see here have not tried it though unfortunately the patch was later removed due to conflict with autoconnect and transations described here the comments from that page say published in intrepid release on python mysqldb unstable urgency low sandro tosi debian control list items lines in description starts with space to avoid reformat on webpages closes bernd zeimetz debian patches reconnect dpatch dropping patch comment in storm which explains the problem here is another sad story about bad transactional behavior mysql offers feature to automatically reconnect dropped connections what sounds like dream is actually nightmare for anyone who is dealing with transactions when reconnection happens the currently running transaction is transparently rolled back and everything that was being done is lost without notice not only that but the connection may be put back in autocommit mode even when that is not the default mysqldb behavior the mysql developers quickly understood that this is terrible idea and removed the behavior in mysql unfortunately debian and ubuntu still have patch right now which reenables that behavior by default even past version
QA
advanced python ftp can control how ftplib talks to server need to send very specific non standard string to an ftp server dir sys ic icama the case is critical as are the style of quotes and their content unfortunately ftplib dir seems to use the list command rather than dir and it uses the wrong case for this application the ftp server is actually telephone switch and it is very non standard implementation tried using ftplib sendcmd but it also sends pasv as part of the command sequence is there an easy way of issuing specific commands to an ftp server
try the following it is modification of the original ftp dir command which uses dir instead of list it gives dir not understood error with the ftp server tested it on but it does send the command you are after you will want to remove the print command used to check that import ftplib class ftp ftplib ftp def shim dir self args list directory in long form by default list current directory to stdout optional last argument is callback function all non empty arguments before it are concatenated to the list command this should only be used for pathname cmd dir func none if args and type args type args func args args for arg in args if arg cmd cmd arg print cmd self retrlines cmd func if name main ftp ftp ncbi nih gov login shim dir blast
QA
map two lists into dictionary in python imagine that you have keys name age food values monty spam what is the simplest way to produce the following dictionary dict name monty age food spam this code works but am not really proud of it dict junk map lambda dict update keys values
if you need to transform keys or values before creating dictionary then generator expression could be used example adict dict str for in zip take look code like pythonista idiomatic python
QA
can use python as bash replacement currently do my textfile manipulation through bunch of badly remembered awk sed bash and tiny bit of perl have seen mentioned few places that python is good for this kind of thing know little and would like to know more is python good choice for this and is there good book or guide to learning how to use python to replace she will scripting awk sed and friends
in the beginning there was sh sed and awk and find and grep and it was good but awk can be an odd little beast and hard to remember if you do not use it often then the great camel created perl perl was system administrator dream it was like she will scripting on steroids text processing including regular expressions were just part of the language then it got ugly people tried to make big applications with perl now do not get me wrong perl can be an application but it can can look like mess if you are not really careful then there is all this flat data business it is enough to drive programmer nuts enter python ruby et al these are really very good general purpose languages they support text processing and do it well though perhaps not as tightly entwined in the basic core of the language but they also scale up very well and still have nice looking code at the end of the day they also have developed pretty hefty communities with plenty of libraries for most anything now much of the negativeness towards perl is matter of opinion and certainly some people can write very clean perl but with this many people complaining about it being too easy to create obfuscated code you know some grain of truth is there the question really becomes then are you ever going to use this language for more than simple bash script replacements if not learn some more perl it is absolutely fantastic for that if on the other hand you want language that will grow with you as you want to do more may suggest python or ruby either way good luck
QA
py rc lookuperror unknown encoding uft just installed the first release candidate of python and got this error after typing help modules foo lookuperror unknown encoding uft notice that it says uft and not utf is this py specific bug or misconfiguration on my part do not have any other versions of python installed on this french locale windows xp sp machine edit bug has been filled by alex coventry on october th
looks like typo in config file somewhere whether in the py package or on your machine you might try installing the stable final python which supports syntax changes with imports from future and if that works you should probably file bug report
QA
py rc lookuperror unknown encoding uft just installed the first release candidate of python and got this error after typing help modules foo lookuperror unknown encoding uft notice that it says uft and not utf is this py specific bug or misconfiguration on my part do not have any other versions of python installed on this french locale windows xp sp machine edit bug has been filled by alex coventry on october th
it is not typo it is deliberate error in test module met pwd home coventry src python rc met rgrep uft lib test bad coding py coding uft py lib test bad coding py coding uft removing this module causes the help command to fall over in different way it is bug however someone should file report
QA
can use python as bash replacement currently do my textfile manipulation through bunch of badly remembered awk sed bash and tiny bit of perl have seen mentioned few places that python is good for this kind of thing know little and would like to know more is python good choice for this and is there good book or guide to learning how to use python to replace she will scripting awk sed and friends
have built semi long she will scripts lines and python code which does similar functionality when many external commands are being executed find the she will is easier to use perl is also good option when there is lots of text manipulation
QA
can use python as bash replacement currently do my textfile manipulation through bunch of badly remembered awk sed bash and tiny bit of perl have seen mentioned few places that python is good for this kind of thing know little and would like to know more is python good choice for this and is there good book or guide to learning how to use python to replace she will scripting awk sed and friends
adding to previous answers check the pexpect module for dealing with interactive commands adduser passwd etc
QA
distributing stand alone python web based application to non technical users am writing web application in python intended for use by teachers and pupils in classroom it will run from hosted website but also want people to be able to download self contained application they can install locally if they want more performance or they simply will not have an internet connection available in the classroom the users are not going to be able to manage instructions like first install python then install dependencies download the tar gz archive and type these commands into the command line need to be able to create an all in one type installer that can potentially install python dependencies python ldap some python code and register python based web server as windows service have had look through previous questions but none quite seem relevant am not concerned about the security of source code my application will be open source will sell content to go with it just need non technical windows users to be able to download and use my application with no fuss my current thoughts are to use nsis to create an installer that includes python and python ldap as msis then registers my own simple python based web server as windows service and puts shortcut in the start menu on the desktop linking to http localhost is this doable with nsis can nsis check for currently installed copies of python for instance is there better way of doing this is there handy framework available that let us me shove my code in folder and bundle it up to make an installer
using nsis is great use it too but would suggest using packager like pyinstaller my personal fav alternatives bb freeze py exe to create an exe before the using nsis the primary benefit you get by doing this is your download is smaller as you are not bundling the whole python standard lib and extra stuff your app will not need and you get an exe file to boot
QA
how to base encode pdf file in python how should base encode pdf file for transport over xml rpc in python
if you do not want to use the xmlrpclib binary class you can just use the encode method of strings open pdf reference pdf rb read encode base
QA
python unsigned bit bitwise arithmetic trying to answer to another post whose solution deals with ip addresses and netmasks got stuck with plain bitwise arithmetic is there standard way in python to carry on bitwise and or xor not operations assuming that the inputs are bit maybe negative integers or longs and that the result must be long in the range in other words need working python counterpart to the bitwise operations between unsigned longs edit the specific issue is this xffffff netmask wtf want
from numpy import uint
QA
extracting parenthesized python expression from string have been wondering about how hard it would be to write some python code to search string for the index of substring of the form expr for example where expr is meant to be python expression or something resembling one given such thing one could easily imagine going on to check the expression syntax with compile evaluate it against particular scope with eval and perhaps even substitute the result into the original string people must do very similar things all the time could imagine solving such problem using third party parser generator oof or by hand coding some sort of state machine eek or perhaps by convincing python own parser to do the heavy lifting somehow hmm maybe there is third party templating library somewhere that can be made to do exactly this maybe restricting the syntax of expr is likely to be worthwhile compromise in terms of simplicity or execution time or cutting down on external dependencies for example maybe all really need is something that matches any expr that has balanced curly braces what is your sense update thanks very much for your responses so far looking back at what wrote yesterday am not sure was sufficiently clear about what am asking template substitution is indeed an interesting problem and probably much more useful to many more people than the expression extraction subproblem am wondering about but brought it up only as simple example of how the answer to my question might be useful in real life some other potential applications might include passing the extracted expressions to syntax highlighter passing the result to real python parser and looking at or monkeying with the parse tree or using the sequence of extracted expressions to build up larger python program perhaps in conjunction with some information taken from the surrounding text the expr syntax mentioned is also intended as an example and in fact wonder if should not have used expr as my example instead because it makes the potential drawbacks of the obvious approach along the lines of re finditer bit easier to see python expressions can and often do contain the or character it seems possible that handling any of those cases might be much more trouble than it is worth but am not convinced of that yet please feel free to try to make this case prior to posting this question spent quite bit of time looking at python template engines hoping that one might expose the sort of low level functionality am asking about namely something that can find expressions in variety of contexts and tell me where they are rather than being limited to finding expressions embedded using single hard coded syntax always evaluating them and always substituting the results back into the original string have not figured out how to use any of them to solve my problem yet but do very much appreciate the suggestions regarding more to look at cannot believe missed that wonderful list on the wiki the api documentation for these things tends to be pretty high level and am not too familiar with the internals of any of them so am sure could use help looking at those and figuring out how to get them to do this sort of thing thanks for your patience
after posting this reading the replies so far thanks everyone and thinking about the problem for while here is the best approach have been able to come up with find the first find the next after that feed whatever in between to compile if it works stick fork in it and we are done otherwise keep extending the string by looking for subsequent occurences of as soon as something compiles return it if we run out of without being able to compile anything use the results of the last compilation attempt to give information about where the problem lies advantages of this approach the code is quite short and easy to understand it is pretty efficient optimal even in the case where the expression contains no worst case seems like it would not be too bad either it works on many expressions that contain and or no external dependencies no need to import anything in fact this surprised me disadvantages sometimes it grabs too much or too little see below for an example of the latter could imagine scary example where you have two expressions and the first one is subtly wrong and the algorithm ends up mistakenly grabbing the whole thing and everything in between and returning it as valid though have not been able to demonstrate this perhaps things are not so bad as fear do not think misunderstandings can be avoided in general the problem definition is kind of slippery but it seems like it ought to be possible to do better especially if one were willing to trade simplicity or execution time have not done any benchmarks but could imagine there being faster alternatives especially in cases that involve lots of in the expression that could be big deal if one wanted to apply this technique to sizable blocks of python code rather than just very short expressions here is my implementation def findexpr begin end compargs string eval assert not in line numbers not implemented index begin len begin index end code errmsg none while code is none and errmsg is none expr try code compile expr compargs except syntaxerror find end if errmsg message offset return code errmsg and here is the docstring with some illustrations in doctest format which did not insert into the middle of the function above only because it is long and feel like the code is easier to read without it search for possibly invalid python expression bracketed by begin and end which default to and return tuple foo bar code errmsg findexpr errmsg none join ord byte for byte in code co code code co names would eval code would eval code would aacccc eval code none traceback most recent call last nameerror name is not defined expressions containing start and or end are allowed foo bar code errmsg findexpr errmsg none if the first match is syntactically invalid python points to the start of the match points to the parse error code is none and errmsg contains message from the compiler foo qwerty asdf zxcvbnm bar code errmsg findexpr errmsg qwerty asdf invalid syntax print code none if second argument is given start searching there code errmsg findexpr errmsg none raise valueerror if there are no further matches code errmsg findexpr traceback most recent call last valueerror substring not found in ambiguous cases match the shortest valid expression this is not always ideal behavior foo or return instead of none bar code errmsg findexpr errmsg or return none this implementation must not be used with multi line strings it does not adjust line number information in the returned code object and it does not take the line number into account when computing the offset of parse error
QA
python unsigned bit bitwise arithmetic trying to answer to another post whose solution deals with ip addresses and netmasks got stuck with plain bitwise arithmetic is there standard way in python to carry on bitwise and or xor not operations assuming that the inputs are bit maybe negative integers or longs and that the result must be long in the range in other words need working python counterpart to the bitwise operations between unsigned longs edit the specific issue is this xffffff netmask wtf want
you can use ctypes and its uint import ctypes xffffff ctypes uint value so what did here was casting to bit unsigned integer and retrieving its value back in python format
QA
python unsigned bit bitwise arithmetic trying to answer to another post whose solution deals with ip addresses and netmasks got stuck with plain bitwise arithmetic is there standard way in python to carry on bitwise and or xor not operations assuming that the inputs are bit maybe negative integers or longs and that the result must be long in the range in other words need working python counterpart to the bitwise operations between unsigned longs edit the specific issue is this xffffff netmask wtf want
you can mask everything by xffffffff xffffff allf xffffffff allf
QA
how to enable mysql client auto re connect with mysqldb came across php way of doing the trick my bool reconnect mysql options mysql mysql opt reconnect reconnect but no luck with mysqldb python mysql can anybody please give clue thanks
had similar problem with mysql and python and the solution that worked for me was to upgrade mysql to on fedora core your system may work fine with different version tried lot of other things including patching the python libraries but upgrading the database was lot easier and think better decision
QA
python module that implements ftps was wondering if anybody could point me towards free ftps module for python am complete newbie to python but this is something need for work project need an ftps client to connect to rd party ftps server thanks david
could not find free sftp client for windows so ended up wrapping putty psftp using python subprocess module probably would have used the twisted implementation mentioned by glyph if would known about it anyway if your interested it is available at http code google com psftplib
QA
using os execvp in python have question about using os execvp in python have the following bit of code that is used to create list of arguments args java classpath djava library path lib path ea xmx server code swarm params when output string using join args and paste that into my she will prompt the jvm launches fine and everything works everything works if use os system join args in my python script too but the following bit of code does not work os execvp java args get the following error unrecognized option classpath and then the classpath created which looks okay could not create the java virtual machine so what gives why does copying pasting into the she will or using os system work but not os execvp
if your classpath variable contains for instance classpath foo jar it will not work since it is thinking the option name is classpath foo jar split it in two arguments classpath classpath the other ways copy and paste and system work because the she will splits the command line at the spaces unless they are escaped or quoted the command line is in fact passed down to the called program as an array unlike on windows and the jvm is expecting to find an element with only classpath followed by another element with the classpath you can see the difference for yourself by calling the following small python script instead of the jvm usr bin python import sys print sys argv
QA
python import does not work as expected when using import with dotted name something like somepackage somemodule the module returned is not somemodule whatever is returned seems to be mostly empty what is going on here
from the python docs on import import name globals locals fromlist level when the name variable is of the form package module normally the top level package the name up till the first dot is returned not the module named by name however when non empty fromlist argument is given the module named by name is returned this is done for compatibility with the bytecode generated for the different kinds of import statement when using import spam ham eggs the top level package spam must be placed in the importing namespace but when using from spam ham import eggs the spam ham subpackage must be used to find the eggs variable as workaround for this behavior use getattr to extract the desired components for example you could define the following helper def my import name mod import name components name split for comp in components mod getattr mod comp return mod to paraphrase when you ask for somepackage somemodule import returns somepackage init py which is often empty it will return somemodule if you provide fromlist list of the variable names inside somemodule you want which are not actually returned you can also as did use the function they suggest note asked this question fully intending to answer it myself there was big bug in my code and having misdiagnosed it it took me long time to figure it out so figured would help the so community out and post the gotcha ran into here
QA
create an icon in memory with win in python what is good way to generate an icon in memory in python right now am forced to use pygame to draw the icon then save it to disk as an ico file and then load it from disk as an ico resource something like this if os path isfile self icon icon flags win con lr loadfromfile win con lr defaultsize hicon win gui loadimage hinst self icon win con image icon icon flags where self icon is the filename of the icon created is there any way to do this in memory edit all want to do is create an icon with digit number displayed on it weather taskbar style
you can probably create object that mimics the python file object interface http docs python org library stdtypes html bltin file objects