prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
translate svn path to local file system path in python am writing utility in python that will attach changed files in subversion to an email and send it when subset of folders that are under source control in svn have been changed am using the pysvn library to access the repository have copy of the files on my local file system and do an update to check if the files have changed since the last time the utility was run am at the point where am translating the path names in svn to the path names on my local copy currently have written the following to do the job def formatpaths self paths newpaths list for path in paths path path len self basepath path path replace newpaths append path return newpaths self basepath would be something like trunk project and am looking to just get the relative path of subset of folders folder under trunk project is this good way to solve this problem or is there some magical function missed
your specific solution to the path name copy is reasonable but your general solution to the entire problem could be improved would easy install anyvc library developed for the pida ide which is uniform python interface into version control systems and use it instead from anyvc import subversion vc subversion trunk modified relpath for in vc list if state clean for in modified print relpath the relative path of the file to the source root additionally would probably attach different to an email rather than the actual file but guess that is your choice
QA
how to determine if directory is on same partition say have an input file and target directory how do determine if the input file is on the same hard drive or partition as the target directory what want to do is the copy file if it is on different but move it if it is the same for example target directory volumes externaldrive something input foldername input filename os path split input file if same partition input foldername target directory copy input file target directory else move input file target directory thanks to cesarb answer the same partition function implemented import os def same partition return os stat st dev os stat st dev
in you would use stat and compare the st dev field in python os stat should do the same
QA
os determine trash location for given path simply moving the file to trash will not work as if the file os on an external drive it will move the file to the main system drive also there are other conditions like files on external drives get moved to volumes trash or whatever the current user id is given file or folder path what is the correct way to determine the trash folder imagine the language is pretty irrelevant but intend to use python
the file manager api has pair of functions called fsmoveobjecttotrashasync and fspathmoveobjecttotrashsync not sure if that is exposed to python or not
QA
how to determine if directory is on same partition say have an input file and target directory how do determine if the input file is on the same hard drive or partition as the target directory what want to do is the copy file if it is on different but move it if it is the same for example target directory volumes externaldrive something input foldername input filename os path split input file if same partition input foldername target directory copy input file target directory else move input file target directory thanks to cesarb answer the same partition function implemented import os def same partition return os stat st dev os stat st dev
another way is the better to ask forgiveness than permission approach just try to rename it and if that fails catch the appropriate oserror and try the copy approach ie import errno try os rename source dest except ioerror ex if ex errno errno exdev perform the copy instead this has the advantage that it will also work on windows where st dev is always for all partitions note that if you actually want to copy and then delete the source file ie perform move rather than just copy then shutil move will already do what you want help on function move in module shutil move src dst recursively move file or directory to another location if the destination is on our current filesystem then simply use rename otherwise copy src to the dst and then remove src edit updated due to matthew schinckel comment to mention that shutil move will delete the source after the copy which is not necessarily what is wanted as the question just mentions copying
QA
lua as general purpose scripting language when see lua the only thing ever read is great for embedding fast lightweight and more often than anything else world of warcraft or in short wow why is it limited to embedding the whole thing into another application why not write general purpose scripts like you do with python or perl lua seems to be doing great in aspects like speed and memory usage the fastest scripting language afaik so why is it that never see lua being used as desktop scripting language to automate tasks for example renaming bunch of files download some files from the web webscraping is it the lack of the standard library
just because it is marketed in some general sense as special purpose language for embedded script engines does not mean that it is limited to that in fact wow could probably just as well have chosen python as their embedded scripting language
QA
lua as general purpose scripting language when see lua the only thing ever read is great for embedding fast lightweight and more often than anything else world of warcraft or in short wow why is it limited to embedding the whole thing into another application why not write general purpose scripts like you do with python or perl lua seems to be doing great in aspects like speed and memory usage the fastest scripting language afaik so why is it that never see lua being used as desktop scripting language to automate tasks for example renaming bunch of files download some files from the web webscraping is it the lack of the standard library
it is probably because lua was designed as scripting and extension language on the official site it is described as powerful fast light weight embeddable scripting language there is nothing stopping you from writing general purpose programs for it if recall correctly it ships with an interpreter and compiler but the language designers intended it to be used mainly as an embedded language hence being light weight and all
QA
how can optimize this google app engine code am relatively new to the python world but this seems very straight forward google is yelling at me that this code needs to be optimized class addlinks webapp requesthandler def post self hash the textarea input to generate pseudo unique value hash md new self request get links hexdigest seperate the input by line alllinks self request get links splitlines for each line in the input add to the database for in alllinks newgroup linkgrouping newgroup reference hash newgroup link newgroup put testing vs live baseurl http localhost baseurl http linkabyss appspot com build template parameters template values all links alllinks base url baseurl reference hash output the template path os path join os path dirname file addlinks html self response out write template render path template values the dashboard is telling me that this is using ton of cpu where should look for improvements
looks pretty tight to me see one thing that may make small improvement your calling self request get links twice so adding unsplitlinks self request get links and referencing unsplitlinks could help other than that the loop is the only area see that would be target for optimization is it possible to prep the data and then add it to the db at once instead of doing db add per link assume the put command adds the link to the database
QA
python regex how to get positions of matches how can get the start and end positions of all matches using the re module for example given the pattern and the string would want to get the positions where it finds each letter ideally would like to get the text of the match back too
import re re compile for in finditer print start group
QA
python regex how to get positions of matches how can get the start and end positions of all matches using the re module for example given the pattern and the string would want to get the positions where it finds each letter ideally would like to get the text of the match back too
taken from regular expression howto span returns both start and end indexes in single tuple since the match method only checks if the re matches at the start of string start will always be zero however the search method of regexobject instances scans through the string so the match may not start at zero in that case re compile print match message none search message print re matchobject instance at group message span combine that with in python the finditer method is also available returning sequence of matchobject instances as an iterator re compile iterator finditer drummers drumming iterator callable iterator object at ac for match in iterator print match span you should be able to do something on the order of for match in re finditer print match span
QA
how can optimize this google app engine code am relatively new to the python world but this seems very straight forward google is yelling at me that this code needs to be optimized class addlinks webapp requesthandler def post self hash the textarea input to generate pseudo unique value hash md new self request get links hexdigest seperate the input by line alllinks self request get links splitlines for each line in the input add to the database for in alllinks newgroup linkgrouping newgroup reference hash newgroup link newgroup put testing vs live baseurl http localhost baseurl http linkabyss appspot com build template parameters template values all links alllinks base url baseurl reference hash output the template path os path join os path dirname file addlinks html self response out write template render path template values the dashboard is telling me that this is using ton of cpu where should look for improvements
how frequently is this getting called this does not look that bad especially after removing the duplicate request
QA
how can optimize this google app engine code am relatively new to the python world but this seems very straight forward google is yelling at me that this code needs to be optimized class addlinks webapp requesthandler def post self hash the textarea input to generate pseudo unique value hash md new self request get links hexdigest seperate the input by line alllinks self request get links splitlines for each line in the input add to the database for in alllinks newgroup linkgrouping newgroup reference hash newgroup link newgroup put testing vs live baseurl http localhost baseurl http linkabyss appspot com build template parameters template values all links alllinks base url baseurl reference hash output the template path os path join os path dirname file addlinks html self response out write template render path template values the dashboard is telling me that this is using ton of cpu where should look for improvements
you can dramatically reduce the interaction between your app and the database by just storing the complete self request get links in text field in the database only one put per post self the hash is not stored times for every link which makes no sense and is really waste of space and you save yourself the parsing of the textfield when someone actually calls the page
QA
truncate string without ending in the middle of word am looking for way to truncate string in python that will not cut off the string in the middle of word for example original this is really awesome dumb truncate this is real smart truncate this is really am looking for way to accomplish the smart truncate from above
actually wrote solution for this on recent project of mine have compressed the majority of it down to be little smaller def smart truncate content length suffix if len content length return content else return join content length split suffix what happens is the if statement checks if your content is already less than the cutoff point if it is not it truncates to the desired length splits on the space removes the last element so that you do not cut off word and then joins it back together while tacking on the
QA
how can optimize this google app engine code am relatively new to the python world but this seems very straight forward google is yelling at me that this code needs to be optimized class addlinks webapp requesthandler def post self hash the textarea input to generate pseudo unique value hash md new self request get links hexdigest seperate the input by line alllinks self request get links splitlines for each line in the input add to the database for in alllinks newgroup linkgrouping newgroup reference hash newgroup link newgroup put testing vs live baseurl http localhost baseurl http linkabyss appspot com build template parameters template values all links alllinks base url baseurl reference hash output the template path os path join os path dirname file addlinks html self response out write template render path template values the dashboard is telling me that this is using ton of cpu where should look for improvements
the main overhead here is the multiple individual puts to the datastore if you can store the links as single entity as andre suggests you can always split the links into an array and store it in listproperty if you do need an entity for each link try this for each line in the input add to the database groups for in alllinks newgroup linkgrouping newgroup reference hash newgroup link groups append newgroup db put groups it will reduce the datastore roundtrips to one and it is the roundtrips that are really killing your high cpu cap
QA
how to scp in python what is the most pythonic way to scp file in python the only route am aware of is os system scp localfile remotehost remotefile which is hack and which does not work outside linux like systems and which needs help from the pexpect module to avoid password prompts unless you already have passwordless ssh set up to the remote host am aware of twisted conch but would prefer to avoid implementing scp myself via low level ssh modules am aware of paramiko python module that supports ssh and sftp but it does not support scp background am connecting to router which does not support sftp but does support ssh scp so sftp is not an option edit this is duplicate of http stackoverflow com questions how do copy file to remote server in python using scp or ssh however that question does not give an scp specific answer that deals with keys from within python am hoping for way to run code kind of like import scp client scp client host host user user keyfile keyfile or client scp client host host user user client use system keys or client scp client host host user user password password and then client transfer etc local filename etc remote filename
if you install putty on win you get an pscp putty scp so you can use the os system hack on win too and you can use the putty agent for key managment sorry it is only hack but you can wrap it in python class
QA
truncate string without ending in the middle of word am looking for way to truncate string in python that will not cut off the string in the middle of word for example original this is really awesome dumb truncate this is real smart truncate this is really am looking for way to accomplish the smart truncate from above
here is slightly better version of the last line in adam solution return content length rsplit suffix this is slightly more efficient and returns more sensible result in the case there are no spaces in the front of the string
QA
truncate string without ending in the middle of word am looking for way to truncate string in python that will not cut off the string in the middle of word for example original this is really awesome dumb truncate this is real smart truncate this is really am looking for way to accomplish the smart truncate from above
def smart truncate width if width isspace return width else return width rsplit none testing it smart truncate the quick brown fox jumped over the lazy dog the quick brown fox
QA
what do you like about django started to learn django few days ago and as dive into it it seems that am starting to like it even more trying to migrate from other language will not say which one as the purpose of this question is not to bash anything so would like to know your opinion about django what do you like about it what made you switch use it what features you would like it to have that are not there what would make you switch to it how fast is it in production how hard is it to master it
what do like about it very simple orm clear separation of template controller django admin pluggable apps it seems to me that the django community really nailed that one what made me switch mainly curiosity heard lot of good things about it from colleague wanted something more lightweight than the java do for living had side project heavily data driven for which the django admin interface is very useful what features would like better simpler control of the transactions configuring different types of transactions read only read write some tweaking here and there is not as easy as am used to having session in view model where the transaction is still open in the view does not make me all that comfortable would prefer if the transactions did not leave service layer but again there is not really service layer in the django model better model for business logic maybe that is just me but miss the service oriented approach of enterprise java never know if should put the business logic in the view in the form or in the model none of those solution make me feel warm and fuzzy at the same time do not have heavy business logic in the application develop for the moment and would probably still use java for those stability in the sense of not changing not in the sense of not crashing again coming from java where am still working on java for lot of projects having project that just released and all the refactoring that went with it is not very reassuring it did take some work to follow trunk and using was not particularly compelling do not think would feel comfortable to use it on mission critical enterprise project yet realize that there is quite few improvements that would like do not understand me wrong love django and will stick to it for lot of projects jsut will not put it everywhere yet
QA
what do you like about django started to learn django few days ago and as dive into it it seems that am starting to like it even more trying to migrate from other language will not say which one as the purpose of this question is not to bash anything so would like to know your opinion about django what do you like about it what made you switch use it what features you would like it to have that are not there what would make you switch to it how fast is it in production how hard is it to master it
what do you like about it url dispatching was never big fan of foo php is the file foo php on my server and if want nicer urls need to mess around with mod rewrite and keep that in line with what my logic in foo expects orm because of your queries in my experience do not need to be written by hand smart caching is much more important for performance in general you can always drop to raw sql as needed middleware and signals easy to extend most parts of the request response view render cycle without touching django code itself what made you switch use it it came out when was disappointed with the python web framework offerings an easy sell for me how fast is it in production hmm to be honest have never cared too much the webserver part of your app is in my opinion always the easiest to scale as long as you use best practices and share nothing all you need to do is add software load balancer and you can add new webservers until the cows come home the first bottleneck people generally hit is database load but django gives you great caching apis that help you alleviate that that said only skimmed this but it seems faster than rails and the well known php frameworks http wiki rubyonrails org rails pages framework performance how hard is it to master it guess it depends how you define master the documentation is great over the course of decent sized site app think you will use little bit of everything which is great start
QA
how can optimize this google app engine code am relatively new to the python world but this seems very straight forward google is yelling at me that this code needs to be optimized class addlinks webapp requesthandler def post self hash the textarea input to generate pseudo unique value hash md new self request get links hexdigest seperate the input by line alllinks self request get links splitlines for each line in the input add to the database for in alllinks newgroup linkgrouping newgroup reference hash newgroup link newgroup put testing vs live baseurl http localhost baseurl http linkabyss appspot com build template parameters template values all links alllinks base url baseurl reference hash output the template path os path join os path dirname file addlinks html self response out write template render path template values the dashboard is telling me that this is using ton of cpu where should look for improvements
can query against the listproperty something like select from linkgrouping where links contains http www google com have future plans where would need that functionality will definitely implement the single db put to reduce usage
QA
truncate string without ending in the middle of word am looking for way to truncate string in python that will not cut off the string in the middle of word for example original this is really awesome dumb truncate this is real smart truncate this is really am looking for way to accomplish the smart truncate from above
def smart truncate text max length suffix returns string of at most max length characters cutting only at word boundaries if the string was truncated suffix will be appended if len text max length pattern max length len suffix return re sub pattern suffix text else return text or def smart truncate text min length suffix if the text is more than min length characters long it will be cut at the next word boundary and suffix will be appended pattern min length return re sub pattern suffix text or def smart truncate text length suffix truncates text on word boundary as close to the target length it can come slen len suffix pattern length slen if len text length match re match pattern text if match length match end length match end if abs length slen length abs length slen length return match group suffix else return match group suffix return text
QA
what do you like about django started to learn django few days ago and as dive into it it seems that am starting to like it even more trying to migrate from other language will not say which one as the purpose of this question is not to bash anything so would like to know your opinion about django what do you like about it what made you switch use it what features you would like it to have that are not there what would make you switch to it how fast is it in production how hard is it to master it
have not had had the opportunity to use it much that said my absolute favorite part of django is the built in administration console
QA
truncate string without ending in the middle of word am looking for way to truncate string in python that will not cut off the string in the middle of word for example original this is really awesome dumb truncate this is real smart truncate this is really am looking for way to accomplish the smart truncate from above
there are few subtleties that may or may not be issues for you such as handling of tabs eg if you are displaying them as spaces but treating them as character internally handling various flavours of breaking and non breaking whitespace or allowing breaking on hyphenation etc if any of this is desirable you may want to take look at the textwrap module eg def truncate text max size if len text max size return text return textwrap wrap text max size the default behaviour for words greater than max size is to break them making max size hard limit you can change to the soft limit used by some of the other solutions here by passing break long words false to wrap in which case it will return the whole word if you want this behaviour change the last line to lines textwrap wrap text max size break long words false return lines if len lines else there are few other options like expand tabs that may be of interest depending on the exact behaviour you want
QA
how to scp in python what is the most pythonic way to scp file in python the only route am aware of is os system scp localfile remotehost remotefile which is hack and which does not work outside linux like systems and which needs help from the pexpect module to avoid password prompts unless you already have passwordless ssh set up to the remote host am aware of twisted conch but would prefer to avoid implementing scp myself via low level ssh modules am aware of paramiko python module that supports ssh and sftp but it does not support scp background am connecting to router which does not support sftp but does support ssh scp so sftp is not an option edit this is duplicate of http stackoverflow com questions how do copy file to remote server in python using scp or ssh however that question does not give an scp specific answer that deals with keys from within python am hoping for way to run code kind of like import scp client scp client host host user user keyfile keyfile or client scp client host host user user client use system keys or client scp client host host user user password password and then client transfer etc local filename etc remote filename
you might be interested in trying pexpect sourceforge project this would allow you to deal with interactive prompts for your password here is snip of example usage for ftp from the main website this connects to the openbsd ftp site and downloads the recursive directory listing import pexpect child pexpect spawn ftp ftp openbsd org child expect name child sendline anonymous child expect password child sendline noah example com child expect ftp child sendline cd pub child expect ftp child sendline get ls lr gz child expect ftp child sendline bye
QA
how to scp in python what is the most pythonic way to scp file in python the only route am aware of is os system scp localfile remotehost remotefile which is hack and which does not work outside linux like systems and which needs help from the pexpect module to avoid password prompts unless you already have passwordless ssh set up to the remote host am aware of twisted conch but would prefer to avoid implementing scp myself via low level ssh modules am aware of paramiko python module that supports ssh and sftp but it does not support scp background am connecting to router which does not support sftp but does support ssh scp so sftp is not an option edit this is duplicate of http stackoverflow com questions how do copy file to remote server in python using scp or ssh however that question does not give an scp specific answer that deals with keys from within python am hoping for way to run code kind of like import scp client scp client host host user user keyfile keyfile or client scp client host host user user client use system keys or client scp client host host user user password password and then client transfer etc local filename etc remote filename
hmmm perhaps another option would be to use something like sshfs there an sshfs for mac too once your router is mounted you can just copy the files outright am not sure if that works for your particular application but it is nice solution to keep handy
QA
is it possible to communicate with sub subprocess with subprocess popen am trying to write python script that packages our software this script needs to build our product and package it currently we have other scripts that do each piece individually which include csh and perl scripts one such script is run like sudo mod args where mod is perl script so in python would do proc popen sudo mod noresource you dtt stderr pipe stdout pipe stdin pipe the problem is that this mod script needs few questions answered for this thought that the traditional stdout stderr proc communicate input would work do not think it is working because the process that popen is controlling is sudo not the mod script that is asking the question is there any way to communicate with the mod script and still run it through sudo
the simplest thing to do would be the run the controlling script the python script via sudo are you able to do that or is that not an option
QA
is it possible to communicate with sub subprocess with subprocess popen am trying to write python script that packages our software this script needs to build our product and package it currently we have other scripts that do each piece individually which include csh and perl scripts one such script is run like sudo mod args where mod is perl script so in python would do proc popen sudo mod noresource you dtt stderr pipe stdout pipe stdin pipe the problem is that this mod script needs few questions answered for this thought that the traditional stdout stderr proc communicate input would work do not think it is working because the process that popen is controlling is sudo not the mod script that is asking the question is there any way to communicate with the mod script and still run it through sudo
think you should remove the sudo in your popen call and require the user of your script to type sudo this additionally makes more explicit the need for elevated privileges in your script instead of hiding it inside popen
QA
jython howto move file shutils move is non existant use jython import shutil print dir shutil there is no shutil move how does one move file with jython and while we at it how does one delete file with jython
if you need support for moving across filesystems consider just copying cpython shutil py into your project the python license is flexible enough to allow this even for commercial projects as long as licensing and attribution information are retained
QA
is it possible to communicate with sub subprocess with subprocess popen am trying to write python script that packages our software this script needs to build our product and package it currently we have other scripts that do each piece individually which include csh and perl scripts one such script is run like sudo mod args where mod is perl script so in python would do proc popen sudo mod noresource you dtt stderr pipe stdout pipe stdin pipe the problem is that this mod script needs few questions answered for this thought that the traditional stdout stderr proc communicate input would work do not think it is working because the process that popen is controlling is sudo not the mod script that is asking the question is there any way to communicate with the mod script and still run it through sudo
we need more information is sudo asking you for password what kind of interface does the mod script have for asking questions because these kind of things are not handled as normal over the pipe solution for both of these might be pexpect which is rather expert at handling funny scripts that ask for passwords and various other input issues
QA
how to specify relations using sqlalchemy declarative syntax cannot find any proper documentation on how to specify relations using the declarative syntax of sqlalchemy is it unsupported that is should use the traditional syntax am looking for way to specify relations at higher level avoiding having to mess with foreign keys etc would like to just declare addresses onetomany address and let the framework handle the details know that elixir can do that but was wondering if plain sqla could do it too thanks for your help
assuming you are referring to the declarative plugin where everything am about to say is documented with examples class user base tablename users id column id integer primary key true addresses relation address backref user class address base tablename addresses id column id integer primary key true user id column user id integer foreignkey users id
QA
django arbitrary number of unnamed urls py parameters have django model with large number of fields and table rows to facilitate human readable urls and the ability to break down the large list into arbitrary sublists would like to have url that looks like this browse name value name value etc where name maps to model attribute and value is the search criteria for that attribute each name will be treated like category to return subsets of the model instances where the categories match now this could be handled with get parameters but prefer more readable urls for both the user sake and the search engines these urls subsets will be embedded on each page that displays this model so it seems worth the effort to make pretty urls ideally each name value pair will be passed to the view function as parameter named name name etc however do not believe it is possible to defined named patterns via regex matched text am wrong there so it seems need to do something like this urlpatterns patterns url browse app views view name model browse it seems this should match any sets of two name value pairs while it matches it successfully it only passes the last name value pair as parameters to the view function my guess is that each match is overwriting the previous match under the guess that the containing is causing it tried simple repeating pattern instead urlpatterns patterns url browse app views view name model browse and got the same problem but this time args only includes the last matched pattern is this limitation of django url dispatcher and or python regex support it seems either of these methods should work is there way to achieve this without hardcoding each possible model attribute in the url as an optional pattern
agree with adam but think the pattern in urls py should be browse match the will only match word characters but the will match anything
QA
is it possible to set timeout on socket in twisted realize am probably just dumb and missing something big and important but cannot figure out how to specify timeout in twisted using reactor listenudp my goal is to be able to specify timeout and after said amount of time if datagramprotocol datagramreceived has not been executed have it execute callback or something that can use to call reactor stop any help or advice is appreciated thanks
think reactor calllater would work better than loopingcall something like this class protocol datagramprotocol def init self timeout self timeout timeout def datagramreceived self datagram self timeout cancel timeout reactor calllater timedout reactor listenudp protocol timeout
QA
lua as general purpose scripting language when see lua the only thing ever read is great for embedding fast lightweight and more often than anything else world of warcraft or in short wow why is it limited to embedding the whole thing into another application why not write general purpose scripts like you do with python or perl lua seems to be doing great in aspects like speed and memory usage the fastest scripting language afaik so why is it that never see lua being used as desktop scripting language to automate tasks for example renaming bunch of files download some files from the web webscraping is it the lack of the standard library
definitely lack of standard libraries it is also lesser known than python perl or ruby
QA
how to get function name as string in python in python how do get function name as string without calling the function def my function pass print get function name as string my function my function is not in quotes should output my function is this available in python if not any idea how to write get function name as string in python
my function func name there are also other fun properties of functions type dir func name to list them func name func code co code is the compiled function stored as string import dis dis dis my function will display the code in almost human readable format
QA
script languages on windows mobile something similar to python nokia try to find something similar to nokia python for windows mobile based devices script interpreter in this case also able to create standalone apps with easy access to all phone interfaces ability to make phone call send sms make photo send file over gprs etc while there is pythonce available for windows mobile it is pure python interpreter and what look for are all those libraries that nokia python has like import camera import messaging ability to control the phone programatically also the bluetooth console of nokia python is great do not want to use net cf as even there afaik to control camera you need to use some indirect methods for example http blogs msdn com marcpe archive aspx appreciate any help you can provide thanks in advance hope there is something was unable to locate via google
well there is mortscript widely used scripting for windows mobile not sure if it can access all the phones functions believe there is tcl for windows mobile as well
QA
os determine trash location for given path simply moving the file to trash will not work as if the file os on an external drive it will move the file to the main system drive also there are other conditions like files on external drives get moved to volumes trash or whatever the current user id is given file or folder path what is the correct way to determine the trash folder imagine the language is pretty irrelevant but intend to use python
alternatively if you are on os you could use scripting bridge to delete files via the finder have done this in ruby code here via rubycocoa the the gist of it is url nsurl fileurlwithpath path finder sbapplication applicationwithbundleidentifier com apple finder item finder items objectatlocation url item delete you could easily do something similar with pyobjc
QA
how to scp in python what is the most pythonic way to scp file in python the only route am aware of is os system scp localfile remotehost remotefile which is hack and which does not work outside linux like systems and which needs help from the pexpect module to avoid password prompts unless you already have passwordless ssh set up to the remote host am aware of twisted conch but would prefer to avoid implementing scp myself via low level ssh modules am aware of paramiko python module that supports ssh and sftp but it does not support scp background am connecting to router which does not support sftp but does support ssh scp so sftp is not an option edit this is duplicate of http stackoverflow com questions how do copy file to remote server in python using scp or ssh however that question does not give an scp specific answer that deals with keys from within python am hoping for way to run code kind of like import scp client scp client host host user user keyfile keyfile or client scp client host host user user client use system keys or client scp client host host user user password password and then client transfer etc local filename etc remote filename
you could also check out paramiko there is no scp module yet but it fully supports sftp edit sorry missed the line where you mentioned paramiko the following module is simply an implementation of the scp protocol for paramiko if you do not want to use paramiko or conch the only ssh implementations know of for python you could rework this to run over regular ssh session using pipes scp py for paramiko
QA
need really good reason to use python have been trying to make case for using python at my work we use and asp net for basically all of our development or more of our projects are web applications it seems natural that we would look at some of the nice dynamic web languages ruby python etc and with things like ironruby and ironpython started seriously investigating love python it is beautiful expressive language it is joy to code in for sure the multitude of python modules and frameworks make it very appealing problem is cannot think of any specific problems any specific hurdles that would require language like python asp net gives us rad it gives us full featured framework and all that good stuff also we all already know and have lots of projects in learning new language just because does not quite work can you guys help me think of something to finally convince my boss to really learn python and start using it on projects edit know that no problem requires only one language just meant are there any specific problems in which dynamic languages excel over static languages edit again let me also mention that my boss prompted me to investigate this he has put aside hours to research these languages find good one learn it and then figure out how we can use it am at the last step here do not need lecture on why should consider my motivation for changing something my company does because they do it for reason
python got good start in the java world as jython for unit testing in fact many java people started using it first that way its dynamic scripting nature makes it great fit for unit tests just yesterday was wishing could use it or something like it for the unit tests was writing for vb net project would have to say that it is not so much about the individual language ironruby or ironpython as it is about the style of development that they enable you can write static language like code in either but you do not fully reap the benefits until you can start to think dynamically once you grasp those concepts you will start to slowly change the way you code and your projects will require less classes and less code to implement testing particularly unit tests will become must since you give up the warm blanket known as compiler with type safety checks for other efficiencies
QA
what do you like about django started to learn django few days ago and as dive into it it seems that am starting to like it even more trying to migrate from other language will not say which one as the purpose of this question is not to bash anything so would like to know your opinion about django what do you like about it what made you switch use it what features you would like it to have that are not there what would make you switch to it how fast is it in production how hard is it to master it
likes the excellent documentation together with help from stackoverflow have learned lot in only few days it writting in python it has the wonderful contrib admin which is even modular and extensible to embed it into the web app proper dislikes none so far am still enchanted switch its my first web framework so no switch after using python for some years django seemed the natural selection to me mainly for its clean design
QA
what is the best way to serve static web pages from within django application am building relatively simple django application and apart from the main page where most of the dynamic parts of the application are there are few pages that will need that will not be dynamic at all about faq etc what is the best way to integrate these into django idealing still using the django template engine should just create template for each and then have view that simply renders that template
have you looked at flat pages in django it probably does everything you are looking for
QA
what is the best way to serve static web pages from within django application am building relatively simple django application and apart from the main page where most of the dynamic parts of the application are there are few pages that will need that will not be dynamic at all about faq etc what is the best way to integrate these into django idealing still using the django template engine should just create template for each and then have view that simply renders that template
if you want to just create template for each of them you could use the direct to template generic view to serve it up another option would be the django contrib flatpages app which would let you configure the static urls and content via the database
QA
how do restrict foreign keys choices to related objects only in django have two way foreign relation similar to the following class parent models model name models charfield max length favoritechild models foreignkey child blank true null true class child models model name models charfield max length myparent models foreignkey parent how do restrict the choices for parent favoritechild to only children whose parent is itself tried class parent models model name models charfield max length favoritechild models foreignkey child blank true null true limit choices to myparent self but that causes the admin interface to not list any children
just came across foreignkey limit choices to in the django docs not sure yet how this works but it might just be the right think here update foreignkey limit choices to allows to specify either constant callable or object to restrict the allowable choices for the key constant obviously is no use here since it knows nothing about the objects involved using callable function or class method or any callable object seem more promising the problem remains how to access the necessary information form the httprequest object using thread local storage may be solution update here is what hast worked for me created middle ware as described in the link above it extracts one or more arguments from the request get part such as product and stores this information in the thread locals next there is class method in the model that reads the thread local variable and returns list of ids to limit the choice of foreign key field classmethod def product list cls return list containing the one product id contained in the request url or query containing all valid product ids if not id present in url used to limit the choice of foreign key object to those related to the current product id threadlocals get current product if id is not none return id else return product objects all values pk query it is important to return query containing all possible ids if none was selected so the normal admin pages work ok the foreign key field is then declared as product models foreignkey product limit choices to dict id in basemodel product list the catch is that you have to provide the information to restrict the choices via the request do not see way to access self here
QA
is it possible to communicate with sub subprocess with subprocess popen am trying to write python script that packages our software this script needs to build our product and package it currently we have other scripts that do each piece individually which include csh and perl scripts one such script is run like sudo mod args where mod is perl script so in python would do proc popen sudo mod noresource you dtt stderr pipe stdout pipe stdin pipe the problem is that this mod script needs few questions answered for this thought that the traditional stdout stderr proc communicate input would work do not think it is working because the process that popen is controlling is sudo not the mod script that is asking the question is there any way to communicate with the mod script and still run it through sudo
would choose to go with pexpect import pexpect child pexpect spawn sudo mod noresource you dtt child expect first question child sendline child expect second question child sendline yup
QA
script languages on windows mobile something similar to python nokia try to find something similar to nokia python for windows mobile based devices script interpreter in this case also able to create standalone apps with easy access to all phone interfaces ability to make phone call send sms make photo send file over gprs etc while there is pythonce available for windows mobile it is pure python interpreter and what look for are all those libraries that nokia python has like import camera import messaging ability to control the phone programatically also the bluetooth console of nokia python is great do not want to use net cf as even there afaik to control camera you need to use some indirect methods for example http blogs msdn com marcpe archive aspx appreciate any help you can provide thanks in advance hope there is something was unable to locate via google
it sounds as if this is an opportunity for you to develop some extension modules for the pythonce project
QA
python using recursive algorithm as generator recently wrote function to generate certain sequences with nontrivial constraints the problem came with natural recursive solution now it happens that even for relatively small input the sequences are several thousands thus would prefer to use my algorithm as generator instead of using it to fill list with all the sequences here is an example suppose we want to compute all the permutations of string with recursive function the following naive algorithm takes an extra argument storage and appends permutation to it whenever it finds one def getpermutations string storage prefix if len string storage append prefix string else for in range len string getpermutations string string storage prefix string storage getpermutations abcd storage for permutation in storage print permutation please do not care about inefficiency this is only an example now want to turn my function into generator to yield permutation instead of appending it to the storage list def getpermutations string prefix if len string yield prefix string else for in range len string getpermutations string string prefix string for permutation in getpermutations abcd print permutation this code does not work the function behaves like an empty generator am missing something is there way to turn the above recursive algorithm into generator without replacing it with an iterative one
this avoids the len string deep recursion and is in general nice way to handle generators inside generators from types import generatortype def flatten stack stack list stack while stack try stack next except stopiteration stack pop continue if isinstance generatortype stack insert else yield def getpermutations string prefix if len string yield prefix string else yield getpermutations string string prefix string for in range len string def getpermutations string return flatten getpermutations string for permutation in getpermutations abcd print permutation flatten allows us to continue progress in another generator by simply yielding it instead of iterating through it and yielding each item manually python will add yield from to the syntax which allows for natural delegation to sub generator def getpermutations string prefix if len string yield prefix string else for in range len string yield from getpermutations string string prefix string
QA
possible google riddle my friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant shirt so have couple of guesses as to what it means but was just wondering if there is something more my first guess is that each block represents page layout and the logo you should test that just means that you should use google website optimizer to test which is the best layout hope that this is not the answer it just seems to simple and unsatisfying well have spent the past hour trying to figure out if there is any deeper meaning but to no avail so am here hoping that someone might be able to help did though write program to see if the blocks represent something in binary will post the code below my code tests every permutation of reading block as bits and then tries to interpret these bits as letters hex and ip addresses hope someone knows better this code interprets the google shirt as binary code each box bits try every permutation of counting the bits and then try to interpret these interpretations as letters or hex numbers or ip addresses need more interpretations maybe one will find pattern import string these represent the boxes binary codes from left to right top to bottom boxes changing the ordering permutations alphabet hashing where alphabet would of alphabet hasing where alphabet would of hex would code to convert from string of ones and zeros binary to decimal number def bin to dec bin string len bin string answer for index in range answer int bin string index index return answer code to try and ping ip addresses def ping ipaddress ping the network addresses import subprocess execute the code and pipe the result to string wait seconds test ping ipaddress process subprocess popen test she will true stdout subprocess pipe give it time to respond process wait read the result to string result str process stdout read for now need to manually check if the ping worked fix later print result str now iterate over the permuation and then the boxes to produce the codes for permute in permutations box codes for box in boxes temp code for index in permute temp code box int index box codes append temp code now manipulate the codes using leter translation network whatever binary print string join box codes alphabet print string join map lambda alphabet box codes alphabet print string join map lambda alphabet box codes hex print string join map lambda hex box codes ipaddress call ping and see who is reachable ipcodes zip box codes box codes ip for code in ipcodes bin bin to dec code code ip repr bin print ip ping ip print print shirt
what if it does not mean anything what if it is just neat design they came up with
QA
bizarre python importerror here is my setup mac running os tiger windows xp running in virtual machine parallels windows xp has my mac home directory mapped as network drive have two files in directory of my mac home directory foo py pass test py import foo if run test py from within my virtual machine by typing python test py get this traceback most recent call last file test py line in module import foo importerror no module named foo if try to import foo from the console running python under windows from the same directory all is well python apr msc bit intel on win type help copyright credits or license for more information import foo if run test py with mac python all is well if copy test py and foo py to different directory can run test py under windows without problems there is an init py in the original directory but it is empty furthermore copying it with the other files does not break anything in the previous paragraph there are no python related environment variables set any ideas
add import sys print sys path to the start of test py see what it prints out in the failing case if is not on the list that may be your problem
QA
possible google riddle my friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant shirt so have couple of guesses as to what it means but was just wondering if there is something more my first guess is that each block represents page layout and the logo you should test that just means that you should use google website optimizer to test which is the best layout hope that this is not the answer it just seems to simple and unsatisfying well have spent the past hour trying to figure out if there is any deeper meaning but to no avail so am here hoping that someone might be able to help did though write program to see if the blocks represent something in binary will post the code below my code tests every permutation of reading block as bits and then tries to interpret these bits as letters hex and ip addresses hope someone knows better this code interprets the google shirt as binary code each box bits try every permutation of counting the bits and then try to interpret these interpretations as letters or hex numbers or ip addresses need more interpretations maybe one will find pattern import string these represent the boxes binary codes from left to right top to bottom boxes changing the ordering permutations alphabet hashing where alphabet would of alphabet hasing where alphabet would of hex would code to convert from string of ones and zeros binary to decimal number def bin to dec bin string len bin string answer for index in range answer int bin string index index return answer code to try and ping ip addresses def ping ipaddress ping the network addresses import subprocess execute the code and pipe the result to string wait seconds test ping ipaddress process subprocess popen test she will true stdout subprocess pipe give it time to respond process wait read the result to string result str process stdout read for now need to manually check if the ping worked fix later print result str now iterate over the permuation and then the boxes to produce the codes for permute in permutations box codes for box in boxes temp code for index in permute temp code box int index box codes append temp code now manipulate the codes using leter translation network whatever binary print string join box codes alphabet print string join map lambda alphabet box codes alphabet print string join map lambda alphabet box codes hex print string join map lambda hex box codes ipaddress call ping and see who is reachable ipcodes zip box codes box codes ip for code in ipcodes bin bin to dec code code ip repr bin print ip ping ip print print shirt
think google are just trying to drive their point home here are bunch of different representations of the same page test them see which is best which block do you like best
QA
possible google riddle my friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant shirt so have couple of guesses as to what it means but was just wondering if there is something more my first guess is that each block represents page layout and the logo you should test that just means that you should use google website optimizer to test which is the best layout hope that this is not the answer it just seems to simple and unsatisfying well have spent the past hour trying to figure out if there is any deeper meaning but to no avail so am here hoping that someone might be able to help did though write program to see if the blocks represent something in binary will post the code below my code tests every permutation of reading block as bits and then tries to interpret these bits as letters hex and ip addresses hope someone knows better this code interprets the google shirt as binary code each box bits try every permutation of counting the bits and then try to interpret these interpretations as letters or hex numbers or ip addresses need more interpretations maybe one will find pattern import string these represent the boxes binary codes from left to right top to bottom boxes changing the ordering permutations alphabet hashing where alphabet would of alphabet hasing where alphabet would of hex would code to convert from string of ones and zeros binary to decimal number def bin to dec bin string len bin string answer for index in range answer int bin string index index return answer code to try and ping ip addresses def ping ipaddress ping the network addresses import subprocess execute the code and pipe the result to string wait seconds test ping ipaddress process subprocess popen test she will true stdout subprocess pipe give it time to respond process wait read the result to string result str process stdout read for now need to manually check if the ping worked fix later print result str now iterate over the permuation and then the boxes to produce the codes for permute in permutations box codes for box in boxes temp code for index in permute temp code box int index box codes append temp code now manipulate the codes using leter translation network whatever binary print string join box codes alphabet print string join map lambda alphabet box codes alphabet print string join map lambda alphabet box codes hex print string join map lambda hex box codes ipaddress call ping and see who is reachable ipcodes zip box codes box codes ip for code in ipcodes bin bin to dec code code ip repr bin print ip ping ip print print shirt
well cannot see an immediate pattern but if you are testing ip why not take two blocks of as single binary number
QA
possible google riddle my friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant shirt so have couple of guesses as to what it means but was just wondering if there is something more my first guess is that each block represents page layout and the logo you should test that just means that you should use google website optimizer to test which is the best layout hope that this is not the answer it just seems to simple and unsatisfying well have spent the past hour trying to figure out if there is any deeper meaning but to no avail so am here hoping that someone might be able to help did though write program to see if the blocks represent something in binary will post the code below my code tests every permutation of reading block as bits and then tries to interpret these bits as letters hex and ip addresses hope someone knows better this code interprets the google shirt as binary code each box bits try every permutation of counting the bits and then try to interpret these interpretations as letters or hex numbers or ip addresses need more interpretations maybe one will find pattern import string these represent the boxes binary codes from left to right top to bottom boxes changing the ordering permutations alphabet hashing where alphabet would of alphabet hasing where alphabet would of hex would code to convert from string of ones and zeros binary to decimal number def bin to dec bin string len bin string answer for index in range answer int bin string index index return answer code to try and ping ip addresses def ping ipaddress ping the network addresses import subprocess execute the code and pipe the result to string wait seconds test ping ipaddress process subprocess popen test she will true stdout subprocess pipe give it time to respond process wait read the result to string result str process stdout read for now need to manually check if the ping worked fix later print result str now iterate over the permuation and then the boxes to produce the codes for permute in permutations box codes for box in boxes temp code for index in permute temp code box int index box codes append temp code now manipulate the codes using leter translation network whatever binary print string join box codes alphabet print string join map lambda alphabet box codes alphabet print string join map lambda alphabet box codes hex print string join map lambda hex box codes ipaddress call ping and see who is reachable ipcodes zip box codes box codes ip for code in ipcodes bin bin to dec code code ip repr bin print ip ping ip print print shirt
think it is simply design nothing secret or mysterious
QA
how do coherently organize modules for pygtk desktop application am working on desktop application in pygtk and seem to be bumping up against some limitations of my file organization thus far have structured my project this way application py holds the primary application class most functional routines gui py holds loosely coupled gtk gui implementation handles signal callbacks etc command py holds command line automation functions not dependent on data in the application class state py holds the state data persistence class this has served fairly well so far but at this point application py is starting to get rather long have looked at numerous other pygtk applications and they seem to have similar structural issues at certain point the primary module starts to get very long and there is not obvious way of breaking the code out into narrower modules without sacrificing clarity and object orientation have considered making the gui the primary module and having seperate modules for the toolbar routines the menus routines etc but at that point believe will lose most of the benefits of oop and end up with an everything references everything scenario should just deal with having very long central module or is there better way of structuring the project so that do not have to rely on the class browser so much edit ok so point taken regarding all the mvc stuff do have rough approximation of mvc in my code but admittedly could probably gain some mileage by further segregating the model and controller however am reading over python gtkmvc documentation which is great find by the way thank you for referencing it and my impression is that its not going to solve my problem so much as just formalize it my application is single glade file generally single window so no matter how tightly define the mvc roles of the modules am still going to have one controller module doing most everything which is pretty much what have now admittedly am little fuzzy on proper mvc implementation and am going to keep researching but it does not look to me like this architecture is going to get any more stuff out of my main file its just going to rename that file to controller py should be thinking about separate controller view pairs for seperate sections of the window the toolbar the menus etc perhaps that is what am missing here it seems that this is what lott is referring to in his second bullet point thanks for the responses so far
sorry to answer so late kiwi seems to me far better solution than gtkmvc it is my first dependency for any pygtk project
QA
how to copy all properties of an object to another object in python is there library method to copy all the properties between two already present instances of the same class in python mean something like apache commons propertyutilsbean copyproperties thanks
if you have to do this guess the nicest way is to have class attribute something like class copyable object copyable attributes an attribute another attribute then iterate them explicitly and use setattr new attr getattr old attr still believe it can be solved with better design though and do not recommend it
QA
script languages on windows mobile something similar to python nokia try to find something similar to nokia python for windows mobile based devices script interpreter in this case also able to create standalone apps with easy access to all phone interfaces ability to make phone call send sms make photo send file over gprs etc while there is pythonce available for windows mobile it is pure python interpreter and what look for are all those libraries that nokia python has like import camera import messaging ability to control the phone programatically also the bluetooth console of nokia python is great do not want to use net cf as even there afaik to control camera you need to use some indirect methods for example http blogs msdn com marcpe archive aspx appreciate any help you can provide thanks in advance hope there is something was unable to locate via google
ironpython
QA
how can use dll file from python what is the easiest way to use dll file from within python specifically how can this be done without writing any additional wrapper code to expose the functionality to python native python functionality is strongly preferred over using third party library
ctypes can be used to access dlls here is tutorial http docs python org library ctypes html module ctypes
QA
how can use dll file from python what is the easiest way to use dll file from within python specifically how can this be done without writing any additional wrapper code to expose the functionality to python native python functionality is strongly preferred over using third party library
ctypes will be the easiest thing to use but mis using it makes python subject to crashing if you are trying to do something quickly and you are careful it is great would encourage you to check out boost python yes it requires that you write some code and have compiler but you do not actually need to learn to use it and you can get free as in beer compiler from microsoft
QA
how can use dll file from python what is the easiest way to use dll file from within python specifically how can this be done without writing any additional wrapper code to expose the functionality to python native python functionality is strongly preferred over using third party library
for ease of use ctypes is the way to go the following example of ctypes is from actual code have written in python this has been by far the easiest way have found for doing what you ask import ctypes load dll into memory hlldll ctypes windll pcomm ehlapi dll set up prototype and parameters for the desired function call hllapi hllapiproto ctypes winfunctype ctypes int return type ctypes void parameters ctypes void ctypes void ctypes void thru hllapiparams actually map the call hllapi to python name hllapi hllapiproto hllapi hlldll hllapiparams this is how you can actually call the dll function set up the variables and call the python name with them ctypes int ctypes char sessionvar ctypes int ctypes int hllapi ctypes byref ctypes byref ctypes byref the ctypes stuff has all the type data types int char short void and so on and can pass by value or reference it can also return specific data types although my example does not do that the hll api returns values by modifying variable passed by reference in terms of the specific example shown above ibm ehllapi is fairly consistent interface all calls pass four void pointers ehllapi sends the return code back through the fourth parameter pointer to an int so while specify int as the return type can safely ignore it as per ibm documentation here in other words the variant of the function would be int hllapi void void void void this makes for single simple ctypes function able to do anything the ehllapi library provides but it is likely that other libraries will need separate ctypes function set up per library function the return value from winfunctype is function prototype but you still have to set up more parameter information over and above the types each tuple in hllapiparams has parameter direction input output and so on parameter name and default value see the ctypes doco for details once you have the prototype and parameter information you can create python callable hllapi with which to call the function you simply create the needed variable through in my case and call the function with them
QA
why will not django admin application work have just started playing with django and am loosely following the tutorial with my own set of basic requirements the models have sketched out so far are lot more comprehensive than the tutorial but they compile fine otherwise everything should have been the same my problem is with the admin application can log into it and view the editable models but when click on model or any of the change add buttons get this is the exact error get page not found request method get request url http localhost admin auth user add app you model you auth not found these are the relevant files and what is in them urls py from django conf urls defaults import uncomment the next two lines to enable the admin from django contrib import admin admin autodiscover urlpatterns patterns example daso include daso foo urls uncomment the admin doc line below and add django contrib admindocs to installed apps to enable admin documentation admin doc include django contrib admindocs urls uncomment the next line to enable the admin admin admin site root admin py from daso clients models import person client contact from django contrib import admin admin site register person admin site register client admin site register contact models py will just show one model class client person relationships models manytomanyfield contact through relationship null true disabilities models manytomanyfield disability related name disability null true medical issues models manytomanyfield medicalissue related name medical issue null true medicare num models charfield max length blank true insurance models onetoonefield insurance null true blank true medications models manytomanyfield medication through medication details null true def unicode self client you client id self id name self first name self last name return client settings py installed apps django contrib auth django contrib contenttypes django contrib sessions django contrib sites django contrib admin daso clients middleware classes django middleware common commonmiddleware django contrib sessions middleware sessionmiddleware django contrib auth middleware authenticationmiddleware those should be the relevant files sections of files if anyone has an idea about why am getting please enlighten me note when pasting in here installed apps had the last apps tabbed instead of spaced and when reloading the admin page it worked for half second then again strange ideas
it is because you left out in urls py change the admin line to the following admin admin site root checked this on my server and got the same error with your line from urls py
QA
append vs extend what is the difference between the list methods append and extend
append appends single element extend appends list of elements note that if you pass list to append it still adds one element append
QA
append vs extend what is the difference between the list methods append and extend
append adds an element to list extend concatenates the first list with another list or another iterable not necessarily list li mpilgrim example li mpilgrim example li append new li mpilgrim example new li insert new li new mpilgrim example new li extend two elements li new mpilgrim example new two elements from dive into python
QA
append vs extend what is the difference between the list methods append and extend
append appends object at end append print gives you extend extends list by appending elements from the iterable extend print gives you
QA
lua as general purpose scripting language when see lua the only thing ever read is great for embedding fast lightweight and more often than anything else world of warcraft or in short wow why is it limited to embedding the whole thing into another application why not write general purpose scripts like you do with python or perl lua seems to be doing great in aspects like speed and memory usage the fastest scripting language afaik so why is it that never see lua being used as desktop scripting language to automate tasks for example renaming bunch of files download some files from the web webscraping is it the lack of the standard library
lua is cool language light weight and extremely fast but the point is is performance so important for those tasks you mentioned renaming bunch of files download some files from the web webscraping you write those programs once and run them once too maybe why do you care about performance so much for run once program for example cost hours to write program to handle data once the program will take hour to run cost minute to write python program to handle data once the program will take hours to run if you choose the first you save the time to run the program but you cost your time to develop the program on the other hand if you choose the second you waste time to run the program but you can do other things when the program is running how about play world of warcraft kill monsters with your warlock eat my that is it although lua is not so difficult to write everything about lua is designed to be efficient and what is more there are little modules for lua but there are so many modules for python you do not want to port library for lua just for run once program do you instead choose python and use those module to achieve your task easily might be better idea fyi actually have tried to use lua to do webscraping but finally realized do not have to care so much about language performance the bottleneck of webscraping is not on the performance of the language the bottleneck is on network html parsing and multitasking all have to do is make sure the program works and find the bottleneck finally chose python rather than lua there is so many excellent python modules have no reason to build my own according to my experience about webscraping chose twisted for network and lxml for html parsing as the backend of my webscraping program have wrote an article for an introduction to this technology the best choice to grab data from websites python twisted lxml hope this is helpful
QA
append vs extend what is the difference between the list methods append and extend
good answers but do not forget any iterable will do for extend not just list extend xrange
QA
os determine trash location for given path simply moving the file to trash will not work as if the file os on an external drive it will move the file to the main system drive also there are other conditions like files on external drives get moved to volumes trash or whatever the current user id is given file or folder path what is the correct way to determine the trash folder imagine the language is pretty irrelevant but intend to use python
based upon code from http www cocoadev com index pl movetotrash have came up with the following def get trash path input file path file os path split input file if path startswith volumes volumes drivename trashes uid path split os path sep is drive name is empty is volumes trash path os path join volumes trashes str os getuid if not os path isdir trash path raise ioerror volume appears to be network drive could not be found trash path else trash path os path join os getenv home trash return trash path fairly basic and there is few things that have to be done seperatly particularly checking if the filename already exist in trash to avoid overwriting and the actual moving to trash but it seems to cover most things internal external and network drives update wanted to trash file in python script so re implemented dave dribin solution in python from appkit import nsurl from scriptingbridge import sbapplication def trashpath path trashes path using the finder via os scripting bridge targetfile nsurl fileurlwithpath path finder sbapplication applicationwithbundleidentifier com apple finder items finder items objectatlocation targetfile items delete usage is simple trashpath tmp examplefile
QA
finding invocations of certain function in file using python need to find all occurrences of function call in file using python and extract the arguments for each call am playing with the pygccxml package and extracting the arguments given string with the function call is extremely easy from pygccxml declarations import call invocation def test is call invocation call if call invocation is call invocation call print call invocation name call for arg in call invocation args call print arg else print not function invocation what could not find is way of getting the calls parsing file from pygccxml import parser from pygccxml import declarations decls parser parse main cpp is there way to find the calls to certain function using the pygccxml package or maybe that package is an overkill for what am trying to do and there is much simpler way finding the function calls with regular expression is am afraid much trickier than it might look at first sight
xml gcc cannot do that because it only reports the data types and function signatures it ignores the function bodies to see that create cc void foo void bar foo and then run gccxml cc fxml xml look at the generated xml to see that the only mentioning of foo or its id is in the declaration of foo an alternative might be available in codeviz http www csn ul ie mel projects codeviz it consists of patch to gcc that generates call dependency information plus some perl scripts that generate graphviz input the latter you can safely ignore as yet another alternative which does not need gcc modifications you could copy the approach from egypt http www gson org egypt this parses gcc rtl dumps it should work with any recent gcc however it might be that you do not get calls to inline functions in any case with these approaches you will not get calls to macros but that might be actually the better choice
QA
how can add post install scripts to easy install setuptools distutils would like to be able to add hook to my setup py that will be run post install either when easy install ing or when doing python setup py install in my project pysmell have some support files for vim and emacs when user installs pysmell the usual way these files get copied in the actual egg and the user has to fish them out and place them in his vim or emacs directories what want is either asking the user post installation where would he like these files copied or even just message printing the location of the files and what should he do with them what is the best way to do this thanks my setup py looks like so usr bin env python coding utf from setuptools import setup version import pysmell pysmell pysmell version setup name pysmell version version description an autocompletion library for python author orestis markou author email orestis orestis gr packages pysmell entry points console scripts pysmell pysmell pysmell main data files vim pysmell vim emacs pysmell el include package data true keywords vim autocomplete url http code google com pysmell long description pysmell is python ide completion helper it tries to statically analyze python source code without executing it and generates information about project structure that ide tools can use the first target is vim because that is what am using and because its completion mechanism is very straightforward but it is not limited to it classifiers development status production stable environment console intended audience developers license osi approved bsd license operating system os independent programming language python topic software development topic utilities topic text editors edit here is stub which demonstrates the python setup py install from setuptools command install import install as install class install install def run self install run self print post install message setup cmdclass install install no luck with the easy install route yet
it depends on how the user installs your package if the user actually runs setup py install it is fairly easy just add another subcommand to the install command say install vim whose run method will copy the files you want in the places where you want them you can add your subcommand to install sub commands and pass the command into setup if you want post install script in binary it depends on the type of binary you are creating for example bdist rpm bdist wininst and bdist msi have support for post install scripts because the underlying packing formats support post install scripts bdist egg does not support post install mechanism by design http bugs python org setuptools issue
QA
how to configure the import path in visual studio ironpython projects have built the ironpythonintegration solution that comes with the visual studio sdk as explained at http www izume com integrating ironpython with visual studio and can now use ironpython projects inside visual studio however to let python file import from the standard library need to include these two lines first import sys sys path append python lib and similarly for any other folders want to be able to import from does anyone know way to set up import paths so that all ironpython projects automatically pick them up
set the environment variable ironpythonpath in your operating system to python lib or anywhere else you need
QA
what python bindings are there for cvs or svn once did cursory search and found no good cvs bindings for python wanted to be able to write helper scripts to do some fine grained manipulation of the repository and projects in it had to resort to using popen and checking stdout and stderr and then parsing those it was messy and error prone are there any good quality modules for cvs integration for python which module do you prefer and why while am at it is there good subversion integration module for python my understanding is that subversion has great api for such things
for cvs pycvs may be worth look for svn there is pysvn which is pretty good
QA
lua as general purpose scripting language when see lua the only thing ever read is great for embedding fast lightweight and more often than anything else world of warcraft or in short wow why is it limited to embedding the whole thing into another application why not write general purpose scripts like you do with python or perl lua seems to be doing great in aspects like speed and memory usage the fastest scripting language afaik so why is it that never see lua being used as desktop scripting language to automate tasks for example renaming bunch of files download some files from the web webscraping is it the lack of the standard library
think the answer about it being marketing thing is probably correct along with the lack of large set of libraries to choose from would like to point out another case of this ruby ruby is meant to be general purpose scripting language the problem is that since ruby on rails has risen to be so popular it is becoming hard to find something that is unrelated to rails am afraid lua will suffer this as well being popular because of few major things using it but never able to break free of that stigma
QA
lua as general purpose scripting language when see lua the only thing ever read is great for embedding fast lightweight and more often than anything else world of warcraft or in short wow why is it limited to embedding the whole thing into another application why not write general purpose scripts like you do with python or perl lua seems to be doing great in aspects like speed and memory usage the fastest scripting language afaik so why is it that never see lua being used as desktop scripting language to automate tasks for example renaming bunch of files download some files from the web webscraping is it the lack of the standard library
lua has fewer libraries than python but be sure to have look at luaforge it has lot of interesting libs like luacurl wxlua or getopt then visit luarocks the package management system for lua with it you can search and install most mature lua modules with dependencies it feels like rubygems or aptitude the site lua users org has lot of interesting resources too like tutorials or the lua wiki what like about lua is not its speed it is its minimal core language flexibility and extensibility that said would probably use python for the tasks you mentionned because of the larger community doing such things in python
QA
looking generic python script to add field and populate the field with conditions am looking for script to allow users to add text field to dbf table landuse categories and allow them to input update the rows basing on what values in the gridcode numeric categories field they think should be assigned into text categories if gridcode value is the corresponding field value of landuse landclass is forest etc is there such script in existence or do you have something similar that can customise to create new script the script will accept users interactive input as parameters passed into the script sincerely david
when you say dbf table are you referring to esri shape file dbf files which are in fact dbase files if so you could implement such thing pretty easily with the python wrapper for shapelib which also supports dbf files
QA
what python bindings are there for cvs or svn once did cursory search and found no good cvs bindings for python wanted to be able to write helper scripts to do some fine grained manipulation of the repository and projects in it had to resort to using popen and checking stdout and stderr and then parsing those it was messy and error prone are there any good quality modules for cvs integration for python which module do you prefer and why while am at it is there good subversion integration module for python my understanding is that subversion has great api for such things
tailor python program which let us different version control systems interoperate simply calls the external programs cvs and svn when working with repositories of those formats this seems pretty ugly but reduces tailor dependencies from requires bindings to requires working system
QA
bizarre python importerror here is my setup mac running os tiger windows xp running in virtual machine parallels windows xp has my mac home directory mapped as network drive have two files in directory of my mac home directory foo py pass test py import foo if run test py from within my virtual machine by typing python test py get this traceback most recent call last file test py line in module import foo importerror no module named foo if try to import foo from the console running python under windows from the same directory all is well python apr msc bit intel on win type help copyright credits or license for more information import foo if run test py with mac python all is well if copy test py and foo py to different directory can run test py under windows without problems there is an init py in the original directory but it is empty furthermore copying it with the other files does not break anything in the previous paragraph there are no python related environment variables set any ideas
as random guess are the permissions on foo py accessable from the windows client eg try opening with notepad from the virtual machine if that is ok try running python test py and looking at the output alternatively set pythonverbose this should list all the places it tries to import foo from comparing it with similar trace on the working machine may give some further clues
QA
in python is there concise way of comparing whether the contents of two text files are the same do not care what the differences are just want to know whether the contents are different
the low level way from future import with statement with open filename as with open filename as if read read the high level way import filecmp if filecmp cmp filename filename shallow false
QA
in python is there concise way of comparing whether the contents of two text files are the same do not care what the differences are just want to know whether the contents are different
open filename read open filename read print
QA
in python is there concise way of comparing whether the contents of two text files are the same do not care what the differences are just want to know whether the contents are different
if you are going for even basic efficiency you probably want to check the file size first if os path getsize filename os path getsize filename if open filename read open filename read files are the same this saves you reading every line of two files that are not even the same size and thus cannot be the same even further than that you could call out to fast md sum of each file and compare those but that is not in python so will stop here
QA
in python is there concise way of comparing whether the contents of two text files are the same do not care what the differences are just want to know whether the contents are different
for larger files you could compute md or sha hash of the files
QA
in python is there concise way of comparing whether the contents of two text files are the same do not care what the differences are just want to know whether the contents are different
would use hash of the file contents using md import hashlib def checksum md hashlib md md update open read return md hexdigest def is contents same return checksum checksum if not is contents same foo txt bar txt print the contents are not the same
QA
can you do linq like queries in language like python or boo take this simple linq query and imagine that db numbers is an sql table with one column number var result from in db numbers where number select number this will run very efficiently in because it generates an sql query something like select number from numbers where number what it does not do is select all the numbers from the database and then filter them in as it might appear to do at first python supports similar syntax result number for in numbers if number but it the if clause here does the filtering on the client side rather than the server side which is much less efficient is there something as efficient as linq in python am currently evaluating python vs ironpython vs boo so an answer that works in any of those languages is fine
boo supports list generator expressions using the same syntax as python for more information on that check out the boo documentation on generator expressions and list comprehensions
QA
in python is there concise way of comparing whether the contents of two text files are the same do not care what the differences are just want to know whether the contents are different
since cannot comment on the answers of others will write my own if you use md you definitely must not just md update read since you will use too much memory def get file md chunk size hashlib md while true chunk read chunk size if not chunk break update chunk return hexdigest
QA
tiny python executable plan to use pyinstaller to create stand alone python executable pythoninstaller comes with built in support for upx and uses it to compress the executable but they are still really huge about mb is there any way to create even smaller python executables for example using shrinked python dll or something similiar
if you recompile pythonxy dll you can omit modules that you do not need going by size stripping off the unicode database and the cjk codes creates the largest code reduction this of course assumes that you do not need these remove the modules from the pythoncore project and also remove them from pc config
QA
how to embed tag within url templatetag in django template how do embed tag within url templatetag in django template django python in views py def home page view request nup homepage named url pattern string for my home page view variables requestcontext request nup nup return render to response home page html variables in home page html the following nup homepage nup homepage is displayed as nup homepage named url pattern string for my home page view and the following url named pattern works as expected url template tag for nup homepage url named url pattern string for my home page view and is displayed as url template tag for nup homepage myhomepage but when nup homepage is embedded within url as follows url template tag for nup homepage url nup homepage this results in template syntax error templatesyntaxerror at myhomepage could not parse the remainder from request method get request url http localhost myhomepage exception type templatesyntaxerror exception value could not parse the remainder from exception location python lib site packages django template init py in init line python executable python python exe python version was expecting url nup homepage to resolve to url named url pattern string for my home page view at runtime and be displayed as myhomepage are embedded tags not supported in django is it possible to write custom url template tag with embedded tags support to make this work url nup homepage
that is seems way too dynamic you are supposed to do url named url pattern string for my home page view and leave it at that dynamically filling in the name of the url tag is frankly little odd if you want to use any of large number of different url tags you would have to do something like this if tagoption href url named url text endif which seems long winded because again the dynamic thing you are trying to achieve seems little odd if you have something like families or clusters of pages perhaps separate template directories would be way to manage this better each of the clusters of pages can inherit from base templates and override small things like this navigation feature to keep all of the pages in the cluster looking similar but having one navigation difference for local home
QA
how to embed tag within url templatetag in django template how do embed tag within url templatetag in django template django python in views py def home page view request nup homepage named url pattern string for my home page view variables requestcontext request nup nup return render to response home page html variables in home page html the following nup homepage nup homepage is displayed as nup homepage named url pattern string for my home page view and the following url named pattern works as expected url template tag for nup homepage url named url pattern string for my home page view and is displayed as url template tag for nup homepage myhomepage but when nup homepage is embedded within url as follows url template tag for nup homepage url nup homepage this results in template syntax error templatesyntaxerror at myhomepage could not parse the remainder from request method get request url http localhost myhomepage exception type templatesyntaxerror exception value could not parse the remainder from exception location python lib site packages django template init py in init line python executable python python exe python version was expecting url nup homepage to resolve to url named url pattern string for my home page view at runtime and be displayed as myhomepage are embedded tags not supported in django is it possible to write custom url template tag with embedded tags support to make this work url nup homepage
maybe you could try passing the final url to the template instead something like this from django core urlresolvers import reverse def home page view request nup homepage reverse named url pattern string for my home page view variables requestcontext request nup nup return render to response home page html variables then in the template the nup homepage should the the url itself
QA
converting datetime to posix time how do convert datetime or date object into posix timestamp in python there are methods to create datetime object out of timestamp but do not seem to find any obvious ways to do the operation the opposite way
import time datetime datetime datetime now print time mktime timetuple
QA
how do keep python print from adding newlines or spaces in python if say print get the letter and newline if say print get the letter and no newline if say print print get the letter space and the letter how can prevent python from printing the space the print statements are different iterations of the same loop so cannot just use the operator
you can use sys stdout write sys stdout write
QA
how do keep python print from adding newlines or spaces in python if say print get the letter and newline if say print get the letter and no newline if say print print get the letter space and the letter how can prevent python from printing the space the print statements are different iterations of the same loop so cannot just use the operator
just comment in python you will use print end to suppress the endline terminator and print sep to suppress the whitespace separator between items
QA
user authentication in pylons authkit am trying to create web application using pylons and the resources on the web point to the pylonsbook page which is not of much help want authentication and authorisation and is there anyway to setup authkit to work easily with pylons tried downloading the simplesitetemplate from the cheeseshop but was not able to run the setup app command it throws up an error file home cnu env lib python site packages sqlalchemy py egg sqlalchemy schema py line in call table metadata tables key attributeerror module object has no attribute tables use pylons rc sqlalchemy authkit
check out this tutorial http wiki pylonshq com display pylonscookbook authkit usersfromdatabase with sqlalchemy and sqlalchemymanager
QA
how do keep python print from adding newlines or spaces in python if say print get the letter and newline if say print get the letter and no newline if say print print get the letter space and the letter how can prevent python from printing the space the print statements are different iterations of the same loop so cannot just use the operator
greg is right you can use sys stdout write perhaps though you should consider refactoring your algorithm to accumulate list of whatevers and then lst print join lst
QA
in python is there concise way of comparing whether the contents of two text files are the same do not care what the differences are just want to know whether the contents are different
this is functional style file comparison function it returns instantly false if the files have different sizes otherwise it reads in kib block sizes and returns false instantly upon the first difference from future import with statement import os import itertools functools operator def filecmp filename filename do the two files have exactly the same contents with open filename rb as fp open filename rb as fp if os fstat fp fileno st size os fstat fp fileno st size return false different sizes not equal fp reader functools partial fp read fp reader functools partial fp read cmp pairs itertools izip iter fp reader iter fp reader inequalities itertools starmap operator ne cmp pairs return not any inequalities if name main import sys print filecmp sys argv sys argv just different take
QA
django arbitrary number of unnamed urls py parameters have django model with large number of fields and table rows to facilitate human readable urls and the ability to break down the large list into arbitrary sublists would like to have url that looks like this browse name value name value etc where name maps to model attribute and value is the search criteria for that attribute each name will be treated like category to return subsets of the model instances where the categories match now this could be handled with get parameters but prefer more readable urls for both the user sake and the search engines these urls subsets will be embedded on each page that displays this model so it seems worth the effort to make pretty urls ideally each name value pair will be passed to the view function as parameter named name name etc however do not believe it is possible to defined named patterns via regex matched text am wrong there so it seems need to do something like this urlpatterns patterns url browse app views view name model browse it seems this should match any sets of two name value pairs while it matches it successfully it only passes the last name value pair as parameters to the view function my guess is that each match is overwriting the previous match under the guess that the containing is causing it tried simple repeating pattern instead urlpatterns patterns url browse app views view name model browse and got the same problem but this time args only includes the last matched pattern is this limitation of django url dispatcher and or python regex support it seems either of these methods should work is there way to achieve this without hardcoding each possible model attribute in the url as an optional pattern
same answer came to me while reading the question believe model browse view is the best way to sort the query parameters and use it as generic router
QA
how to get function name as string in python in python how do get function name as string without calling the function def my function pass print get function name as string my function my function is not in quotes should output my function is this available in python if not any idea how to write get function name as string in python
my function name using name is the preferred method as it applies uniformly unlike func name it works on built in functions as well import time time time func name traceback most recent call last file stdin line in attributeerror builtin function or method object has no attribute func name time time name time also the double underscores indicate to the reader this is special attribute as bonus classes and modules have name attribute too so you only have remember one special name
QA
how do keep python print from adding newlines or spaces in python if say print get the letter and newline if say print get the letter and no newline if say print print get the letter space and the letter how can prevent python from printing the space the print statements are different iterations of the same loop so cannot just use the operator
python sep gcc on linux type help copyright credits or license for more information import sys print hello print there hello there print hello sys stdout softspace false print there hellothere but really you should use sys stdout write directly
QA
how do keep python print from adding newlines or spaces in python if say print get the letter and newline if say print get the letter and no newline if say print print get the letter space and the letter how can prevent python from printing the space the print statements are different iterations of the same loop so cannot just use the operator
for completeness one other way is to clear the softspace value after performing the write import sys print hello sys stdout softspace print world print prints helloworld using stdout write is probably more convenient for most cases though
QA
python re findall with groupdicts kind of wish that there were version of re findall that returned groupdicts instead of just groups am missing some simple way to accomplish the same result does anybody know of reason that this function does not exist
you could use the finditer function this will give you sequence of match objects so you can get the groupdict for each with groupdict for in regex finditer search string
QA
determine if named parameter was passed would like to know if it is possible to determine if function parameter with default value was passed in python for example how does dict pop work pop test traceback most recent call last file stdin line in module keyerror pop dictionary is empty pop test none pop test pop test notimplemented notimplemented how does the pop method determine that the first time default return value was not passed is this something that can only be done in thanks
you can do it like this def isdefarg args if len args print len args arguments else print no arguments isdefarg isdefarg none isdefarg see the python documentation on calls for full information
QA
determine if named parameter was passed would like to know if it is possible to determine if function parameter with default value was passed in python for example how does dict pop work pop test traceback most recent call last file stdin line in module keyerror pop dictionary is empty pop test none pop test pop test notimplemented notimplemented how does the pop method determine that the first time default return value was not passed is this something that can only be done in thanks
guess you mean keyword argument when you say named parameter dict pop does not accept keyword argument so this part of the question is moot pop test none traceback most recent call last file stdin line in module typeerror pop takes no keyword arguments that said the way to detect whether an argument was provided is to use the args or kwargs syntax for example def foo first rest if len rest raise typeerror foo expected at most arguments got len rest print first first if rest print second rest with some work and using the kwargs syntax too it is possible to completely emulate the python calling convention where arguments can be either provided by position or by name and arguments provided multiple times by position and name because an error
QA
determine if named parameter was passed would like to know if it is possible to determine if function parameter with default value was passed in python for example how does dict pop work pop test traceback most recent call last file stdin line in module keyerror pop dictionary is empty pop test none pop test pop test notimplemented notimplemented how does the pop method determine that the first time default return value was not passed is this something that can only be done in thanks
def one two print wonder if two has been passed or not if this is the exact meaning of your question think that there is no way to distinguish between that was in the default value and that has been passed did not find how to accomplish such distinction even in the inspect module
QA
determine if named parameter was passed would like to know if it is possible to determine if function parameter with default value was passed in python for example how does dict pop work pop test traceback most recent call last file stdin line in module keyerror pop dictionary is empty pop test none pop test pop test notimplemented notimplemented how does the pop method determine that the first time default return value was not passed is this something that can only be done in thanks
am not certain if fully understand what is it you want however def fun arg ellipsis if arg is ellipsis print no arg provided else print arg provided repr arg does that do what you want if not then as others have suggested you should declare your function with the args kwargs syntax and check in the kwargs dict for the parameter existence
QA
browser based application or stand alone gui app am sure this has been asked before but cannot find it what are the benefits limitations of using browser based interface for stand alone application vs using normal gui framework am working on python program currently implement with wxpython for the gui the application is simply user entry forms and dialogs am considering moving to pyqt because of the widgets it has for future expansion then realized could probably just use browser to do much of the same stuff the application currently does not require internet access though it is possibility in the future was thinking of using karrigell for the web framework if go browser based edit for clarification as of right now the application would be browser based not web based all the information would be stored locally on the client computer no server calls would need to be made and no internet access required it may come later though it would simply be browser gui instead of wxpython pyqt gui hope that makes sense
the obvious advantages to browser based you can present the same ui regardless of platform you can upgrade the application easily and all users have the same version of the app running you know the environment that your application will be running in the server hardware os which makes for easier testing and support compared to the multitude of operating system hardware configurations that gui app will be installed on and for gui based some applications image editing arguably work better in native gui application does not require network access also see my comments on this question cross platform guis are an age old problem qt gtk wxwindows java awt java swing xul they all suffer from the same problem the resulting gui does not look native on every platform worse still every platform has slightly different look and feel so even if you were somehow able to get toolkit that looked native on every platform you would have to somehow code your app to feel native on each platform it comes down to decision do you want to minimise development effort and have gui that does not look and feel quite right on each platform or do you want to maximise the user experience if you choose the second option you will need to develop common backend and custom ui for each platform edit or use web application another thought just had you also need to consider the kind of data that your application manipulates and where it is stored and how the users will feel about that people are obviously okay having their facebook profile data stored on webserver but they might feel differently if you are writing finance application like myob and you want to store all their personal financial details on your server you might be able to get that to work but it would require lot of effort to implement the required security and to assure the userbase that their data is safe in that situation you might decide that the overall effort is lower if you go with native gui app
QA
browser based application or stand alone gui app am sure this has been asked before but cannot find it what are the benefits limitations of using browser based interface for stand alone application vs using normal gui framework am working on python program currently implement with wxpython for the gui the application is simply user entry forms and dialogs am considering moving to pyqt because of the widgets it has for future expansion then realized could probably just use browser to do much of the same stuff the application currently does not require internet access though it is possibility in the future was thinking of using karrigell for the web framework if go browser based edit for clarification as of right now the application would be browser based not web based all the information would be stored locally on the client computer no server calls would need to be made and no internet access required it may come later though it would simply be browser gui instead of wxpython pyqt gui hope that makes sense
browsers can be accessed anywhere with internet and you deploy it on the server the desktop app has to be deployed to their computers and each computer somehow has its own uniqueness even with same os and same version this could bring you lots of hassles go for web
QA
browser based application or stand alone gui app am sure this has been asked before but cannot find it what are the benefits limitations of using browser based interface for stand alone application vs using normal gui framework am working on python program currently implement with wxpython for the gui the application is simply user entry forms and dialogs am considering moving to pyqt because of the widgets it has for future expansion then realized could probably just use browser to do much of the same stuff the application currently does not require internet access though it is possibility in the future was thinking of using karrigell for the web framework if go browser based edit for clarification as of right now the application would be browser based not web based all the information would be stored locally on the client computer no server calls would need to be made and no internet access required it may come later though it would simply be browser gui instead of wxpython pyqt gui hope that makes sense
when it comes to simple data entry using user entry forms would argue that using browser based solution would probably be easier and faster to develop unless your core feature is the interface itself if it is core business function do it yourself no matter what see in defense of not invented here syndrome from joel on software feel that the browser will be able to perform the form rendering and handling better than having to develop gui from scratch also not to mention the it would take much longer time to code gui as opposed to generating html forms and processing them after they are posted by the browser what found in the past was that was asked by friend to write an application to enter results from survey at first was writing java applet to display the survey itself with all the radio boxes when it hit me that would be better off writing simple http server which would generate the forms and process them what it really comes down is to whether you are either developing the user interface data entry application if you are making data entry application then leave the user interface to the browser and focus on your core functionality
QA
browser based application or stand alone gui app am sure this has been asked before but cannot find it what are the benefits limitations of using browser based interface for stand alone application vs using normal gui framework am working on python program currently implement with wxpython for the gui the application is simply user entry forms and dialogs am considering moving to pyqt because of the widgets it has for future expansion then realized could probably just use browser to do much of the same stuff the application currently does not require internet access though it is possibility in the future was thinking of using karrigell for the web framework if go browser based edit for clarification as of right now the application would be browser based not web based all the information would be stored locally on the client computer no server calls would need to be made and no internet access required it may come later though it would simply be browser gui instead of wxpython pyqt gui hope that makes sense
benefits of browser based interface easier to manage no installation required on user machines upgrades need only be performed on server side and are immediately available to all users data backup can be performed on single machine as data will not be spread out across multiple clients application can be accessed from any machine with browser can easily support multiple platforms consistently memory and cpu requirements may be considerably less on the client side as intensive operations can be performed on the server increased security data is stored on single server instead of multiple client machines and access can be better controlled many other benefits of centralized environment including logging data entered from multiple sources can immediately be available from other clients etc in my experience it is often easier to debug and faster to develop web based solutions benefits of gui based interface may be easier to design more responsive fluid interface can take advantage of os specific functionality that may not be available via browser does not necessarily require network access do not need to worry about browser compatibility issues no single point of failure if server goes down or becomes unavailable