prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
how to get instance variables in python is there built in method in python to get an array of all class instance variables for example if have this code class hi def init self self ii foo self okay bar is there way for me to do this mystery method hi ii okay thanks guys edit originally had asked for class variables erroneously thanks to all who brought this to my attention
although not directly an answer to the op question there is pretty sweet way of finding out what variables are in scope in function take look at this code def sqrt return sqrt func code co varnames sqrt the func code attribute has all kinds of interesting things in it it allows you todo some cool stuff here is an example of how have have used this def exec command self cmd message sig def message message self link process self link recieved message message self exec command def error message self printer printinfo message def set usrlist message self client connected users message def chatmessage message self printer printinfo message if not locals has key cmd return cmd locals cmd try if sig in cmd func code co varnames and message in cmd func code co varnames cmd message sig elif message in cmd func code co varnames cmd message else cmd except exception print error print error print error proccessing cmd name print message message print sig sig print error
QA
is there any way to do http put in python need to upload some data to server using http put in python from my brief reading of the urllib docs it only does http post is there any way to do an http put in python
have you taken look at put py have used it in the past you can also just hack up your own request with urllib
QA
using python ftplib to get directory listing portably you can use ftplib for full ftp support in python however the preferred way of getting directory listing is file ftplib example py import ftplib ftp ftplib ftp www python org ftp login anonymous ftplib example data ftp dir data append ftp quit for line in data print line which yields python ftplib example py total drwxrwxr root sep drwxrwxr root sep drwxrwxr root sep rcs lrwxrwxrwx root bin jun readme welcome message drwxr xr root wheel may bin drwxr sr root jun dev drwxrwxr root feb dup drwxr xr root wheel may etc guess the idea is to parse the results to get the directory listing however this listing is directly dependent on the ftp server way of formatting the list it would be very messy to write code for this having to anticipate all the different ways ftp servers might format this list is there portable way to get an array filled with the directory listing the array should only have the folder names
try to use ftp nlst dir however note that if the folder is empty it might throw an error files try files ftp nlst except ftplib error perm resp if str resp no files found print no files in this directory else raise for in files print
QA
is there any way to do http put in python need to upload some data to server using http put in python from my brief reading of the urllib docs it only does http post is there any way to do an http put in python
you can of course roll your own with the existing standard libraries at any level from sockets up to tweaking urllib http pycurl sourceforge net pycurl is python interface to libcurl libcurl is free and easy to use client side url transfer library supports http put the main drawback with pycurl is that it is relative thin layer over libcurl without any of those nice pythonic class hierarchies this means it has somewhat steep learning curve unless you are already familiar with libcurl api
QA
is there any way to do http put in python need to upload some data to server using http put in python from my brief reading of the urllib docs it only does http post is there any way to do an http put in python
you should have look at the httplib module it should let you make whatever sort of http request you want
QA
how do find out the size of canvas item in python tkinter want to create some text in canvas mytext self canvas create text anchor nw text test now how do find the width and height of mytext
bounds self canvas bbox mytext returns tuple like width bounds bounds height bounds bounds see the tkinter reference
QA
using python ftplib to get directory listing portably you can use ftplib for full ftp support in python however the preferred way of getting directory listing is file ftplib example py import ftplib ftp ftplib ftp www python org ftp login anonymous ftplib example data ftp dir data append ftp quit for line in data print line which yields python ftplib example py total drwxrwxr root sep drwxrwxr root sep drwxrwxr root sep rcs lrwxrwxrwx root bin jun readme welcome message drwxr xr root wheel may bin drwxr sr root jun dev drwxrwxr root feb dup drwxr xr root wheel may etc guess the idea is to parse the results to get the directory listing however this listing is directly dependent on the ftp server way of formatting the list it would be very messy to write code for this having to anticipate all the different ways ftp servers might format this list is there portable way to get an array filled with the directory listing the array should only have the folder names
there is no standard for the layout of the list response you would have to write code to handle the most popular layouts would start with linux ls and windows server dir formats there is lot of variety out there though fall back to the nlst method returning the result of the nlst command if you cannot parse the longer list for bonus points cheat perhaps the longest number in the line containing known file name is its length
QA
is there any way to do http put in python need to upload some data to server using http put in python from my brief reading of the urllib docs it only does http post is there any way to do an http put in python
import urllib opener urllib build opener urllib httphandler request urllib request http example org data your put data request add header content type your contenttype request get method lambda put url opener open request
QA
python array versus numpy array if you are creating array in python is there any benefit to using the numpy package
it all depends on what you plan to do with the array if all you are doing is creating arrays of simple data types and doing the array module will do just fine if on the other hand you want to do any kind of numerical calculations the array module does not provide any help with that numpy and scipy give you wide variety of operations between arrays and special functions that are useful not only for scientific work but for things like advanced image manipulation or in general anything where you need to perform efficient calculations with large amounts of data numpy is also much more flexible it supports arrays of any type of python objects and is also able to interact natively with your own objects if they conform to the array interface
QA
how do overlap widgets with the tkinter pack geometry manager want to put canvas with an image in my window and then want to pack widgets on top of it so the canvas acts as background is it possible to have two states for the pack manager one for one set of widgets and another for another set
the answer to your specific question is no you cannot have two states or otherwise use pack two different ways in the same parent however what think you want to accomplish is simple use the built in features of the canvas to create an image item that is part of the canvas then pack things into the canvas as if it were frame you can accomplish similar thing by creating label widget with an image then pack your other widgets into the label one advantage to using canvas is you can easily tile an image to fill the whole canvas with repeating background image so as the window grows the image will continue to fill the window of course you can just use sufficiently large original image
QA
how do overlap widgets with the tkinter pack geometry manager want to put canvas with an image in my window and then want to pack widgets on top of it so the canvas acts as background is it possible to have two states for the pack manager one for one set of widgets and another for another set
believe that bryan answer is probably the best general solution however you may also want to look at the place geometry manager the place geometry manager let us you specify the exact size and position of the widget which can get tedious quickly but will get the job done
QA
how do overlap widgets with the tkinter pack geometry manager want to put canvas with an image in my window and then want to pack widgets on top of it so the canvas acts as background is it possible to have two states for the pack manager one for one set of widgets and another for another set
not without swapping widget trees in and out which do not think can be done cleanly with tk other toolkits can do this little more elegantly com vb mfc can do this with an activex control you can hide show multiple activex controls in the same region any of the containers will let you do this by changing the child around if you are doing windows specific program you may be able to accomplish it this way qt will also let you do this in similar manner gtk is slightly harder
QA
does anyone know of widget for desktop toolkit gtk qt wx for displaying map of us states am specifically looking for one that let us me display map of us states with each one as it is own object in the sense that can control the color on click and on mouseover of each one individually gtk is my personal preference but at this point would settle for just about anything the application itself will be written in python fwiw
you can use qgraphicsview in pyqt each state is new qgraphicsitem which is either bitmap or path object you just need to provide the outlines or bitmaps and the positions of the states if you have svgs of the states you can use them too there is no generally accepted canvas class for gtk
QA
list all words in dictionary that start with how would go about making program where the user enters string and the program generates list of words beginning with that string ex user abd program abdicate abdomen abduct thanks edit am using python but assume that this is fairly language independent problem
var words from word in dictionary where word key startswith bla bla bla select word
QA
list all words in dictionary that start with how would go about making program where the user enters string and the program generates list of words beginning with that string ex user abd program abdicate abdomen abduct thanks edit am using python but assume that this is fairly language independent problem
try using regex to search through your list of words word and report all matches
QA
list all words in dictionary that start with how would go about making program where the user enters string and the program generates list of words beginning with that string ex user abd program abdicate abdomen abduct thanks edit am using python but assume that this is fairly language independent problem
def main script name for word in open usr share dict words if word startswith name print word if name main import sys main sys argv
QA
list all words in dictionary that start with how would go about making program where the user enters string and the program generates list of words beginning with that string ex user abd program abdicate abdomen abduct thanks edit am using python but assume that this is fairly language independent problem
one of the best ways to do this is to use directed graph to store your dictionary it takes little bit of setting up but once done it is fairly easy to then do the type of searches you are talking about the nodes in the graph correspond to letter in your word so each node will have one incoming link and up to in english outgoing links you could also use hybrid approach where you maintain sorted list containing your dictionary and use the directed graph as an index into your dictionary then you just look up your prefix in your directed graph and then go to that point in your dictionary and spit out all words matching your search criteria
QA
list all words in dictionary that start with how would go about making program where the user enters string and the program generates list of words beginning with that string ex user abd program abdicate abdomen abduct thanks edit am using python but assume that this is fairly language independent problem
use trie add your list of words to trie each path from the root to leaf is valid word path from root to an intermediate node represents prefix and the children of the intermediate node are valid completions for the prefix
QA
list all words in dictionary that start with how would go about making program where the user enters string and the program generates list of words beginning with that string ex user abd program abdicate abdomen abduct thanks edit am using python but assume that this is fairly language independent problem
if you really want to be efficient use suffix trees or suffix arrays wikipedia article your problem is what suffix trees were designed to handle there is even implementation for python here
QA
list all words in dictionary that start with how would go about making program where the user enters string and the program generates list of words beginning with that string ex user abd program abdicate abdomen abduct thanks edit am using python but assume that this is fairly language independent problem
if you need to be really fast use tree build an array and split the words in sets based on the first letter then split each item in based on the second letter then again so if your user types abd you would look for array and get list of all the words starting like that at that point your list should be small enough to pass over to the client and use javascript to filter
QA
list all words in dictionary that start with how would go about making program where the user enters string and the program generates list of words beginning with that string ex user abd program abdicate abdomen abduct thanks edit am using python but assume that this is fairly language independent problem
if you on debian like machine bin bash echo enter word read input grep input usr share dict words takes all of on my
QA
list all words in dictionary that start with how would go about making program where the user enters string and the program generates list of words beginning with that string ex user abd program abdicate abdomen abduct thanks edit am using python but assume that this is fairly language independent problem
egrep read input echo input usr share dict words oh did not see the python edit here is the same thing in python my input raw input enter beginning of word my words open usr share dict words readlines my found words for in my words if len my input my input
QA
list all words in dictionary that start with how would go about making program where the user enters string and the program generates list of words beginning with that string ex user abd program abdicate abdomen abduct thanks edit am using python but assume that this is fairly language independent problem
if you really want speed use trie automaton however something that will be faster than simply scanning the whole list given that the list of words is sorted from itertools import takewhile islice import bisect def prefixes words pfx return list takewhile lambda startswith pfx islice words bisect bisect right words pfx len words note that an automaton is with regard to the size of your dictionary while this algorithm is log and then with regard to the number of strings that actually start with the prefix while the full scan is with
QA
how do use genshi builder to programmatically build an html document recently discovered the genshi builder module it reminds me of divmod nevow stan module how would one use genshi builder tag to build an html document with particular doctype or is this even good thing to do if not what is the right way
genshi builder is for programmatically generating markup streams believe the purpose of it is as backend for the templating language you are probably looking for the templating language for generating whole page you can however do the following import genshi output genshi output doctype html html dtd html en http www org tr html strict dtd see other doctypes here http genshi edgewall org wiki apidocs genshi output genshi output doctype genshi builder doc
QA
py exe generate single executable file thought heard that py exe was able to do this but never figured it out has anyone successfully done this can see your setup py file and what command line options you used basically am thinking of it giving me single executable file that does something like unzips itself to maybe temp and runs
pyinstaller will create single exe file with no dependencies use the onefile option it does this by packing all the needed shared libs into the executable and unpacking them before it runs just as you describe edit py exe also has this feature see minty answer use the version of pyinstaller from svn since the latest release is somewhat outdated it is been working really well for an app which depends on pyqt pyqwt numpy scipy and few more
QA
how would one log into phpbb forum through python script using urllib urllib and clientcookie clientcookie is module for automatic cookie handling http wwwsearch sourceforge net clientcookie encode the data will be sending data urllib urlencode username mandark password deedee and send it and read the page page clientcookie urlopen http www forum com ucp php mode login data output page read the script does not log in but rather seems to get redirected back to the same login page asking it for username and password what am doing wrong any help would be greatly appreciated thanks
have you tried fetching the login page first would suggest using tamper data to have peek at exactly what is being sent when you request the login page and then log in normally using web browser from fresh start with no initial cookies in place so that your script can replicate it exactly that is the approach used when writing the following extracted from script which needs to login to an invision power board forum using cookielib and urllib you may find it useful as reference import cookielib import logging import sys import urllib import urllib cookies cookielib lwpcookiejar opener urllib build opener urllib httpcookieprocessor cookies urllib install opener opener headers user agent mozilla windows you windows nt en gb rv gecko firefox accept text xml application xml application xhtml xml text html text plain image png accept language en gb en accept charset iso utf fetch the login page to set initial cookies urllib urlopen urllib request http www rllmukforum com index php act login code none headers login so we can access the off topic forum login headers headers copy login headers update referer http www rllmukforum com index php act login code content type application www form urlencoded html urllib urlopen urllib request http www rllmukforum com index php act login code urllib urlencode referer http www rllmukforum com index php username rllmuk username password rllmuk password login headers read if the following errors were found in html logging error rllmuk login failed logging info html sys exit
QA
list all words in dictionary that start with how would go about making program where the user enters string and the program generates list of words beginning with that string ex user abd program abdicate abdomen abduct thanks edit am using python but assume that this is fairly language independent problem
if your dictionary is really big would suggest indexing with python text index pylucene note that have never used the python extension for lucene the search would be efficient and you could even return search score also if your dictionary is relatively static you will not even have the overhead of re indexing very often
QA
how do use genshi builder to programmatically build an html document recently discovered the genshi builder module it reminds me of divmod nevow stan module how would one use genshi builder tag to build an html document with particular doctype or is this even good thing to do if not what is the right way
it is not possible to build an entire page using just genshi builder tag you would need to perform some surgery on the resulting stream to insert the doctype besides the resulting code would look horrific the recommended way to use genshi is to use separate template file generate stream from it and then render that stream to the output type you want genshi builder tag is mostly useful for when you need to generate simple markup from within python such as when you are building form or doing some sort of logic heavy modification of the output see documentation for creating and using templates the xml based template language genshi builder api docs if you really want to generate full document using only builder tag this completely untested code could be good starting point from itertools import chain from genshi core import doctype stream from genshi output import doctype from genshi builder import tag as build the page using genshi builder tag page html head title hello world body div body text convert the page element into stream stream page generate chain the page stream with stream containing only an html doctype declaration stream stream chain doctype doctype get html none stream convert the stream to text using the html renderer could also be xml xhtml text etc text stream render html the resulting page will have no whitespace in it it will look normal but you will have hard time reading the source code because it will be entirely on one line implementing appropriate filters to add whitespace is left as an exercise to the reader
QA
how would one log into phpbb forum through python script using urllib urllib and clientcookie clientcookie is module for automatic cookie handling http wwwsearch sourceforge net clientcookie encode the data will be sending data urllib urlencode username mandark password deedee and send it and read the page page clientcookie urlopen http www forum com ucp php mode login data output page read the script does not log in but rather seems to get redirected back to the same login page asking it for username and password what am doing wrong any help would be greatly appreciated thanks
would recommend taking look at the mechanize library it is designed for precisely this type of task it is also far easier than doing it by hand
QA
python when to use file vs open what is the difference between file and open in python when should use which one say am in
you should always use open as the documentation states when opening file it is preferable to use open instead of invoking this constructor directly file is more suited to type testing for example writing isinstance file also file has been removed since python
QA
python when to use file vs open what is the difference between file and open in python when should use which one say am in
functionally the two are the same open will call file anyway so currently the difference is matter of style the python docs recommend using open when opening file it is preferable to use open instead of invoking the file constructor directly the reason is that in future versions they is not guaranteed to be the same open will become factory function which returns objects of different types depending on the path it is opening
QA
python when to use file vs open what is the difference between file and open in python when should use which one say am in
two reasons the python philosophy of there ought to be one way to do it and file is going away file is the actual type using file myfile txt is calling its constructor open is factory function that will return file object in python file is going to move from being built in to being implemented by multiple classes in the io library somewhat similar to java with buffered readers etc
QA
python when to use file vs open what is the difference between file and open in python when should use which one say am in
only ever use open for opening files file is actually being removed in and it is deprecated at the moment they have had sort of strange relationship but file is going now so there is no need to worry anymore the following is from the python docs bracket stuff added by me when opening file it preferable to use open instead of invoking this file constructor directly file is more suited to type testing for example writing isinstance file
QA
python when to use file vs open what is the difference between file and open in python when should use which one say am in
according to mr van rossum although open is currently an alias for file you should use open because this might change in the future
QA
writing to the windows logs in python is it possible to write to the windows logs in python
yes just use windows python extension as stated here import win evtlogutil win evtlogutil reportevent applicationname eventid eventcategory eventtype inserts data sid
QA
py exe generate single executable file thought heard that py exe was able to do this but never figured it out has anyone successfully done this can see your setup py file and what command line options you used basically am thinking of it giving me single executable file that does something like unzips itself to maybe temp and runs
the way to do this using py exe is to use the bundle files option in your setup py file for single file you will want to set bundle files to compressed to true and set the zipfile option to none that way it creates one compressed file for easy distribution here is more complete description of the bundle file option quoted directly from the py exe site using bundle files and zipfile an easier and better way to create single file executables is to set bundle files to or and to set zipfile to none this approach does not require extracting files to temporary location which provides much faster program startup valid values for bundle files are default do not bundle bundle everything but the python interpreter bundle everything including the python interpreter if zipfile is set to none the files will be bundle within the executable instead of library zip here is sample setup py from distutils core import setup import py exe sys os sys argv append py exe setup options py exe bundle files compressed true windows script single py zipfile none
QA
python when to use file vs open what is the difference between file and open in python when should use which one say am in
file is type like an int or list open is function for opening files and will return file object this is an example of when you should use open open filename for line in process line close this is an example of when you should use file class loggingfile file def write self data sys stderr write wrote bytes len data super loggingfile self write data as you can see there is good reason for both to exist and clear use case for both
QA
what are the python equivalents of the sighold and sigrelse functions found in it appears the python signal module does not have anything similar to the sighold and sigrelse functions found in using signal are there python equivalents of any sort many thanks
there is no way to block signals temporarily from critical sections since this is not supported by all unix flavors https docs python org library signal html
QA
what are the python equivalents of the sighold and sigrelse functions found in it appears the python signal module does not have anything similar to the sighold and sigrelse functions found in using signal are there python equivalents of any sort many thanks
there are no direct bindings for this in python accessing them through ctypes is easy enough here is an example import ctypes signal libc ctypes cdll loadlibrary libc so libc sighold signal sigkill libc sigrelse signal sigkill am not familiar with the use of these calls but be aware that python signal handlers work differently than when python code is attached to signal callback the signal is caught on the side of the interpreter and queued the interpreter is occasionally interrupted for internal housekeeping and thread switching etc it is during that interrupt the python handler for the signal will be called all that to say just be aware that python signal handling is little less asynchronous than normal signal handlers
QA
python passing variable between classes am trying to create character generation wizard for game in one class calculate the attributes of the character in different class am displaying to the user which specialties are available based on the attributes of the character however cannot remember how to pass variables between different classes here is an example of what have class basicinfopage wx wizard wizardpagesimple def init self parent title wiz wizardpagesimple init self parent self next self prev none self sizer makepagetitle self title snip self intelligence self genattribs class mos wx wizard wizardpagesimple def init self parent title wiz wizardpagesimple init self parent self next self prev none self sizer makepagetitle self title def eligiblemos self event if self intelligence self mos list append analyst the problem is that cannot figure out how to use the intelligence variable from the basicinfopage class to the mos class have tried several different things from around the internet but nothing seems to work what am missing edit realized after posted this that did not explain it that well am trying to create computer version of the twilight rpg from the am using wxpython to create wizard the parent class of my classes is the wizard from wxpython that wizard will walk user through the creation of character so the basic information page class basicinfopage let us the user give the character name and roll for the character attributes that is where the self intelligence comes from am trying to use the attributes created her for page further on in the wizard where the user selects the speciality of the character the specialities that are available depend on the attributes the character has if the intelligence is high enough the character can be an intel anaylst it is been several years since have programmed especially with oop ideas that is why am confused on how to create what is essentially global variable with classes and methods
if understood you correctly then the answer is you cannot intelligence should be an attribute of wizardpagesimple if you would want both classes to inherit it depending on your situation you might try to extract intelligence and related attributes into another baseclass then you could inherit from both class mos wiz wizardpagesimple wiz intelligenceattributes or something like that in that case you must use the co operative super in fact you should be using it already instead of calling wiz wizardpagesimple init self parent call super mos self init self parent
QA
python passing variable between classes am trying to create character generation wizard for game in one class calculate the attributes of the character in different class am displaying to the user which specialties are available based on the attributes of the character however cannot remember how to pass variables between different classes here is an example of what have class basicinfopage wx wizard wizardpagesimple def init self parent title wiz wizardpagesimple init self parent self next self prev none self sizer makepagetitle self title snip self intelligence self genattribs class mos wx wizard wizardpagesimple def init self parent title wiz wizardpagesimple init self parent self next self prev none self sizer makepagetitle self title def eligiblemos self event if self intelligence self mos list append analyst the problem is that cannot figure out how to use the intelligence variable from the basicinfopage class to the mos class have tried several different things from around the internet but nothing seems to work what am missing edit realized after posted this that did not explain it that well am trying to create computer version of the twilight rpg from the am using wxpython to create wizard the parent class of my classes is the wizard from wxpython that wizard will walk user through the creation of character so the basic information page class basicinfopage let us the user give the character name and roll for the character attributes that is where the self intelligence comes from am trying to use the attributes created her for page further on in the wizard where the user selects the speciality of the character the specialities that are available depend on the attributes the character has if the intelligence is high enough the character can be an intel anaylst it is been several years since have programmed especially with oop ideas that is why am confused on how to create what is essentially global variable with classes and methods
all you need is reference it is not really simple problem that can give some one line solution to other than simple ugly global that would probably break something else but one of program structure you do not magically get access to variable that was created on another instance of another class you have to either give the intelligence reference to mos or take it from basicinfopage however that might happen it seems to me that the classes are designed rather oddly an information page for one thing should not generate anything and if it does it should give it back to whatever needs to know some sort of central place which should have been the one generating it in the first place ordinarily you would set the variables there and get them from there or at least would if you want the basic answer of how do pass variables between different classes then here you go but doubt it is exactly what you want as you look to be using some sort of controlling framework class foo object def init self var self var var class bar object def do something self var print var if name main foo bar look am using the variable from one instance in another do something var
QA
xml rpc best way to handle bit values so the official xml rpc standard does not support bit values but in these modern times bit values are increasingly common how do you handle these what xml rpc extensions are the most common what language bindings are there am especially interested in python and but all information is appreciated
the use of as data type is becoming more and more common recently added this to my perl xml rpc module http metacpan org pod rpc xml in response to request from large group that needed it in order to work with server written in java do not know what toolkit the server used but it was already accepting as type one thing that feel still has to be addressed is whether the int alias for should also accept the way it currently does or for that matter if parameter typed as should quietly accept an input typed as xml rpc has great potential as lightweight low overhead protocol handy when you do not need all the coverage of soap but it is often overlooked in the religious wars between rest and soap xml rpc is in need of some updating and revision if we could just get the original author to permit it
QA
is there function in python to split string without ignoring the spaces is there function in python to split string without ignoring the spaces in the resulting list this is the string want to split split gives me this is the string want to split want something like this is the string
the hard part with what you are trying to do is that you are not giving it character to split on split explodes string on the character you provide to it and removes that character perhaps this may help string to split mylist for item in split mylist append item mylist append mylist mylist messy but it will do the trick for you
QA
is there function in python to split string without ignoring the spaces is there function in python to split string without ignoring the spaces in the resulting list this is the string want to split split gives me this is the string want to split want something like this is the string
import re re split this is the string want to split this is the string want to split using the capturing parentheses in re split causes the function to return the separators as well
QA
is there function in python to split string without ignoring the spaces is there function in python to split string without ignoring the spaces in the resulting list this is the string want to split split gives me this is the string want to split want something like this is the string
do not think there is function in the standard library that does that by itself but partition comes close the best way is probably to use regular expressions which is how would do this in any language import re print re split your string here
QA
is there function in python to split word into list is there function in python to split word into list of single letters word to split to get wordlist of would of
list word to split of would of
QA
is there function in python to split word into list is there function in python to split word into list of single letters word to split to get wordlist of would of
the easiest way is probably just to use list but there is at least one other option as well word to split wordlist list option wordlist ch for ch in option list comprehension they should both give you what you need of would of as stated the first is likely the most preferable for your example but there are use cases that may make the latter quite handy for more complex stuff such as if you want to apply some arbitrary function to the items such as with dosomethingwith ch for ch in
QA
is there function in python to split word into list is there function in python to split word into list of single letters word to split to get wordlist of would of
the list function will do this list foo of of
QA
list all words in dictionary that start with how would go about making program where the user enters string and the program generates list of words beginning with that string ex user abd program abdicate abdomen abduct thanks edit am using python but assume that this is fairly language independent problem
do not use bazooka to kill fly use something simple just like sqlite there are all the tools you need for every modern languages and you can just do select word from dict where word like user entry it is lightning fast and baby could do it what is more it is portable persistent and so easy to maintain python tuto http www initd org pub software pysqlite doc usage guide html
QA
python passing variable between classes am trying to create character generation wizard for game in one class calculate the attributes of the character in different class am displaying to the user which specialties are available based on the attributes of the character however cannot remember how to pass variables between different classes here is an example of what have class basicinfopage wx wizard wizardpagesimple def init self parent title wiz wizardpagesimple init self parent self next self prev none self sizer makepagetitle self title snip self intelligence self genattribs class mos wx wizard wizardpagesimple def init self parent title wiz wizardpagesimple init self parent self next self prev none self sizer makepagetitle self title def eligiblemos self event if self intelligence self mos list append analyst the problem is that cannot figure out how to use the intelligence variable from the basicinfopage class to the mos class have tried several different things from around the internet but nothing seems to work what am missing edit realized after posted this that did not explain it that well am trying to create computer version of the twilight rpg from the am using wxpython to create wizard the parent class of my classes is the wizard from wxpython that wizard will walk user through the creation of character so the basic information page class basicinfopage let us the user give the character name and roll for the character attributes that is where the self intelligence comes from am trying to use the attributes created her for page further on in the wizard where the user selects the speciality of the character the specialities that are available depend on the attributes the character has if the intelligence is high enough the character can be an intel anaylst it is been several years since have programmed especially with oop ideas that is why am confused on how to create what is essentially global variable with classes and methods
you may have class and instance confused it is not clear from your example so will presume that you are using lot of class definitions and do not have appropriate object instances of those classes classes do not really have usable attribute values class is just common set of definitions for collection of objects you should think of of classes as definitions not actual things instances of classes objects are actual things that have actual attribute values and execute method functions you do not pass variables among classes you pass variables among instances as practical matter only instance variables matter yes there are class variables but they are fairly specialized and often confusing thing best avoided when you create an object an instance of class basicinfopage then intelligence is the value of intelligence for the instance of basicinfopage really common thing is class mos wx wizard pagesimple def init self parent title basicinfopage snip self basicinfo basicinfopage now within mos methods you can say self basicinfo intelligence because mos has an object that is basicinfopage available to it when you build mos you provide it with the instance of basicinfopage that it is supposed to use somebasicinfopage basicinfopage mos somebasicinfopage now the object can examine somebasicinfopage intelligence
QA
deploying django how do you do it have tried following guides like this one but it just did not work for me so my question is this what is good guide for deploying django and how do you deploy your django keep hearing that capastrano is pretty nifty to use but have no idea as to how to work it or what it does apart from automation of deploying code or even if want need to use it or not
this looks like good place to start http www unessa net en hoyci using capistrano deploy django apps
QA
python passing variable between classes am trying to create character generation wizard for game in one class calculate the attributes of the character in different class am displaying to the user which specialties are available based on the attributes of the character however cannot remember how to pass variables between different classes here is an example of what have class basicinfopage wx wizard wizardpagesimple def init self parent title wiz wizardpagesimple init self parent self next self prev none self sizer makepagetitle self title snip self intelligence self genattribs class mos wx wizard wizardpagesimple def init self parent title wiz wizardpagesimple init self parent self next self prev none self sizer makepagetitle self title def eligiblemos self event if self intelligence self mos list append analyst the problem is that cannot figure out how to use the intelligence variable from the basicinfopage class to the mos class have tried several different things from around the internet but nothing seems to work what am missing edit realized after posted this that did not explain it that well am trying to create computer version of the twilight rpg from the am using wxpython to create wizard the parent class of my classes is the wizard from wxpython that wizard will walk user through the creation of character so the basic information page class basicinfopage let us the user give the character name and roll for the character attributes that is where the self intelligence comes from am trying to use the attributes created her for page further on in the wizard where the user selects the speciality of the character the specialities that are available depend on the attributes the character has if the intelligence is high enough the character can be an intel anaylst it is been several years since have programmed especially with oop ideas that is why am confused on how to create what is essentially global variable with classes and methods
each page of wizard by itself should not actually be the container for the information you are gathering read up on the model view control design pattern your pages have the view and control parts of the design they are not the data model however you will be happier if you have separate object that is built by the pages each page will set some attributes of that underlying model object then the pages are independent of each other since the pages all get and set values of this underlying model object since you are building character you would have some class like this class character object def init self self intelligence default values for all attributes then your various wizard instances just need to be given the underlying character object as place to put and get values
QA
deploying django how do you do it have tried following guides like this one but it just did not work for me so my question is this what is good guide for deploying django and how do you deploy your django keep hearing that capastrano is pretty nifty to use but have no idea as to how to work it or what it does apart from automation of deploying code or even if want need to use it or not
have had success with mod wsgi
QA
class method differences in python bound unbound and static what is the difference between the following class methods is it that one is static and the other is not class test object def method one self print called method one def method two print called method two test test test method one test method two
when you call class member python automatically uses reference to the object as the first parameter the variable self actually means nothing it is just coding convention you could call it gargaloo if you wanted that said the call to method two would raise typeerror because python is automatically trying to pass parameter the reference to its parent object to method that was defined as having no parameters to actually make it work you could append this to your class definition method two staticmethod method two or you could use the staticmethod function decorator
QA
class method differences in python bound unbound and static what is the difference between the following class methods is it that one is static and the other is not class test object def method one self print called method one def method two print called method two test test test method one test method two
method two will not work because you are defining member function but not telling it what the function is member of if you execute the last line you will get test method two traceback most recent call last file stdin line in module typeerror method two takes no arguments given if you are defining member functions for class the first argument must always be self
QA
class method differences in python bound unbound and static what is the difference between the following class methods is it that one is static and the other is not class test object def method one self print called method one def method two print called method two test test test method one test method two
the call to method two will throw an exception for not accepting the self parameter the python runtime will automatically pass it if you want to create static method in python class decorate it with the staticmethod decorator class test object staticmethod def method two print called method two test method two
QA
class method differences in python bound unbound and static what is the difference between the following class methods is it that one is static and the other is not class test object def method one self print called method one def method two print called method two test test test method one test method two
in python there is distinction between bound and unbound methods basically call to member function like method one bound function test method one is translated to test method one test call to an unbound method because of that call to your version of method two will fail with typeerror test test test method two traceback most recent call last file stdin line in module typeerror method two takes no arguments given you can change the behavior of method using decorator class test object def method one self print called method one staticmethod def method two print called method two the decorator tells the built in default metaclass type the class of class cf this question to not create bound methods for method two now you can invoke static method both on an instance or on the class directly test test test method one called method one test method two called method two test method two called method two
QA
deploying django how do you do it have tried following guides like this one but it just did not work for me so my question is this what is good guide for deploying django and how do you deploy your django keep hearing that capastrano is pretty nifty to use but have no idea as to how to work it or what it does apart from automation of deploying code or even if want need to use it or not
mod wsgi in combination with virtualenv for all the dependencies mercurial checkout into the virtualenv and fabric recipe to check out the changes on the server wrote an article about my usual workflow deploying python web applications hope that helps
QA
class method differences in python bound unbound and static what is the difference between the following class methods is it that one is static and the other is not class test object def method one self print called method one def method two print called method two test test test method one test method two
that is an error first of all first line should be like this be careful of capitals class test object whenever you call method of class it gets itself as the first argument hence the name self and method two gives this error method two traceback most recent call last file stdin line in module typeerror method two takes no arguments given
QA
class method differences in python bound unbound and static what is the difference between the following class methods is it that one is static and the other is not class test object def method one self print called method one def method two print called method two test test test method one test method two
the second one will not work because when you call it like that python internally tries to call it with the test instance as the first argument but your method two does not accept any arguments so it will not work you will get runtime error if you want the equivalent of static method you can use class method there is much less need for class methods in python than static methods in languages like java or most often the best solution is to use method in the module outside class definition those work more efficiently than class methods
QA
class method differences in python bound unbound and static what is the difference between the following class methods is it that one is static and the other is not class test object def method one self print called method one def method two print called method two test test test method one test method two
methods in python are very very simple thing once you understood the basics of the descriptor system imagine the following class class object def foo self pass now let us have look at that class in the she will foo unbound method foo dict foo function foo at as you can see if you access the foo attribute on the class you get back an unbound method however inside the class storage the dict there is function why is that the reason for this is that the class of your class implements getattribute that resolves descriptors sounds complex but is not foo is roughly equivalent to this code in that special case dict foo get none unbound method foo that is because functions have get method which makes them descriptors if you have an instance of class it is nearly the same just that none is the class instance dict foo get bound method foo of main object at bd now why does python do that because the method object binds the first parameter of function to the instance of the class that is where self comes from now sometimes you do not want your class to make function method that is where staticmethod comes into play class object staticmethod def foo pass the staticmethod decorator wraps your class and implements dummy get that returns the wrapped function as function and not as method dict foo get none function foo at hope that explains it
QA
where can save confirmation page be hooked into the django admin similar to delete confirmation want to emulate the delete confirmation page behavior before saving certain models in the admin in my case if change one object certain others should be deleted as they depend upon the object now out of date state understand where to implement the actual cascaded updates inside the parent model save method but do not see quick way to ask the user for confirmation and then rollback if they decide not to save suppose could implement some weird confirmation logic directly inside the save method sort of two phase save but that seems ugly any thoughts even general pointers into the django codebase thanks
am by no means django expert so this answer might misguide you start looking somewhere around django contrib admin options modeladmin especially render change form and response change guess you would need to subclass modeladmin for your model and provide required behavior around those methods
QA
where can save confirmation page be hooked into the django admin similar to delete confirmation want to emulate the delete confirmation page behavior before saving certain models in the admin in my case if change one object certain others should be deleted as they depend upon the object now out of date state understand where to implement the actual cascaded updates inside the parent model save method but do not see quick way to ask the user for confirmation and then rollback if they decide not to save suppose could implement some weird confirmation logic directly inside the save method sort of two phase save but that seems ugly any thoughts even general pointers into the django codebase thanks
you could overload the get form method of your model admin and add an extra checkbox to the generated form that has to be ticket alternatively you can override change view and intercept the request
QA
how can unit test responses from the webapp wsgi application in google app engine would like to unit test responses from the google app engine webapp wsgiapplication for example request the url and test that the responses status code is using gaeunit how can do this would like to use the webapp framework and gaeunit which runs within the app engine sandbox unfortunately webtest does not work within the sandbox
have added sample application to the gaeunit project which demonstrates how to write and execute web test using gaeunit the sample includes slightly modified version of the webtest module import webbrowser is commented out as recommended by david coffin here is the web tests py file from the sample application test directory import unittest from webtest import testapp from google appengine ext import webapp import index class indextest unittest testcase def setup self self application webapp wsgiapplication index indexhandler debug true def test default page self app testapp self application response app get self assertequal ok response status self asserttrue hello world in response def test page with param self app testapp self application response app get name bob self assertequal ok response status self asserttrue hello bob in response
QA
what is the fastest way to scale and display an image in python am required to display two dimensional numpy array of int at fps or so using matplotlib imshow chokes on anything above fps there obviously are some issues with scaling and interpolation should add that the dimensions of the array are not known but will probably be around thirty by four hundred these are data from sensor that are supposed to have real time display so the data has to be re sampled on the fly
the fastest way to display data points is to use opengl color arrays if you can quickly transform your data to what opengl understands as color array you could create vertex array describing quads one for each sensor then update your color array and draw this orthographically on screen use opengl textures if you can quickly transform your datapoints to an opengl texture you can draw one quad with fixed uv coordinates that is bound to this texture use pygame pygame has support for conversion of numpy numarray to surfaces pygame can then transform such surfaces which involves resampling after resampling you can blit it on screen misc pyglet makes dealing with opengl very easy
QA
is there any way to do http put in python need to upload some data to server using http put in python from my brief reading of the urllib docs it only does http post is there any way to do an http put in python
needed to solve this problem too while back so that could act as client for restful api settled on httplib because it allowed me to send put and delete in addition to get and post httplib is not part of the standard library but you can easily get it from the cheese shop
QA
how to bundle python application including dependencies need to package my python application its dependencies and python into single msi installer the end result should desirably be python is installed in the standard location the package and its dependencies are installed in separate directory possibly site packages the installation directory should contain the python uncompressed and standalone executable is not required
my company uses the free innosetup tool it is moderately complex program that has tons of flexibility for building installers for windows believe that it creates exe and not msi files however innosetup is not python specific but we have created an installer for one of our products that installs python along with dependencies to locations specified by the user at install time
QA
is python dictionary an example of hash table one of the basic data structures in python is the dictionary which allows one to record keys for looking up values of any type is this implemented internally as hash table if not what is it
yes it is hash mapping or hash table you can read description of python dict implementation as written by tim peters here that is why you cannot use something not hashable as dict key like list some list hash traceback most recent call last file stdin line in module typeerror list objects are unhashable some traceback most recent call last file stdin line in module typeerror list objects are unhashable you can read more about hash tables or check how it has been implemented in python and why it is implemented that way
QA
is python dictionary an example of hash table one of the basic data structures in python is the dictionary which allows one to record keys for looking up values of any type is this implemented internally as hash table if not what is it
yes internally it is implemented as open hashing based on primitive polynomial over source
QA
is python dictionary an example of hash table one of the basic data structures in python is the dictionary which allows one to record keys for looking up values of any type is this implemented internally as hash table if not what is it
if you are interested in the technical details one article in beautiful code deals with the internals of python dict implementation
QA
python dns cannot get rrsig records no answer get dns records from python program using dns python can get various dnssec related records import dns resolver myresolver dns resolver resolver myresolver use edns print myresolver query sources org dnskey dns resolver answer object at xb ed print myresolver query ripe net nsec dns resolver answer object at but no rrsig records print myresolver query sources org rrsig traceback most recent call last file stdin line in module file usr lib python site packages dns resolver py line in query answer answer qname rdtype rdclass response file usr lib python site packages dns resolver py line in init raise noanswer tried several signed domains like absolight fr or ripe net trying with dig see that there are indeed rrsig records checking with tcpdump can see that dns python sends the correct query and receives correct replies here eight records ip au rrsig sources org ip rrsig domain dns python python aug gcc on linux
this looks like probable bug in the python dns library although do not read python well enough to find it note that in any case your edns buffer size parameter is not large enough to handle the rrsig records for sources org so your client and server would have to fail over to tcp ip
QA
how do overlap widgets with the tkinter pack geometry manager want to put canvas with an image in my window and then want to pack widgets on top of it so the canvas acts as background is it possible to have two states for the pack manager one for one set of widgets and another for another set
turned out to be unworkable because wanted to add labels and more canvases to it but cannot find any way to make their backgrounds transparent if it is acceptable to load an additional extension take look at tkzinc from the web site tkzinc historically called zinc widget is very similar to the tk canvas in that they both support structured graphics like the canvas tkzinc implements items used to display graphical entities those items can be manipulated and bindings can be associated with them to implement interaction behaviors but unlike the canvas tkzinc can structure the items in hierarchy has support for scaling and rotation clipping can be set for sub trees of the item hierarchy supports muti contour curves it also provides advanced rendering with the help of opengl such as color gradient antialiasing transparencies and triangles item am currently using it on tcl project and am quite pleased with the results extensions for tcl perl and python are available
QA
is there function in python to split word into list is there function in python to split word into list of single letters word to split to get wordlist of would of
abuse of the rules same result for in word to split actually an iterator not list but it is likely you will not really care
QA
what is callable in python now that it is clear what metaclass is there is an associated concept that use all the time without knowing what it really means suppose everybody made once mistake with parenthesis resulting in an object is not callable exception what is more using init and new lead to wonder what this bloody call can be used for could you give me some explanations including examples with the magic method
from python sources object test whether an object can be called int pycallable check pyobject if null return if pyinstance check pyobject call pyobject getattrstring call if call null pyerr clear return could test recursively but do not for fear of endless recursion if some joker sets self call self py decref call return else return ob type tp call null it says if an object is an instance of some class then it is callable iff it has call attribute else the object is callable iff ob type tp call null desciption of tp call field ternaryfunc tp call an optional pointer to function that implements calling the object this should be null if the object is not callable the signature is the same as for pyobject call this field is inherited by subtypes you can always use built in callable function to determine whether given object is callable or not or better yet just call it and catch typeerror later callable is removed in python and use callable lambda hasattr call or isinstance collections callable example simplistic cache implementation class cached def init self function self function function self cache def call self args try return self cache args except keyerror ret self cache args self function args return ret usage cached def ack return ack ack if else example from standard library file site py definition of built in exit and quit functions class quitter object def init self name self name name def repr self return use or to exit self name eof def call self code none shells like idle catch the systemexit but listen when their stdin wrapper is closed try sys stdin close except pass raise systemexit code builtin quit quitter quit builtin exit quitter exit
QA
is python dictionary an example of hash table one of the basic data structures in python is the dictionary which allows one to record keys for looking up values of any type is this implemented internally as hash table if not what is it
to expand upon nosklo explanation some list some this will not work tuple some this will same as some list
QA
how can consume wsdl soap web service in python want to use wsdl soap based web service in python have looked at the dive into python code but the soappy module does not work under python have tried using suds which works partly but breaks with certain types suds typenotfound type not found item have also looked at client but this does not appear to support wsdl and have looked at zsi but it looks very complex does anyone have any sample code for it the wsdl is https ws pingdom com soap pingdomapi wsdl and works fine with the php soap client
right now as of all the soap libraries available for python suck recommend avoiding soap if possible the last time we where forced to use soap web service from python we wrote wrapper in that handled the soap on one side and spoke com out the other
QA
which is more pythonic factory as function in module or as method on the class it creates have some python code that creates calendar object based on parsed vevent objects from and icalendar file the calendar object just has method that adds events as they get parsed now want to create factory function that creates calendar from file object path or url have been using the icalendar python module which implements factory function as class method directly on the class that it returns an instance of cal icalendar calendar from string data from what little know about java this is common pattern in java code though seem to find more references to factory method being on different class than the class you actually want to instantiate instances from the question is is this also considered pythonic or is it considered more pythonic to just create module level method as the factory function
it is pythonic not to think about esoteric difference in some pattern you read somewhere and now want to use everywhere like the factory pattern most of the time you would think of staticmethod as solution it is probably better to use module function except when you stuff multiple classes in one module and each has different implementation of the same interface then it is better to use staticmethod ultimately weather you create your instances by staticmethod or by module function makes little difference would probably use the initializer init of class because one of the more accepted patterns in python is that the factory for class is the class initialization
QA
which is more pythonic factory as function in module or as method on the class it creates have some python code that creates calendar object based on parsed vevent objects from and icalendar file the calendar object just has method that adds events as they get parsed now want to create factory function that creates calendar from file object path or url have been using the icalendar python module which implements factory function as class method directly on the class that it returns an instance of cal icalendar calendar from string data from what little know about java this is common pattern in java code though seem to find more references to factory method being on different class than the class you actually want to instantiate instances from the question is is this also considered pythonic or is it considered more pythonic to just create module level method as the factory function
the factory pattern has its own strengths and weaknesses however choosing one way to create instances usually has little pragmatic effect on your code
QA
which is more pythonic factory as function in module or as method on the class it creates have some python code that creates calendar object based on parsed vevent objects from and icalendar file the calendar object just has method that adds events as they get parsed now want to create factory function that creates calendar from file object path or url have been using the icalendar python module which implements factory function as class method directly on the class that it returns an instance of cal icalendar calendar from string data from what little know about java this is common pattern in java code though seem to find more references to factory method being on different class than the class you actually want to instantiate instances from the question is is this also considered pythonic or is it considered more pythonic to just create module level method as the factory function
imho module level method is cleaner solution it hides behind the python module system that gives it unique namespace prefix something the factory pattern is commonly used for
QA
how do configure the ip address with cherrypy am using python and cherrypy to create simple internal website that about people use use the built in webserver with cherrypy quickstart and never messed with the config files recently changed machines so installed the latest python and cherrypy and when run the site can access it from localhost but not through the ip or the windows machine name it could be machine configuration difference or newer version of cherrypy or python any ideas how can bind to the correct ip address edit to make it clear currently do not have config file at all
that depends on how you are running the cherrypy init if using cherrypy syntax that wold do it cherrypy server socket host www machinename com cherrypy engine start cherrypy engine block of course you can have something more fancy like subclassing the server class or using config files those uses are covered in the documentation but that should be enough if not just tell us what you are doing and cherrypy version and will edit this answer
QA
which is more pythonic factory as function in module or as method on the class it creates have some python code that creates calendar object based on parsed vevent objects from and icalendar file the calendar object just has method that adds events as they get parsed now want to create factory function that creates calendar from file object path or url have been using the icalendar python module which implements factory function as class method directly on the class that it returns an instance of cal icalendar calendar from string data from what little know about java this is common pattern in java code though seem to find more references to factory method being on different class than the class you actually want to instantiate instances from the question is is this also considered pythonic or is it considered more pythonic to just create module level method as the factory function
note be very cautious about separating calendar collection of events and event single event on calendar in your question it seems like there could be some confusion there are many variations on the factory design pattern stand alone convenience function calendarmaker data separate class calendarparser which builds your target class calendar class level method calendar from string method these have different purposes all are pythonic the questions are what do you mean and what is likely to change meaning is everything change is important convenience functions are pythonic languages like java cannot have free floating functions you must wrap lonely function in class python allows you to have lonely function without the overhead of class function is relevant when your constructor has no state changes or alternate strategies or any memory of previous actions sometimes folks will define class and then provide convenience function that makes an instance of the class sets the usual parameters for state and strategy and any other configuration and then calls the single relevant method of the class this gives you both the statefulness of class plus the flexibility of stand alone function the class level method pattern is used but it has limitations one it is forced to rely on class level variables since these can be confusing complex constructor as static method runs into problems when you need to add features like statefulness or alternative strategies be sure you are never going to expand the static method two it is more or less irrelevant to the rest of the class methods and attributes this kind of from string is just one of many alternative encodings for your calendar objects you might have from xml from json from yaml and on and on none of this has the least relevance to what calendar is or what it does these methods are all about how calendar is encoded for transmission what you will see in the mature python libraries is that factories are separate from the things they create encoding as strings xml json yaml is subject to great deal of more or less random change the essential thing however rarely changes separate the two concerns keep encoding and representation as far away from state and behavior as you can
QA
convert mysql timestamp to epoch time in python convert mysql timestamp to epoch time in python is there an easy way to do this
why not let mysql do the hard work select unix timestamp fieldname from tablename
QA
which is more pythonic factory as function in module or as method on the class it creates have some python code that creates calendar object based on parsed vevent objects from and icalendar file the calendar object just has method that adds events as they get parsed now want to create factory function that creates calendar from file object path or url have been using the icalendar python module which implements factory function as class method directly on the class that it returns an instance of cal icalendar calendar from string data from what little know about java this is common pattern in java code though seem to find more references to factory method being on different class than the class you actually want to instantiate instances from the question is is this also considered pythonic or is it considered more pythonic to just create module level method as the factory function
staticmethod rarely has value but classmethod may be useful it depends on what you want the class and the factory function to actually do factory function in module would always make an instance of the right type where right in your case is the calendar class always but you might also make it dependant on the contents of what it is creating the instance out of use classmethod if you wish to make it dependant not on the data but on the class you call it on classmethod is like staticmethod in that you can call it on the class without an instance but it receives the class it was called on as first argument this allows you to actually create an instance of that class which may be subclass of the original class an example of classmethod is dict fromkeys which creates dict from list of keys and single value defaulting to none because it is classmethod when you subclass dict you get the fromkeys method entirely for free here is an example of how one could write dict fromkeys oneself class dict with fromkeys dict classmethod def fromkeys cls keys value none self cls for key in keys self key value return self
QA
what would be the simplest way to daemonize python script in linux what would be the simplest way to daemonize python script in linux need that this works with every flavor of linux so it should only use python based tools
nohup creating daemon the python way
QA
using pylint with django would very much like to integrate pylint into the build process for my python projects but have run into one show stopper one of the error types that find extremely useful has no member constantly reports errors when using common django fields for example get user tags class tag has no objects member which is caused by this code def get user tags username gets all the tags that username has used returns query set return tag objects filter this line triggers the error tagownership users username exact username distinct here is the tag class models model is provided by django class tag models model model for user defined strings that help categorize events on on per user basis name models charfield max length null false unique true def unicode self return self name how can tune pylint to properly take fields such as objects into account have also looked into the django source and have been unable to find the implementation of objects so suspect it is not just class field on the other hand am fairly new to python so may very well have overlooked something edit the only way have found to tell pylint to not warn about these warnings is by blocking all errors of the type which is not an acceptable solution since that is in my opinion an extremely useful error if there is another way without augmenting the pylint source please point me to specifics see here for summary of the problems have had with pychecker and pyflakes they have proven to be far to unstable for general use in pychecker case the crashes originated in the pychecker code not source it was loading invoking
because of how pylint works it examines the source itself without letting python actually execute it it is very hard for pylint to figure out how metaclasses and complex baseclasses actually affect class and its instances the pychecker tool is bit better in this regard because it does actually let python execute the code it imports the modules and examines the resulting objects however that approach has other problems because it does actually let python execute the code you could extend pylint to teach it about the magic django uses or to make it understand metaclasses or complex baseclasses better or to just ignore such cases after detecting one or more features it does not quite understand do not think it would be particularly easy you can also just tell pylint to not warn about these things through special comments in the source command line options or pylintrc file
QA
what is the simplest way to offer consume web services in jython have an application for tomcat which needs to offer consume web services since java web services are nightmare xml code generation etc compared with what is possible in python would like to learn from your experience using jython instead of java for offerring consuming web services what have done so far involves adapting http pywebsvcs sourceforge net to jython still get errors namespaces types and so although some of it is succesful for the simplest services
pyservlet helps you configure tomcat to serve up jython scripts from url you could use this is rest like way to do some basic web services without much effort it is also described here we used similar home grown framework to provide variety of data services in large multiple web application very successfully
QA
what would be the simplest way to daemonize python script in linux what would be the simplest way to daemonize python script in linux need that this works with every flavor of linux so it should only use python based tools
see stevens and also this lengthy thread on activestate which found personally to be both mostly incorrect and much to verbose and came up with this from os import fork setsid umask dup from sys import stdin stdout stderr if fork exit umask setsid if fork exit stdout flush stderr flush si file dev null so file dev null se file dev null dup si fileno stdin fileno dup so fileno stdout fileno dup se fileno stderr fileno if you need to stop that process again it is required to know the pid the usual solution to this is pidfiles do this if you need one from os import getpid outfile open pid file outfile write getpid outfile close for security reasons you might consider any of these after demonizing from os import setuid setgid chdir from pwd import getpwnam from grp import getgrnam setuid getpwnam someuser pw uid setgid getgrnam somegroup gr gid chdir you could also use nohup but that does not work well with python subprocess module
QA
using pylint with django would very much like to integrate pylint into the build process for my python projects but have run into one show stopper one of the error types that find extremely useful has no member constantly reports errors when using common django fields for example get user tags class tag has no objects member which is caused by this code def get user tags username gets all the tags that username has used returns query set return tag objects filter this line triggers the error tagownership users username exact username distinct here is the tag class models model is provided by django class tag models model model for user defined strings that help categorize events on on per user basis name models charfield max length null false unique true def unicode self return self name how can tune pylint to properly take fields such as objects into account have also looked into the django source and have been unable to find the implementation of objects so suspect it is not just class field on the other hand am fairly new to python so may very well have overlooked something edit the only way have found to tell pylint to not warn about these warnings is by blocking all errors of the type which is not an acceptable solution since that is in my opinion an extremely useful error if there is another way without augmenting the pylint source please point me to specifics see here for summary of the problems have had with pychecker and pyflakes they have proven to be far to unstable for general use in pychecker case the crashes originated in the pychecker code not source it was loading invoking
try running pylint with pylint ignored classes tags if that works add all the other django classes possibly using script in say python the documentation for ignore classes is ignored classes members names list of classes names for which member attributes should not be checked useful for classes with attributes dynamicaly set current default should add this is not particular elegant solution in my view but it should work
QA
what would be the simplest way to daemonize python script in linux what would be the simplest way to daemonize python script in linux need that this works with every flavor of linux so it should only use python based tools
use grizzled os daemonize easy install grizzled from grizzled os import daemonize daemon daemonize to understand how this works or to do it yourself read the discussion on activestate
QA
is there any way to do http put in python need to upload some data to server using http put in python from my brief reading of the urllib docs it only does http post is there any way to do an http put in python
also recommend httplib by joe gregario use this regularly instead of httplib in the standard lib
QA
how can search word in word docx file would like to search word file docx for text string some special phrase that could would be found from search within word is there way from python to see the text have no interest in formatting just want to classify documents as having or not having some special phrase
docx is just zip archive with lots of files inside maybe you can look at some of the contents of those files other than that you probably have to find lib that understands the word format so that you can filter out things you are not interested in second choice would be to interop with word and do the search through it
QA
how can search word in word docx file would like to search word file docx for text string some special phrase that could would be found from search within word is there way from python to see the text have no interest in formatting just want to classify documents as having or not having some special phrase
docx file is essentially zip file with an xml inside it the xml contains the formatting but it also contains the text
QA
how can search word in word docx file would like to search word file docx for text string some special phrase that could would be found from search within word is there way from python to see the text have no interest in formatting just want to classify documents as having or not having some special phrase
you should be able to use the msword activex interface to extract the text to search or possibly do the search have no idea how you access activex from python though
QA
how can search word in word docx file would like to search word file docx for text string some special phrase that could would be found from search within word is there way from python to see the text have no interest in formatting just want to classify documents as having or not having some special phrase
more exactly docx document is zip archive in openxml format you have first to uncompress it downloaded sample google some search term filetype docx and after unzipping found some folders the word folder contains the document itself in file document xml
QA
python regular expression to split paragraphs how would one write regular expression to use in python to split paragraphs paragraph is defined by linebreaks but one can have any ammount of spaces tabs together with the line breaks and it still should be considered as paragraph am using python so the solution can use python regular expression syntax which is extended can make use of stuff examples the str paragraph nparagraph splitting should yield paragraph paragraph the str np tstill tp should yield tstill the str tp should yield tp the best could come with is but that is ugly anything better edit suggestions rejected that would make example and fail since includes so it would allow paragraph breaks with more than ns
almost the same but using non greedy quantifiers and taking advantage of the whitespace sequence
QA
python regular expression to split paragraphs how would one write regular expression to use in python to split paragraphs paragraph is defined by linebreaks but one can have any ammount of spaces tabs together with the line breaks and it still should be considered as paragraph am using python so the solution can use python regular expression syntax which is extended can make use of stuff examples the str paragraph nparagraph splitting should yield paragraph paragraph the str np tstill tp should yield tstill the str tp should yield tp the best could come with is but that is ugly anything better edit suggestions rejected that would make example and fail since includes so it would allow paragraph breaks with more than ns
are you trying to deduce the structure of document in plain test are you doing what docutils does you might be able to simply use the docutils parser rather than roll your own
QA
python regular expression to split paragraphs how would one write regular expression to use in python to split paragraphs paragraph is defined by linebreaks but one can have any ammount of spaces tabs together with the line breaks and it still should be considered as paragraph am using python so the solution can use python regular expression syntax which is extended can make use of stuff examples the str paragraph nparagraph splitting should yield paragraph paragraph the str np tstill tp should yield tstill the str tp should yield tp the best could come with is but that is ugly anything better edit suggestions rejected that would make example and fail since includes so it would allow paragraph breaks with more than ns
unfortunately there is no nice way to write space but not newline think the best you can do is add some space with the modifier and try to factor out the ugliness bit but that is questionable you could also try creating subrule just for the character class and interpolating it three times
QA
how do you create an osx application dmg from python package want to create mac osx application from python package and then put it in disk image because load some resources out of the package the package should not reside in zip file the resulting disk image should display the background picture to drag here applications for installation
do not know the correct way to do it but this manual method is the approach have used for simple scripts which seems to have preformed suitably will assume that whatever directory am in the python files for my program are in the relative src directory and that the file want to execute which has the proper shebang and execute permissions is named main py mkdir myapplication app contents macos mv src myapplication app contents macos cd myapplication app contents macos mv main py myapplication at this point we have an application bundle which as far as know should work on any mac os system with python installed which think it has by default it does not have an icon or anything that requires adding some more metadata to the package which is unnecessary for my purposes and am not familiar with to create the drag and drop installer is quite simple use disk utility to create new disk image of approximately the size you require to store your application open it up copy your application and an alias of applications to the drive then use view options to position them as you want the drag and drop message is just background of the disk image which you can also specify in view options have not done it before but would assume that after you whip up an image in your editor of choice you could copy it over set it as the background and then use chflags hidden to prevent it from cluttering up your nice window know these are not the clearest simplest or most detailed instructions out there but hope somebody may find them useful
QA
best practices for manipulating database result sets in python am writing simple python web application that consists of several pages of business data formatted for the iphone am comfortable programming python but am not very familiar with python idiom especially regarding classes and objects python object oriented design differs somewhat from other languages have worked with so even though my application is working am curious whether there is better way to accomplish my goals specifics how does one typically implement the request transform render database workflow in python currently am using pyodbc to fetch data copying the results into attributes on an object performing some calculations and merges using list of these objects then rendering the output from the list of objects sample code below sql queries redacted is this sane is there better way are there any specific gotchas have stumbled into in my relative ignorance of python am particularly concerned about how have implemented the list of rows using the empty record class class record object pass def calculate pnl records node prices for record in records try fill rt and da prices from the hash retrieved above if hasattr record sink and record sink record da node prices record sink node prices record id record rt node prices record sink node prices record id else record da node prices record id record rt node prices record id calculate dependent values rt da and pnl record rtda record rt record da record pnl record rtda record mw except print sys exc info def map rows cursor mappings callback none records for row in cursor record record for field attr in mappings iteritems setattr record attr getattr row field none if not callback or callback record records append record return records def get positions cursor get the latest position time cursor execute select latest data time time cursor fetchone time hour eelib util get hour ending time fetch the current positions cursor execute select stuff from atable hour read the rows nodes def record callback record if abs record mw if record id nodes record id none return true else return false records util map rows cursor id id name name mw mw record callback query prices for node id in nodes rt price row cursor execute select price where node id time time fetchone rt row lmp if row else none da price row cursor execute select price where node id hour hour fetchone da row da lmp if row else none update the hash value nodes node id da rt calculate the position pricing calculate pnl records nodes sort records sort key lambda name return the records return records
have you considered using an orm sqlalchemy is pretty good and elixir makes it beautiful it can really reduce the ammount of boilerplate code needed to deal with databases also lot of the gotchas mentioned have already shown up and the sqlalchemy developers dealt with them
QA
how can consume wsdl soap web service in python want to use wsdl soap based web service in python have looked at the dive into python code but the soappy module does not work under python have tried using suds which works partly but breaks with certain types suds typenotfound type not found item have also looked at client but this does not appear to support wsdl and have looked at zsi but it looks very complex does anyone have any sample code for it the wsdl is https ws pingdom com soap pingdomapi wsdl and works fine with the php soap client
it is not true soappy does not work with python it works although it is very simple and really really basic if you want to talk to any more complicated webservice zsi is your only friend the really useful demo found is at http www ebi ac uk tools webservices tutorials python this really helped me to understand how zsi works