prefix
stringclasses 1
value | input_text
stringlengths 19
27.3k
⌀ | target_text
stringlengths 2
24.8k
⌀ |
---|---|---|
QA
|
django fastcgi how to manage long running process have inherited django fastcgi application which needs to be modified to perform lengthy computation up to half an hour or more what want to do is run the computation in the background and return your job has been started type response while the process is running further hits to the url should return your job is still running until the job finishes at which point the results of the job should be returned any subsequent hit on the url should return the cached result am an utter novice at django and have not done any significant web work in decade so do not know if there is built in way to do what want have tried starting the process via subprocess popen and that works fine except for the fact it leaves defunct entry in the process table need clean solution that can remove temporary files and any traces of the process once it has finished have also experimented with fork and threads and have yet to come up with viable solution is there canonical solution to what seems to me to be pretty common use case fwiw this will only be used on an internal server with very low traffic
|
maybe you could look at the problem the other way around maybe you could try djangoqueueservice and have daemon listening to the queue seeing if there is something new and process it
|
QA
|
stunned weird problem with python and sockets threads have python script that is http server http paste org when benchmarking it against apachebench ab with concurrency level switch that is lower then or equal to the value specified in the socket listen call in the sourcecode everything works fine but as soon as put the concurrency level in apache bench above the value in the socket listen call performance drops through the floor some example socket listen and ab http localhost req socket listen and ab http localhost req socket listen and ab http localhost req socket listen and ab http localhost req nothing changes in the code between the two calls can figure out what is wrong been at this problem for one day now also note that the multiplexing version of the same code wrote to compare to the threaded version works fine no matter what socket listen is set to or what the concurrency switch in apache is set to have spent day on irc python docs posted on comp lang python and on my blog cannot find anyone that even has an idea what could be wrong help me
|
found this article on backlog on tomcat java which gives an interesting insight in the backlog for example if all threads are busy in java handling requests the kernel will handle syn and tcp handshakes until its backlog is full when the backlog is full it will simply drop future syn requests it will not send rst ie causing connection refused on the client instead the client will assume the package was lost and retransmit the syn hopefully the backlog queue will have cleared up by then as interpret it by asking ab to create more simultaneous connection than your socket is configured to handle packets get dropped not refused and do not know how ab handles that it may be that it retransmits the syn but possibly after waiting while this may even be specced somewhere tcp protocol as said do not know but hope this hints at the because good luck
|
QA
|
stunned weird problem with python and sockets threads have python script that is http server http paste org when benchmarking it against apachebench ab with concurrency level switch that is lower then or equal to the value specified in the socket listen call in the sourcecode everything works fine but as soon as put the concurrency level in apache bench above the value in the socket listen call performance drops through the floor some example socket listen and ab http localhost req socket listen and ab http localhost req socket listen and ab http localhost req socket listen and ab http localhost req nothing changes in the code between the two calls can figure out what is wrong been at this problem for one day now also note that the multiplexing version of the same code wrote to compare to the threaded version works fine no matter what socket listen is set to or what the concurrency switch in apache is set to have spent day on irc python docs posted on comp lang python and on my blog cannot find anyone that even has an idea what could be wrong help me
|
cannot confirm your results and your server is coded fishy whipped up my own server and do not have this problem either let us move the discussion to simpler level import thread socket queue connections queue queue num threads backlog def request while conn connections get data while not in data data conn recv conn sendall http ok nhello world conn close if name main for in range num threads thread start new thread request acceptor socket socket socket af inet socket sock stream acceptor setsockopt socket sol socket socket so reuseaddr acceptor bind acceptor listen backlog while conn addr acceptor accept connections put conn which on my machine does ab http sec ab http sec
|
QA
|
stunned weird problem with python and sockets threads have python script that is http server http paste org when benchmarking it against apachebench ab with concurrency level switch that is lower then or equal to the value specified in the socket listen call in the sourcecode everything works fine but as soon as put the concurrency level in apache bench above the value in the socket listen call performance drops through the floor some example socket listen and ab http localhost req socket listen and ab http localhost req socket listen and ab http localhost req socket listen and ab http localhost req nothing changes in the code between the two calls can figure out what is wrong been at this problem for one day now also note that the multiplexing version of the same code wrote to compare to the threaded version works fine no matter what socket listen is set to or what the concurrency switch in apache is set to have spent day on irc python docs posted on comp lang python and on my blog cannot find anyone that even has an idea what could be wrong help me
|
it looks like you are not really getting concurrency apparently when you do socket accept the main thread does not go immediately back to waiting for the next connection maybe your connection handling thread is only python code so you are getting sequentialized by the sil single interpreder lock if there is not heavy communications between threads better use multi process scheme with pool of pre spawned processes of course
|
QA
|
how do coherently organize modules for pygtk desktop application am working on desktop application in pygtk and seem to be bumping up against some limitations of my file organization thus far have structured my project this way application py holds the primary application class most functional routines gui py holds loosely coupled gtk gui implementation handles signal callbacks etc command py holds command line automation functions not dependent on data in the application class state py holds the state data persistence class this has served fairly well so far but at this point application py is starting to get rather long have looked at numerous other pygtk applications and they seem to have similar structural issues at certain point the primary module starts to get very long and there is not obvious way of breaking the code out into narrower modules without sacrificing clarity and object orientation have considered making the gui the primary module and having seperate modules for the toolbar routines the menus routines etc but at that point believe will lose most of the benefits of oop and end up with an everything references everything scenario should just deal with having very long central module or is there better way of structuring the project so that do not have to rely on the class browser so much edit ok so point taken regarding all the mvc stuff do have rough approximation of mvc in my code but admittedly could probably gain some mileage by further segregating the model and controller however am reading over python gtkmvc documentation which is great find by the way thank you for referencing it and my impression is that its not going to solve my problem so much as just formalize it my application is single glade file generally single window so no matter how tightly define the mvc roles of the modules am still going to have one controller module doing most everything which is pretty much what have now admittedly am little fuzzy on proper mvc implementation and am going to keep researching but it does not look to me like this architecture is going to get any more stuff out of my main file its just going to rename that file to controller py should be thinking about separate controller view pairs for seperate sections of the window the toolbar the menus etc perhaps that is what am missing here it seems that this is what lott is referring to in his second bullet point thanks for the responses so far
|
so having not heard back regarding my edit to the original question have done some more research and the conclusion seem to be coming to is that yes should break the interface out into several views each with its own controller python gtkmvc provides the ability to this by providing glade top widget name parameter to the view constructor this all seems to make good deal of sense although it is going to require large refactoring of my existing codebase which may or may not be willing to undertake in the near term know know should moreover am left to wonder whether should just have single model object my application is fairly simple no more than twenty five state vars or if should break it out into multiple models and have to deal with controllers observing multiple models and chaining notifications across them again know really should do the latter if anyone has any further insight still do not really feel like have gotten an answer to the original question although have direction to head in now moreover it seems like their ought to be other architectural choices at hand given that up until now had not seen single python application coded in the mvc style but then again many python applications tend to have the exact problem have described above
|
QA
|
stunned weird problem with python and sockets threads have python script that is http server http paste org when benchmarking it against apachebench ab with concurrency level switch that is lower then or equal to the value specified in the socket listen call in the sourcecode everything works fine but as soon as put the concurrency level in apache bench above the value in the socket listen call performance drops through the floor some example socket listen and ab http localhost req socket listen and ab http localhost req socket listen and ab http localhost req socket listen and ab http localhost req nothing changes in the code between the two calls can figure out what is wrong been at this problem for one day now also note that the multiplexing version of the same code wrote to compare to the threaded version works fine no matter what socket listen is set to or what the concurrency switch in apache is set to have spent day on irc python docs posted on comp lang python and on my blog cannot find anyone that even has an idea what could be wrong help me
|
for the heck of it also implemented an asynchronous version import socket queue select class request object def init self conn self conn conn self fileno conn fileno self perform self perform next def perform self data self conn recv while not in data message self conn recv if message data message yield else break reading remove self writing append self data http ok nhello world while data sent self conn send data data data sent yield writing remove self self conn close class acceptor def init self sock socket socket socket af inet socket sock stream sock setsockopt socket sol socket socket so reuseaddr sock bind sock listen self sock sock self fileno sock fileno def perform self conn addr self sock accept reading append request conn if name main reading acceptor writing list while readable writable error select select reading writing for action in readable writable try action perform except stopiteration pass which performs ab http sec ab http sec
|
QA
|
scrape dynamic website what is the best method to scrape dynamic website where most of the content is generated by what appears to be ajax requests have previous experience with mechanize beautifulsoup and python combo but am up for something new edit for more detail am trying to scrape the cnn primary database there is wealth of information there but there does not appear to be an api
|
there is bit of learning curve but tools like pamie python or watir ruby will let you latch into the ie web browser and get at the elements this turns out to be easier than mechanize and other http level tools since you do not have to emulate the browser you just ask the browser for the html elements and it is going to be way easier than reverse engineering the javascript ajax calls if needed you can also use tools like beatiful soup in conjunction with pamie
|
QA
|
how do you get output parameters from stored procedure in python have googled around bit but maybe did not put the correct magik incantation into the search box does anyone know how to get output parameters from stored procedure in python am using pymssql to call stored procedure and am not sure of the correct syntax to get the output parameter back do not think can use any other db modules since am running this from linux box to connect to mssql database on ms server import pymssql con pymssql connect host xxxxx user xxxx password xxxxx database xxxxx cur con cursor query execute blah blah blah cur execute query con commit con close
|
it looks like every python dbapi library implemented on top of freetds pymssql pyodbc etc will not be able to access output parameters when connecting to microsoft sql server sp and higher http www freetds org faq html ms output parameters
|
QA
|
how do you get output parameters from stored procedure in python have googled around bit but maybe did not put the correct magik incantation into the search box does anyone know how to get output parameters from stored procedure in python am using pymssql to call stored procedure and am not sure of the correct syntax to get the output parameter back do not think can use any other db modules since am running this from linux box to connect to mssql database on ms server import pymssql con pymssql connect host xxxxx user xxxx password xxxxx database xxxxx cur con cursor query execute blah blah blah cur execute query con commit con close
|
if you cannot or do not want to modify the original procedure and have access to the database you can write simple wrapper procedure that is callable from python for example if you have stored procedure like create proc getnextnumber nextnumber int output as you could write wrapper like so which is easily callable from python create proc getnextnumberwrap as declare rnextnumber int exec getnextnumber rnextnumber select rnextnumber go then you could call it from python like so import pymssql con pymssql connect cur con cursor cur execute exec getnextnumberwrap next num cur fetchone
|
QA
|
getting method parameter names in python given the python function def amethod arg arg pass how can extract the number and names of the arguments ie given that have reference to func want the func something to return arg arg the usage scenario for this is that have decorator and wish to use the method arguments in the same order that they appear for the actual function as key ie how would the decorator look that printed when call amethod
|
here is something think will work for what you want using decorator class logwrappedfunction object def init self function self function function def logandcall self arguments namedarguments print calling with arguments and named arguments self function func name arguments namedarguments self function call arguments namedarguments def logwrap function return logwrappedfunction function logandcall logwrap def dosomething spam eggs foo bar print doing something totally awesome with and spam eggs dosomething beans rice foo wiggity bar wack run it it will yield the following output scripts python decoratorexample py calling dosomething with arguments beans rice and named arguments foo wiggity bar wack doing something totally awesome with beans and rice
|
QA
|
ensure single instance of an application in linux am working on gui application in wxpython and am not sure how can ensure that only one copy of my application is running at any given time on the machine due to the nature of the application running more than once does not make any sense and will fail quickly under win can simply make named mutex and check that at startup unfortunately do not know of any facilities in linux that can do this am looking for something that will automatically be released should the application crash unexpectedly do not want to have to burden my users with having to manually delete lock files because crashed
|
if you create lock file and put the pid in it you can check your process id against it and tell if you crashed no have not done this personally so take with appropriate amounts of salt
|
QA
|
how can represent an enum in python am mainly developer but am currently working on project in python how can represent the equivalent of an enum in python
|
it is funny just had need for this the other day and could not find an implementation worth using so wrote my own import functools class enumvalue object def init self name value type self value value self name name self type type def str self return self name def repr self only so change to what ever you need return cls format self name self value self type name cls type self name def hash self return hash self value def nonzero self return bool self value def cmp self other if isinstance other enumvalue return cmp self value other value else return cmp self value other hopefully their the same type but who cares def or self other if other is none return self elif type self is not type other raise typeerror return enumvalue name name format self other self value other value self type def and self other if other is none return self elif type self is not type other raise typeerror return enumvalue name name format self other self value other value self type def contains self other if self value other value return true return bool self other def invert self enumerables self type enumerables return functools reduce enumvalue or enum for enum in enumerables itervalues if enum not in self property def name self return self name property def value self return self value class enummeta type staticmethod def addtoreverselookup rev value newkeys nextiter force true if value in rev forced items rev get value force if forced and force value was forced so just append rev value true items newkeys elif not forced move it to new spot next nextiter next enummeta addtoreverselookup rev next items nextiter false rev value force newkeys else not forcing this value next nextiter next enummeta addtoreverselookup rev next newkeys nextiter false rev value force newkeys else set it and forget it rev value force newkeys return value def init cls name bases atts classvars vars cls enums classvars get enumerables none nextiter getattr cls nextitr itertools count reverselookup values if enums is not none build reverse lookup for item in enums if isinstance item tuple list items list item value items pop enummeta addtoreverselookup reverselookup value tuple map str items nextiter else value nextiter next value enummeta addtoreverselookup reverselookup value str item nextiter false add it to the reverse lookup but do not force it to that value build values and clean up reverse lookup for value fkeys in reverselookup iteritems keys fkeys for key in keys enum enumvalue key value cls setattr cls key enum values key enum reverselookup value tuple val for val in values itervalues if val value value setattr cls reverselookup reverselookup setattr cls enumerables values setattr cls max max key for key in reverselookup or return super enummeta cls init name bases atts def iter cls for enum in cls enumerables itervalues yield enum def getenumbyname cls name return cls enumerables get name none def getenumbyvalue cls value return cls reverselookup get value none class enum object metaclass enummeta enumerables none class flagenum enum staticmethod def nextitr yield for val in itertools count yield val def enum name args return enummeta name enum dict enumerables args take it or leave it it did what needed it to do use it like class air flagenum enumerables none oxygen nitrogen hydrogen class mammals enum enumerables bat whale dog puppy cat bool enum bool yes no
|
QA
|
ensure single instance of an application in linux am working on gui application in wxpython and am not sure how can ensure that only one copy of my application is running at any given time on the machine due to the nature of the application running more than once does not make any sense and will fail quickly under win can simply make named mutex and check that at startup unfortunately do not know of any facilities in linux that can do this am looking for something that will automatically be released should the application crash unexpectedly do not want to have to burden my users with having to manually delete lock files because crashed
|
can you use the pidof utility if your app is running pidof will write the process id of your app to stdout if not it will print newline lf and return an error code example from bash for simplicity linux pidof myapp linux pidof nonexistent app linux
|
QA
|
ensure single instance of an application in linux am working on gui application in wxpython and am not sure how can ensure that only one copy of my application is running at any given time on the machine due to the nature of the application running more than once does not make any sense and will fail quickly under win can simply make named mutex and check that at startup unfortunately do not know of any facilities in linux that can do this am looking for something that will automatically be released should the application crash unexpectedly do not want to have to burden my users with having to manually delete lock files because crashed
|
by far the most common method is to drop file into var run called application pid which contains only the pid of the running process or parent process as an alternative you can create named pipe in the same directory to be able to send messages to the active process to open new file
|
QA
|
ensure single instance of an application in linux am working on gui application in wxpython and am not sure how can ensure that only one copy of my application is running at any given time on the machine due to the nature of the application running more than once does not make any sense and will fail quickly under win can simply make named mutex and check that at startup unfortunately do not know of any facilities in linux that can do this am looking for something that will automatically be released should the application crash unexpectedly do not want to have to burden my users with having to manually delete lock files because crashed
|
there are several common techniques including using semaphores the one see used most often is to create pid lock file on startup that contains the pid of the running process if the file already exists when the program starts up open it up and grab the pid inside check to see if process with that pid is running if it is check the cmdline value in proc pid to see if it is an instance of your program if it is then quit otherwise overwrite the file with your pid the usual name for the pid file is application name pid
|
QA
|
ensure single instance of an application in linux am working on gui application in wxpython and am not sure how can ensure that only one copy of my application is running at any given time on the machine due to the nature of the application running more than once does not make any sense and will fail quickly under win can simply make named mutex and check that at startup unfortunately do not know of any facilities in linux that can do this am looking for something that will automatically be released should the application crash unexpectedly do not want to have to burden my users with having to manually delete lock files because crashed
|
the set of functions defined in semaphore sem open sem trywait etc are the posix equivalent believe
|
QA
|
ensure single instance of an application in linux am working on gui application in wxpython and am not sure how can ensure that only one copy of my application is running at any given time on the machine due to the nature of the application running more than once does not make any sense and will fail quickly under win can simply make named mutex and check that at startup unfortunately do not know of any facilities in linux that can do this am looking for something that will automatically be released should the application crash unexpectedly do not want to have to burden my users with having to manually delete lock files because crashed
|
look for python module that interfaces to sysv semaphores on unix the semaphores have sem undo flag which will cause the resources held by the process to be released if the process crashes otherwise as bernard suggested you can use import os os getpid and write it to var run application name pid when the process starts it should check if the pid in var run application name pid is listed in the ps table and quit if it is otherwise write its own pid into var run application name pid in the following var run pid is the pid you read from var run application name pid cmd ps comm var run pid app name os popen cmd read strip if len app name already running
|
QA
|
ensure single instance of an application in linux am working on gui application in wxpython and am not sure how can ensure that only one copy of my application is running at any given time on the machine due to the nature of the application running more than once does not make any sense and will fail quickly under win can simply make named mutex and check that at startup unfortunately do not know of any facilities in linux that can do this am looking for something that will automatically be released should the application crash unexpectedly do not want to have to burden my users with having to manually delete lock files because crashed
|
the right thing is advisory locking using flock lock ex in python this is found in the fcntl module unlike pidfiles these locks are always automatically released when your process dies for any reason have no race conditions exist relating to file deletion as the file does not need to be deleted to release the lock and there is no chance of different process inheriting the pid and thus appearing to validate stale lock if you want unclean shutdown detection you can write marker such as your pid for traditionalists into the file after grabbing the lock and then truncate the file to byte status before clean shutdown while the lock is being held thus if the lock is not held and the file is non empty an unclean shutdown is indicated
|
QA
|
including pyds dlls in py exe builds one of the modules for my app uses functions from pyd file there is an option to exclude dlls exclude dlls but is there one for including them the build process does not seem to be copying the pyd in my module despite copying the rest of the files py also need to include dll how do get py exe to include both pyd and dll files
|
if they are not being automatically detected try manually copying them into py exe temporary build directory they will be included in the final executable
|
QA
|
can you add new statements to python syntax can you add new statements like print raise with to python syntax say to allow mystatement something or new if true print example not so much if you should but rather if it is possible short of modifying the python interpreters code
|
general answer you need to preprocess your source files more specific answer install easyextend and go through following steps create new langlet extension language import easyextend easyextend new langlet mystmts prompt my source ext mypy without additional specification bunch of files shall be created under easyextend langlets mystmts ii open mystmts parsedef grammar ext and add following lines small stmt expr stmt print stmt del stmt pass stmt flow stmt import stmt global stmt exec stmt assert stmt my stmt my stmt mystatement expr this is sufficient to define the syntax of your new statement the small stmt non terminal is part of the python grammar and it is the place where the new statement is hooked in the parser will now recognize the new statement source file containing it will be parsed the compiler will reject it though because it still has to be transformed into valid python iii now one has to add semantics of the statement for this one has to edit msytmts langlet py and add my stmt node visitor def call my stmt expression defines behaviour for my stmt print my stmt called with expression class langlettransformer transformer transform def my stmt self node expr find node node symbol expr return any stmt cst callfunc call my stmt expr publish call my stmt iv cd to langlets mystmts and type python run mystmts py now session shall be started and the newly defined statement can be used mystmts on python apr msc bit intel my mystatement my stmt called with quite few steps to come to trivial statement right there is not an api yet that let us one define simple things without having to care about grammars but ee is very reliable modulo some bugs so it is just matter of time that an api emerges that let us programmers define convenient stuff like infix operators or small statements using just convenient oo programming for more complex things like embedding whole languages in python by means of building langlet there is no way of going around full grammar approach
|
QA
|
including pyds dlls in py exe builds one of the modules for my app uses functions from pyd file there is an option to exclude dlls exclude dlls but is there one for including them the build process does not seem to be copying the pyd in my module despite copying the rest of the files py also need to include dll how do get py exe to include both pyd and dll files
|
you can modify the setup script to copy the files explicitly script pyinvaders py name of starting py project name os path splitext os path split script setup name project name scripts script this installs the program also need to hand copy the extra files here def installfile name dst os path join dist project name print copying name dst if os path isdir name dst os path join dst name if os path isdir dst shutil rmtree dst shutil copytree name dst elif os path isfile name shutil copy name dst else print warning not found name pygamedir os path split pygame base file installfile os path join pygamedir pygame font get default font installfile os path join pygamedir pygame icon bmp for data in extra data installfile data etc modify to suit your needs of course
|
QA
|
load dll from python am building python application from some source code have found here have managed to compile and fix some problems by searching the web but am stuck at this point when running the application this message appears this python app usues swig to link to code have vc express edition which used to compile along with scons and python and tried too the dlls that are attempting to load is msvcr dll because before the message was msvcr dll cannot be found or something like that so got it and drop it in window folder for what have read in here http msdn microsoft com en us library ms vs aspx the solution is to run mt with the manifest and the dll file did it already and does not work either could anyone point me to the correct direction this is the content of the manifest fie xml version encoding utf standalone yes assembly xmlns urn schemas microsoft com asm manifestversion dependency dependentassembly assemblyidentity type win name microsoft vc crt version processorarchitecture publickeytoken fc dependentassembly dependency assembly am going to try python now am not quite sure of understanding the problem but python and python exe had the string msvcr dll inside the exe file but probably this has nothing to do ps if only everything was as easy as jar files this is the stack trace for completeness none info root skipping provider enso platform osx info root skipping provider enso platform linux info root added provider enso platform win traceback most recent call last file scripts run enso py line in module enso run file oreyes apps enso enso read only enso init py line in run from enso events import eventmanager file oreyes apps enso enso read only enso events py line in module from enso import input file oreyes apps enso enso read only enso input init py line in module input enso providers getinterface input file oreyes apps enso enso read only enso providers py line in getinterface interface provider provideinterface name file oreyes apps enso enso read only enso platform win init py line in provideinterface import enso platform win input file oreyes apps enso enso read only enso platform win input init py line in module from inputmanager import file oreyes apps enso enso read only enso platform win input inputmanager py line in module import inputmanager importerror dll load failed error en una rutina de inicializaci de biblioteca de nculos din micos dll
|
you probably need to install the vc runtime redistributables the links to them are here
|
QA
|
load dll from python am building python application from some source code have found here have managed to compile and fix some problems by searching the web but am stuck at this point when running the application this message appears this python app usues swig to link to code have vc express edition which used to compile along with scons and python and tried too the dlls that are attempting to load is msvcr dll because before the message was msvcr dll cannot be found or something like that so got it and drop it in window folder for what have read in here http msdn microsoft com en us library ms vs aspx the solution is to run mt with the manifest and the dll file did it already and does not work either could anyone point me to the correct direction this is the content of the manifest fie xml version encoding utf standalone yes assembly xmlns urn schemas microsoft com asm manifestversion dependency dependentassembly assemblyidentity type win name microsoft vc crt version processorarchitecture publickeytoken fc dependentassembly dependency assembly am going to try python now am not quite sure of understanding the problem but python and python exe had the string msvcr dll inside the exe file but probably this has nothing to do ps if only everything was as easy as jar files this is the stack trace for completeness none info root skipping provider enso platform osx info root skipping provider enso platform linux info root added provider enso platform win traceback most recent call last file scripts run enso py line in module enso run file oreyes apps enso enso read only enso init py line in run from enso events import eventmanager file oreyes apps enso enso read only enso events py line in module from enso import input file oreyes apps enso enso read only enso input init py line in module input enso providers getinterface input file oreyes apps enso enso read only enso providers py line in getinterface interface provider provideinterface name file oreyes apps enso enso read only enso platform win init py line in provideinterface import enso platform win input file oreyes apps enso enso read only enso platform win input init py line in module from inputmanager import file oreyes apps enso enso read only enso platform win input inputmanager py line in module import inputmanager importerror dll load failed error en una rutina de inicializaci de biblioteca de nculos din micos dll
|
have been able to compile and run enso by using ld as compiler flag this links dynamically to the ms visual runtime and seems to allow you to get away without manifest if you are using scons see the different file here http paste org
|
QA
|
what is the best way on python for windows to execute program like ghostscript with multiple arguments and spaces in paths surely there is some kind of abstraction that allows for this this is essentially the command cmd self ghostscriptpath gswin dnopause dbatch sdevice tiffg spapersize soutputfile tifdest pdfsource os popen cmd this way looks really dirty to me there must be some pythonic way
|
use subprocess it superseeds os popen though it is not much more of an abstraction from subprocess import popen pipe output popen mycmd myarg stdout pipe communicate this is how would mangle the arguments together output popen self ghostscriptpath gswin dnopause dbatch sdevice tiffg spapersize soutputfile tifdest pdfsource stdout pipe communicate if you have only python which has no subprocess module you can still use os popen os popen join self ghostscriptpath gswin dnopause dbatch sdevice tiffg spapersize soutputfile tifdest pdfsource
|
QA
|
ensure single instance of an application in linux am working on gui application in wxpython and am not sure how can ensure that only one copy of my application is running at any given time on the machine due to the nature of the application running more than once does not make any sense and will fail quickly under win can simply make named mutex and check that at startup unfortunately do not know of any facilities in linux that can do this am looking for something that will automatically be released should the application crash unexpectedly do not want to have to burden my users with having to manually delete lock files because crashed
|
complete locking solution using the fcntl module import fcntl pid file program pid fp open pid file try fcntl lockf fp fcntl lock ex fcntl lock nb except ioerror another instance is running sys exit
|
QA
|
load dll from python am building python application from some source code have found here have managed to compile and fix some problems by searching the web but am stuck at this point when running the application this message appears this python app usues swig to link to code have vc express edition which used to compile along with scons and python and tried too the dlls that are attempting to load is msvcr dll because before the message was msvcr dll cannot be found or something like that so got it and drop it in window folder for what have read in here http msdn microsoft com en us library ms vs aspx the solution is to run mt with the manifest and the dll file did it already and does not work either could anyone point me to the correct direction this is the content of the manifest fie xml version encoding utf standalone yes assembly xmlns urn schemas microsoft com asm manifestversion dependency dependentassembly assemblyidentity type win name microsoft vc crt version processorarchitecture publickeytoken fc dependentassembly dependency assembly am going to try python now am not quite sure of understanding the problem but python and python exe had the string msvcr dll inside the exe file but probably this has nothing to do ps if only everything was as easy as jar files this is the stack trace for completeness none info root skipping provider enso platform osx info root skipping provider enso platform linux info root added provider enso platform win traceback most recent call last file scripts run enso py line in module enso run file oreyes apps enso enso read only enso init py line in run from enso events import eventmanager file oreyes apps enso enso read only enso events py line in module from enso import input file oreyes apps enso enso read only enso input init py line in module input enso providers getinterface input file oreyes apps enso enso read only enso providers py line in getinterface interface provider provideinterface name file oreyes apps enso enso read only enso platform win init py line in provideinterface import enso platform win input file oreyes apps enso enso read only enso platform win input init py line in module from inputmanager import file oreyes apps enso enso read only enso platform win input inputmanager py line in module import inputmanager importerror dll load failed error en una rutina de inicializaci de biblioteca de nculos din micos dll
|
update have downloaded python and vs express edition and the problem with the msvcr dll is gone assume because python and vsc xe use msvscr dll have compile with ld and all the changes listed here http paste org and now the problem follows info root skipping provider enso platform osx info root skipping provider enso platform linux info root added provider enso platform win info root obtained interface input from provider enso platform win traceback most recent call last file scripts run enso py line in module enso run file oreyes apps enso enso comunity enso init py line in run from enso quasimode import quasimode file oreyes apps enso enso comunity enso quasimode init py line in module from enso quasimode window import thequasimodewindow file oreyes apps enso enso comunity enso quasimode window py line in module from enso quasimode linewindows import textwindow file oreyes apps enso enso comunity enso quasimode linewindows py line in module from enso import cairo file oreyes apps enso enso comunity enso cairo py line in module cairoimpl enso providers getinterface cairo file oreyes apps enso enso comunity enso providers py line in getinterface interface provider provideinterface name file oreyes apps enso enso comunity enso platform win init py line in provideinterface import enso platform win cairo file oreyes apps enso enso comunity enso platform win cairo init py line in module from cairo import importerror no module named cairo
|
QA
|
how can write method within django model to retrieve related objects have two models we will call them object and object their design looks something like this class foo models model name models charfield class bar models model title models charfield foo models foreignkey myapp foo now suppose want to make method within foo that returns all bar objects that reference that instance of foo how do do this class foo models model name models charfield def returnbars self
|
you get this for free http docs djangoproject com en dev topics db queries backwards related objects by default you can access manager which gives you access to related items through relatedclassname set attribute some foo bar set all or you can use the related name argument to foreignkey to specify the attribute which should hold the reverse relationship manager class foo models model name models charfield class bar models model title models charfield foo models foreignkey foo related name bars some foo bars all
|
QA
|
putting copyright symbol into python file need to include copyright statement at the top of every python source file produce copyright etc however when then run such file get this message syntaxerror non ascii character xa in file myfile py on line but no encoding declared see http www python org peps pep html for details apparently python is not happy about the copyright symbol because it assumes the source file is all in ascii either need to make my first line be coding iso to tell python am using latin encoding or can change the copyright statement to copyright xa etc which just possibly does not have the same legal standing is there more elegant solution
|
the copyright symbol in ascii is spelled or copyright see circular copyright registration for computer programs while it is true that the legal formalism see circular copyright basics is the symbol the letter in circle or the word copyright or the abbreviation copr and and it is also true that to guarantee protection for copyrighted work in all ucc member countries the notice must consist of the symbol the word copyright or the abbreviation is not acceptable you can dig through circular and this has however already been tested in court it is not an interesting issue if you do search for acceptable for in circle you will find that lawyers all agree that is an acceptable substitute see perle and williams see scott on information technology law
|
QA
|
putting copyright symbol into python file need to include copyright statement at the top of every python source file produce copyright etc however when then run such file get this message syntaxerror non ascii character xa in file myfile py on line but no encoding declared see http www python org peps pep html for details apparently python is not happy about the copyright symbol because it assumes the source file is all in ascii either need to make my first line be coding iso to tell python am using latin encoding or can change the copyright statement to copyright xa etc which just possibly does not have the same legal standing is there more elegant solution
|
you can always revert to good old
|
QA
|
removing sequence of characters from large binary file using python would like to trim long sequences of the same value from binary file in python simple way of doing it is simply reading in the file and using re sub to replace the unwanted sequence this will of course not work on large binary files can it be done in something like numpy
|
if two copies fit in memory then you can easily make copy the second copy is the compressed version sure you can use numpy but you can also use the array package additionally you can treat your big binary object as string of bytes and manipulate it directly it sounds like your file may be really large and you cannot fit two copies into memory you did not provide lot of details so this is just guess you will have to do your compression in chunks you will read in chunk do some processing on that chunk and write it out again numpy array or simple string of bytes will work fine
|
QA
|
putting copyright symbol into python file need to include copyright statement at the top of every python source file produce copyright etc however when then run such file get this message syntaxerror non ascii character xa in file myfile py on line but no encoding declared see http www python org peps pep html for details apparently python is not happy about the copyright symbol because it assumes the source file is all in ascii either need to make my first line be coding iso to tell python am using latin encoding or can change the copyright statement to copyright xa etc which just possibly does not have the same legal standing is there more elegant solution
|
waiting for python where the default encoding of the source will be utf
|
QA
|
putting copyright symbol into python file need to include copyright statement at the top of every python source file produce copyright etc however when then run such file get this message syntaxerror non ascii character xa in file myfile py on line but no encoding declared see http www python org peps pep html for details apparently python is not happy about the copyright symbol because it assumes the source file is all in ascii either need to make my first line be coding iso to tell python am using latin encoding or can change the copyright statement to copyright xa etc which just possibly does not have the same legal standing is there more elegant solution
|
contrary to the accepted answer afaik is not an officially recognized alternative to the copyright symbol although am not sure it is been tested in court however is just an abreviation of the word copyright saying copyright robert munro is identical to saying robert munro your copyright etc expands to copyright copyright etc wikipedia page seems to agree with me http en wikipedia org wiki copyright symbol in the united states the copyright notice consists of three elements the symbol or the word copyright or abbreviation copr
|
QA
|
putting copyright symbol into python file need to include copyright statement at the top of every python source file produce copyright etc however when then run such file get this message syntaxerror non ascii character xa in file myfile py on line but no encoding declared see http www python org peps pep html for details apparently python is not happy about the copyright symbol because it assumes the source file is all in ascii either need to make my first line be coding iso to tell python am using latin encoding or can change the copyright statement to copyright xa etc which just possibly does not have the same legal standing is there more elegant solution
|
answers to this question particularly ben combee answer should be helpful
|
QA
|
is it possible to implement python code completion in textmate pysmell seems like good starting point think it should be possible pysmell idehelper py does majority of the complex stuff it should just be case of giving it the current line offering up the completions the bit am not sure about and then replacing the line with the selected one import idehelper the path is where my pysmelltags file is located pysmelldict idehelper findpysmelldict users dbr desktop pysmell options idehelper detectcompletiontype pysmelldict completions idehelper findcompletions proc pysmelldict options print completions dup menu pysmell pysmell kind word process abbr process arglist excluded output verbose false it will never be perfect but it would be extremely useful even if just for completing the stdlib modules which should never change so you will not have to constantly regenerate the pysmelltags file whenever you add function progressing have the utter basics of completion in place barely works but it is close ran python pysmells py system library frameworks python framework versions lib python py library python site packages pysmell pysmelltags place the following in textmate bundle script set input entire document output insert as text activation key equivalent alt esc scope selector source python usr bin env python import os import sys from pysmell import idehelper cur word os environ get tm current word cur file os environ get tm filepath orig source sys stdin read line no int os environ get tm line number cur col int os environ get tm line index pysmells is currently in site packages pysmell pysmelldict idehelper findpysmelldict library python site packages pysmell blah options idehelper detectcompletiontype cur file orig source line no cur col pysmelldict completions idehelper findcompletions cur word pysmelldict options if len completions new word completions word new word new word replace cur word remove what user has already typed print new word then made new python document typed import urll and hit alt escape and it completed it to import urllib as said it is entirely work in progress so do not use it yet last update orestis has integrated this into the pysmell project code any further fiddling will happen on github
|
this is not exactly what you are looking for but it might be able to get you started using textmate with django they appear to be somewhat django specific but some snippets may assist with your needs you also may be able to build on top of that with pysmells
|
QA
|
removing sequence of characters from large binary file using python would like to trim long sequences of the same value from binary file in python simple way of doing it is simply reading in the file and using re sub to replace the unwanted sequence this will of course not work on large binary files can it be done in something like numpy
|
you need to make your question more precise do you know the values you want to trim ahead of time assuming you do would probably search for the matching sections using subprocess to run fgrep search string and then change the relevant sections of the file using the python file object seek read and write methods
|
QA
|
is it possible to set timeout on socket in twisted realize am probably just dumb and missing something big and important but cannot figure out how to specify timeout in twisted using reactor listenudp my goal is to be able to specify timeout and after said amount of time if datagramprotocol datagramreceived has not been executed have it execute callback or something that can use to call reactor stop any help or advice is appreciated thanks
|
since twisted is event driven you do not need timeout per se you simply need to set state variable like datagramrecieved when you receive datagram and register looping call that checks the state variable stops the reactor if appropriate then clears state variable from twisted internet import task from twisted internet import reactor datagramrecieved false timeout one second udp code here def testtimeout global datagramrecieved if not datagramrecieved reactor stop datagramrecieved false task loopingcall testtimeout start timeout call every second stop will stop the looping calls reactor run
|
QA
|
removing sequence of characters from large binary file using python would like to trim long sequences of the same value from binary file in python simple way of doing it is simply reading in the file and using re sub to replace the unwanted sequence this will of course not work on large binary files can it be done in something like numpy
|
if you do not have the memory to do open big file read then numpy will not really help it uses the same memory as python variables do if you have gb of ram you can only load gb of data into numpy the solution is simple read the file in chunks open big file rb then do series of read remove the sequence and write it back out to another file object pretty much how you do file reading writing in the problem then is if you miss the pattern you are replacing for example target seq input file target seq read reads does not contain target seq read reads does not contain the obvious solution is to start at the first character in the file check len target seq characters then go forward one character check forward again for example pseudo code while cur data seek start chunk size len target seq input file seek offset seek start whence whence means seek from start of file offset cur data input file read chunk size reads if target seq cur data found it out file write replacement string else not it shove it in the new file out file write cur data seek start it is not exactly the most efficient way but it will work and not require keeping copy of the file in memory or two
|
QA
|
pros and cons of different approaches to web programming in python would like to do some server side scripting using python but am kind of lost with the number of ways to do that it starts with the do it yourself cgi approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves and huge lot of stuff in between like web py pyroxide and django what are the pros and cons of the frameworks or approaches that you have worked on what trade offs are there for what kind of projects they do well and for what they do not edit have not got much experience with web programing yet would like to avoid the basic and tedious things like parsing the url for parameters etc on the other hand while the video of blog created in minutes with ruby on rails left me impressed realized that there were hundreds of things hidden from me which is cool if you need to write working webapp in no time but not that great for really understanding the magic and that is what seek now
|
it is always worth doing something the hard way once as learning exercise once you understand how it works pick framework that suits your application and use that you do not need to reinvent the wheel once you understand angular velocity it is also worth making sure that you have fairly robust understanding of the programming language behind the framework before you jump in trying to learn both django and python at the same time or ruby and rails or and can lead to even more confusion write some code in the language first then add the framework we learn to develop not by using tools but by solving problems run into few walls climb over and find some higher walls
|
QA
|
how can use sharepoint via soap from python want to use sharepoint with python python has anyone tried this before
|
to get the wsdl import sys we use suds https fedorahosted org suds from suds import webfault from suds client import import urllib my url conf url sharepoint url ntlm authproxy import myconfig as my build url wsdl vti bin sitedata asmx wsdl url join my url sharepoint wsdl we need ntlm auth proxy http ntlmaps sourceforge net follow instruction and get proxy running proxy handler urllib proxyhandler http my url ntlm authproxy opener urllib build opener proxy handler client soapclient url opener opener print client wsdl main mean problem the sharepoint server uses ntlm auth so had to use the ntlm auth proxy to rob and enzondio thanks for your hints
|
QA
|
load dll from python am building python application from some source code have found here have managed to compile and fix some problems by searching the web but am stuck at this point when running the application this message appears this python app usues swig to link to code have vc express edition which used to compile along with scons and python and tried too the dlls that are attempting to load is msvcr dll because before the message was msvcr dll cannot be found or something like that so got it and drop it in window folder for what have read in here http msdn microsoft com en us library ms vs aspx the solution is to run mt with the manifest and the dll file did it already and does not work either could anyone point me to the correct direction this is the content of the manifest fie xml version encoding utf standalone yes assembly xmlns urn schemas microsoft com asm manifestversion dependency dependentassembly assemblyidentity type win name microsoft vc crt version processorarchitecture publickeytoken fc dependentassembly dependency assembly am going to try python now am not quite sure of understanding the problem but python and python exe had the string msvcr dll inside the exe file but probably this has nothing to do ps if only everything was as easy as jar files this is the stack trace for completeness none info root skipping provider enso platform osx info root skipping provider enso platform linux info root added provider enso platform win traceback most recent call last file scripts run enso py line in module enso run file oreyes apps enso enso read only enso init py line in run from enso events import eventmanager file oreyes apps enso enso read only enso events py line in module from enso import input file oreyes apps enso enso read only enso input init py line in module input enso providers getinterface input file oreyes apps enso enso read only enso providers py line in getinterface interface provider provideinterface name file oreyes apps enso enso read only enso platform win init py line in provideinterface import enso platform win input file oreyes apps enso enso read only enso platform win input init py line in module from inputmanager import file oreyes apps enso enso read only enso platform win input inputmanager py line in module import inputmanager importerror dll load failed error en una rutina de inicializaci de biblioteca de nculos din micos dll
|
looking at your update it looks like you need to install pycairo since you are missing the cairo module installed as part of pycairo see the pycairo downloads page for instructions on how to obtain install binaries for windows
|
QA
|
best approach with dynamic classes using python globals am working on web application that will return variable set of modules depending on user input each module is python class with constructor that accepts single parameter and has an html property that contains the output pulling the class dynamically from the global namespace works result globals classname param html and it is certainly more succinct than if classname foo result foo param html elif classname bar what is considered the best way to write this stylistically are there risks or reasons not to use the global namespace
|
first of all it sounds like you may be reinventing the wheel little bit most python web frameworks cherrypy turbogears is what know already include way to dispatch requests to specific classes based on the contents of the url or the user input there is nothing wrong with the way that you do it really but in my experience it tends to indicate some kind of missing abstraction in your program you are basically relying on the python interpreter to store list of the objects you might need rather than storing it yourself so as first step you might want to just make dictionary of all the classes that you might want to call dispatch foo foo bar bar bizbaz bizbaz initially this will not make much of difference but as your web app grows you may find several advantages you will not run into namespace clashes using globals you may have security issues where an attacker can in essence access any global symbol in your program if they can find way to inject an arbitrary classname into your program if you ever want to have classname be something other than the actual exact classname using your own dictionary will be more flexible you can replace the dispatch dictionary with more flexible user defined class that does database access or something like that if you find the need the security issues are particularly salient for web app doing globals variable where variable is input from web form is just asking for trouble
|
QA
|
best approach with dynamic classes using python globals am working on web application that will return variable set of modules depending on user input each module is python class with constructor that accepts single parameter and has an html property that contains the output pulling the class dynamically from the global namespace works result globals classname param html and it is certainly more succinct than if classname foo result foo param html elif classname bar what is considered the best way to write this stylistically are there risks or reasons not to use the global namespace
|
flaw with this approach is that it may give the user the ability to to more than you want them to they can call any single parameter function in that namespace just by providing the name you can help guard against this with few checks eg isinstance somebaseclass theclass but its probably better to avoid this approach another disadvantage is that it constrains your class placement if you end up with dozens of such classes and decide to group them into modules your lookup code will stop working you have several alternative options create an explicit mapping class lookup class class result class lookup classname param html though this has the disadvantage that you have to re list all the classes nest the classes in an enclosing scope eg define them within their own module or within an outer class class namespace object class class object class class object result getattr namespace classname param html you do inadvertantly expose couple of additional class variables here though bases getattribute etc probably not exploitable but not perfect construct lookup dict from the subclass tree make all your classes inherit from single baseclass when all classes have been created examine all baseclasses and populate dict from them this has the advantage that you can define your classes anywhere eg in seperate modules and so long as you create the registry after all are created you will find them def register subclasses base for cls in base subclasses cls name cls update register subclasses cls return class lookup register subclasses mybaseclass more advanced variation on the above is to use self registering classes create metaclass than automatically registers any created classes in dict this is probably overkill for this case its useful in some user plugins scenarios though
|
QA
|
python code generator for visual studio had an idea if add python py file to my project and tag the file with custom generator that would execute the python file and treat the output as the result of the code generation ie put it into file that would allow me to do quite lot of code generation as part of the build process does anyone know if such custom generator for visual studio exists
|
think cog does what you want
|
QA
|
how to script visual studio from python would like to write python scripts that drive visual studio and visual all the examples have found so far use win com client dispatch this works fine for excel and word but fails for visual studio import win com client app win com client dispatch excel application ok app win com client dispatch word application ok app win com client dispatch msdev application error any ideas does visual studio use different string to identify itself is the above method out dated
|
you can try net own version ironpython it has vs addon ironpythonstudio being net language you can access all the available assemblies including visual studio tools for office
|
QA
|
elementtree xpath select element based on attribute am having trouble using the attribute xpath selector in elementtree which should be able to do according to the documentation here is some sample code xml root target name target target name target root python def parse document root et parse document for target in root findall target name print target children am receiving the following exception expected path separator
|
looks like findall only supports subset xpath see the mailing list discussion here
|
QA
|
elementtree xpath select element based on attribute am having trouble using the attribute xpath selector in elementtree which should be able to do according to the documentation here is some sample code xml root target name target target name target root python def parse document root et parse document for target in root findall target name print target children am receiving the following exception expected path separator
|
the syntax you are trying to use is new in elementtree such version is shipped with python or higher if you have python or less you still have elementtree or less
|
QA
|
what is the meaning of password in python regular expression pexpect can be used to automate tasks in python does not need tcl to be installed one of the simplest routines of this class is the run routine it accepts dictionary of expected question patterns as keys and the responses as values for example pexpect run scp foo myname host example com events password mypassword know that usually is used to indicate or occurrences of previous literal in the string for regular expressions that is however over here this does not seem to be the meaning can experts comment on what is it
|
https docs python org library re html regular expression syntax this is an extension notation following is not meaningful otherwise the first character after the determines what the meaning and further syntax of the construct is extensions usually do not create new group is the only exception to this rule following are the currently supported extensions ilmsux one or more letters from the set you the group matches the empty string the letters set the corresponding flags re re re re re you re for the entire regular expression this is useful if you wish to include the flags as part of the regular expression instead of passing flag argument to the compile function note that the flag changes how the expression is parsed it should be used first in the expression string or after one or more whitespace characters if there are non whitespace characters before the flag the results are undefined so in this case the string is regular expression and is set to be case insensitive
|
QA
|
what is the meaning of password in python regular expression pexpect can be used to automate tasks in python does not need tcl to be installed one of the simplest routines of this class is the run routine it accepts dictionary of expected question patterns as keys and the responses as values for example pexpect run scp foo myname host example com events password mypassword know that usually is used to indicate or occurrences of previous literal in the string for regular expressions that is however over here this does not seem to be the meaning can experts comment on what is it
|
this is an extension in the regular expression syntax in the re module of python the means ignore case this means case insensitive search for password is done from https docs python org library re html regular expression syntax ilmsux one or more letters from the set you the group matches the empty string the letters set the corresponding flags re re re re re you re for the entire regular expression this is useful if you wish to include the flags as part of the regular expression instead of passing flag argument to the compile function note that the flag changes how the expression is parsed it should be used first in the expression string or after one or more whitespace characters if there are non whitespace characters before the flag the results are undefined
|
QA
|
stunned weird problem with python and sockets threads have python script that is http server http paste org when benchmarking it against apachebench ab with concurrency level switch that is lower then or equal to the value specified in the socket listen call in the sourcecode everything works fine but as soon as put the concurrency level in apache bench above the value in the socket listen call performance drops through the floor some example socket listen and ab http localhost req socket listen and ab http localhost req socket listen and ab http localhost req socket listen and ab http localhost req nothing changes in the code between the two calls can figure out what is wrong been at this problem for one day now also note that the multiplexing version of the same code wrote to compare to the threaded version works fine no matter what socket listen is set to or what the concurrency switch in apache is set to have spent day on irc python docs posted on comp lang python and on my blog cannot find anyone that even has an idea what could be wrong help me
|
ok so ran the code on totally different server vps got at slicehost not single problem everything works as expected so honestly think it is something wrong with my laptop now thanks for everyone is help though
|
QA
|
sorting tuple that contains tuples have the following tuple which contains tuples my tuple apple carrot banana would like to sort this tuple based upon the second value contained in inner tuples sort apple carrot banana rather than any thoughts
|
from operator import itemgetter my sorted tuple tuple sorted my tuple key itemgetter or without itemgetter my sorted tuple tuple sorted my tuple key lambda item item
|
QA
|
sorting tuple that contains tuples have the following tuple which contains tuples my tuple apple carrot banana would like to sort this tuple based upon the second value contained in inner tuples sort apple carrot banana rather than any thoughts
|
sorted my tuple key lambda tup tup in other words when comparing two elements of the tuple you are sorting sort based on the return value of the function passed as the key parameter
|
QA
|
sorting tuple that contains tuples have the following tuple which contains tuples my tuple apple carrot banana would like to sort this tuple based upon the second value contained in inner tuples sort apple carrot banana rather than any thoughts
|
from sorting mini how to often there is built in that will match your needs such as str lower the operator module contains number of functions useful for this purpose for example you can sort tuples based on their second element using operator itemgetter import operator would map operator itemgetter would map operator itemgetter sorted key operator itemgetter would hope this helps
|
QA
|
how to use super in python can someone explain to me the difference between doing class child somebaseclass def init self super child self init and this class child somebaseclass def init self somebaseclass init self have seen super being used quite lot in classes with only single inheritance can see why you would use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation
|
the benefits of super in single inheritance are minimal mostly you do not have to hard code the name of the base class into every method that uses its parent methods however it is almost impossible to use multiple inheritance without super this includes common idioms like mixins interfaces abstract classes etc this extends to code that later extends yours if somebody later wanted to write class that extended child and mixin their code would not work properly
|
QA
|
how to script visual studio from python would like to write python scripts that drive visual studio and visual all the examples have found so far use win com client dispatch this works fine for excel and word but fails for visual studio import win com client app win com client dispatch excel application ok app win com client dispatch word application ok app win com client dispatch msdev application error any ideas does visual studio use different string to identify itself is the above method out dated
|
depending on what exactly you are trying to do autoit may meet your needs in fact am sure it will do anything you need it to do taken from my other post about how to use autoit with python import win com client oautoitx win com client dispatch autoitx control oautoitx opt wintitlematchmode match text anywhere in window title width oautoitx wingetclientsizewidth firefox height oautoitx wingetclientsizeheight firefox print width height you can of course use any of the autoitx functions note that that link goes to the autoit function reference the com version of autoit autoitx has subset of that list the documentation is included in the download in this way do not know what you are wanting to do so cannot point you towards the appropriate functions but this should get you started
|
QA
|
cherrypy not closing the sockets am using cherrypy as webserver it gives good performance for my application but there is very big problem with it cherrypy crashes after couple of hours stating that it could not create socket as there are too many files open oct engine http server cherrypy cpwsgi server cpwsgiserver shut down oct engine stopped thread timeoutmonitor oct engine stopped thread autoreloader oct engine bus stopped oct engine bus exiting oct engine bus exited exception in thread httpserver thread traceback most recent call last file usr lib python threading py line in bootstrap self run file usr lib python threading py line in run self target self args self kwargs file usr lib python site packages cherrypy process servers py line in start http thread self httpserver start file usr lib python site packages cherrypy wsgiserver init py line in start self tick file usr lib python site packages cherrypy wsgiserver init py line in tick addr self socket accept file usr lib python socket py line in accept sock addr self sock accept error too many open files oct engine waiting for child threads to terminate tried to figure out what was happening my application does not open any file or any socket etc my file only opens couple of berkeley dbs investigated this issue further saw the file descriptors used by my cherrypy process with id in proc fd initially there were new sockets created and cleaned up properly but after an hour found that it had about sockets that were not cleaned all the sockets were in close wait state got this information using the following command netstat ap grep grep close wait wc close wait state means that the remote client has closed the connection why is cherrypy then not closing the socket and free the file descriptors what can do to resolve the problem tried to play with the following cherrypy config update server socketqueuesize thought that this would restrict the number of sockets open at any time to but it was not effective at all this is the only config have set so rest of the configs hold their default values could somebody throw light on this do you think its bug in cherrypy how can resolve it is there way can close these sockets myself following is my systems info cherrypy python red hat enterprise linux es release nahant update thanks in advance
|
imagine you are storing in memory some piece of data which has reference to the socket if you store the request objects anywhere for instance that would likely do it the last ditch chance for sockets to be closed is when they are garbage collected if you are doing anything that would prevent garbage collection from reaching them there is your problem suggest that you try to reproduce with hello world program written in cherrypy if you cannot reproduce there you know it is in your code look for places where you are persisting information which could directly or otherwise reference the socket
|
QA
|
python code generator for visual studio had an idea if add python py file to my project and tag the file with custom generator that would execute the python file and treat the output as the result of the code generation ie put it into file that would allow me to do quite lot of code generation as part of the build process does anyone know if such custom generator for visual studio exists
|
dug through my old bookmarks love del icio us and found this article code generation with python cog and nant keep in mind that anything you can do in nant can probably be done in msbuild as well this should be enough to get you started
|
QA
|
when does urllib actually download file from url url http example com file xml data urllib urlopen url data read the question is when exactly will the file be downloaded from the internet when do urlopen or read on my network interface see high traffic both times
|
witout looking at the code would expect that the following happens urlopen opens the connection and sends the query then the server starts feeding the reply at this point the data accumulates in buffers until they are full and the operating system tells the server to hold on for while then data read empties the buffer so the operating system tells the server to go on and the rest of the reply gets downloaded naturally if the reply is short enough or if the read happens quickly enough then the buffers do not have time to fill up and the download happens in one go
|
QA
|
how do you get the text from an html datacell using beautifulsoup have been trying to strip out some data from html files have the logic coded to get the right cells now am struggling to get the actual contents of the cell here is my htm snip headerrows contents font size font face serif size apples produced font size font font font note that this is list item from python need the value apples produced but cannot get to it any suggestions would be appreciated suggestions on good book that explains this would earn my eternal gratitude thanks for that answer however is not there more general answer what happens if my cell does not have bold attribute say it is font size font face serif size apples produced font size font font font apples produced am trying to learn to read understand the documentation and your response will help really appreciate this help the best thing about these answers is that it is lot easier to generalize from them then have been able to do so from the beautifulsoup documentation learned to program in the fortran era and while am enjoying learning python and am amzed at its power beautifulsoup is an example making cohernet whole of the documentation is tough for me cheers
|
the beautifulsoup documentation should cover everything you need in this case it looks like you want to use findnext headerrows findnext string more generic solution which does not rely on the tag would be to use the text argument to findall which allows you to search only for navigablestring objects beautifulsoup you test span more span test you join string for in findall text true you test more test
|
QA
|
using variables for class names in python want to know how to use variables for objects and function names in python in php you can do this classname myclass newobject new classname how do you do this sort of thing in python or am totally not appreciating some fundamental difference with python and if so what is it
|
in python classname myclass newobject classname the first line makes the variable classname refer to the same thing as myclass then the next line calls the myclass constructor through the classname variable as concrete example classname list newobject classname newobject in python list is the constructor for the list class the difference is that in php you represent the name of the class you want to refer to as string while in python you can reference the same class directly if you must use string for example if the name of the class is created dynamically then you will need to use other techniques
|
QA
|
using variables for class names in python want to know how to use variables for objects and function names in python in php you can do this classname myclass newobject new classname how do you do this sort of thing in python or am totally not appreciating some fundamental difference with python and if so what is it
|
if you have this class myclass def init self print myclass then you usually do this myclass myclass but you could also do this which is what think you are asking myclass eval myclass but be very careful about where you get the string that you use eval on if it is come from the user you are essentially creating an enormous security hole
|
QA
|
using variables for class names in python want to know how to use variables for objects and function names in python in php you can do this classname myclass newobject new classname how do you do this sort of thing in python or am totally not appreciating some fundamental difference with python and if so what is it
|
assuming that some module has class named class name import some module klass getattr some module class name some object klass should note that you should be careful here turning strings into code can be dangerous if the string came from the user so you should keep security in mind in this situation one other method assuming that we still are using class name class lookup class name class name some object class lookup class name call the object once we have pulled it out of the dict the latter method is probably the most secure way of doing this so it is probably what you should use if at all possible
|
QA
|
is it possible to implement python code completion in textmate pysmell seems like good starting point think it should be possible pysmell idehelper py does majority of the complex stuff it should just be case of giving it the current line offering up the completions the bit am not sure about and then replacing the line with the selected one import idehelper the path is where my pysmelltags file is located pysmelldict idehelper findpysmelldict users dbr desktop pysmell options idehelper detectcompletiontype pysmelldict completions idehelper findcompletions proc pysmelldict options print completions dup menu pysmell pysmell kind word process abbr process arglist excluded output verbose false it will never be perfect but it would be extremely useful even if just for completing the stdlib modules which should never change so you will not have to constantly regenerate the pysmelltags file whenever you add function progressing have the utter basics of completion in place barely works but it is close ran python pysmells py system library frameworks python framework versions lib python py library python site packages pysmell pysmelltags place the following in textmate bundle script set input entire document output insert as text activation key equivalent alt esc scope selector source python usr bin env python import os import sys from pysmell import idehelper cur word os environ get tm current word cur file os environ get tm filepath orig source sys stdin read line no int os environ get tm line number cur col int os environ get tm line index pysmells is currently in site packages pysmell pysmelldict idehelper findpysmelldict library python site packages pysmell blah options idehelper detectcompletiontype cur file orig source line no cur col pysmelldict completions idehelper findcompletions cur word pysmelldict options if len completions new word completions word new word new word replace cur word remove what user has already typed print new word then made new python document typed import urll and hit alt escape and it completed it to import urllib as said it is entirely work in progress so do not use it yet last update orestis has integrated this into the pysmell project code any further fiddling will happen on github
|
in textmate php has simple auto completion in form of hardcoded set of function names sounds as ugly as php but in practice it is good enough to be useful
|
QA
|
how to script visual studio from python would like to write python scripts that drive visual studio and visual all the examples have found so far use win com client dispatch this works fine for excel and word but fails for visual studio import win com client app win com client dispatch excel application ok app win com client dispatch word application ok app win com client dispatch msdev application error any ideas does visual studio use different string to identify itself is the above method out dated
|
do not know if this will help you with but with visual studio and win com am able to do this import win com client win com client dispatch visualstudio dte comobject visualstudio dte name you microsoft visual studio version you unfortunately do not have to test with though
|
QA
|
elegant structured text file parsing need to parse transcript of live chat conversation my first thought on seeing the file was to throw regular expressions at the problem but was wondering what other approaches people have used put elegant in the title as have previously found that this type of task has danger of getting hard to maintain just relying on regular expressions the transcripts are being generated by www providesupport com and emailed to an account then extract plain text transcript attachment from the email the reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via crm here is an example of transcript file chat transcript visitor random website visitor operator milton company initech started oct finished oct random website visitor where do get the cover sheet for the tps report there are no operators available at the moment if you would like to leave message please type it in the input field below and click send button call accepted by operator milton currently in room milton random website visitor milton excuse me you believe you have my stapler random website visitor really just need the cover sheet okay milton it is not okay because if they take my stapler then will will will set the building on fire random website visitor oh found it thanks anyway random website visitor is now off line and may not reply currently in room milton milton well ok but that is the last straw milton has left the conversation currently in room room is empty visitor details your name random website visitor your question where do get the cover sheet for the tps report ip address host name referrer unknown browser os mozilla compatible msie windows nt net clr infopath net clr
|
using multiline commented regexs can mitigate the maintainance problem somewhat try and avoid the one line super regex also consider breaking the regex down into individual tasks one for each thing you want to get eg visitor text find visitor operator text find operator body text find whatever instead of text match visitor noperator whatever to giant regex do visitor operator etc end then it makes it easy to change how any particular item is parsed as far as parsing through file with many chat blocks just have single simple regex that matches single chat block iterate over the text and pass the match data from this to your group of other matchers this will obviously affect performance but unless you processing enormous files would not worry
|
QA
|
elegant structured text file parsing need to parse transcript of live chat conversation my first thought on seeing the file was to throw regular expressions at the problem but was wondering what other approaches people have used put elegant in the title as have previously found that this type of task has danger of getting hard to maintain just relying on regular expressions the transcripts are being generated by www providesupport com and emailed to an account then extract plain text transcript attachment from the email the reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via crm here is an example of transcript file chat transcript visitor random website visitor operator milton company initech started oct finished oct random website visitor where do get the cover sheet for the tps report there are no operators available at the moment if you would like to leave message please type it in the input field below and click send button call accepted by operator milton currently in room milton random website visitor milton excuse me you believe you have my stapler random website visitor really just need the cover sheet okay milton it is not okay because if they take my stapler then will will will set the building on fire random website visitor oh found it thanks anyway random website visitor is now off line and may not reply currently in room milton milton well ok but that is the last straw milton has left the conversation currently in room room is empty visitor details your name random website visitor your question where do get the cover sheet for the tps report ip address host name referrer unknown browser os mozilla compatible msie windows nt net clr infopath net clr
|
no and in fact for the specific type of task you describe doubt there is cleaner way to do it than regular expressions it looks like your files have embedded line breaks so typically what we will do here is make the line your unit of decomposition applying per line regexes meanwhile you create small state machine and use regex matches to trigger transitions in that state machine this way you know where you are in the file and what types of character data you can expect also consider using named capture groups and loading the regexes from an external file that way if the format of your transcript changes it is simple matter of tweaking the regex rather than writing new parse specific code
|
QA
|
when does urllib actually download file from url url http example com file xml data urllib urlopen url data read the question is when exactly will the file be downloaded from the internet when do urlopen or read on my network interface see high traffic both times
|
agree with ddaa however if you want to understand this sort of thing you can set up dummy server using something like nc in nix and then open the url in the interactive python interpreter in one terminal run nc which will open socket and listen for connections on port of the local machine nc will accept an incoming connection and display whatever it reads from the socket anything you type into nc will be sent over the socket to the remote connection in this case python urlopen run python in another terminal and enter your code data urllib urlopen http data read the call to urlopen will establish the connection to the server send the request and then block waiting for response you will see that nc prints the http request into it is terminal now type something into the terminal that is running nc the call to urlopen will still block until you press enter in nc that is until it receives new line character so urlopen will not return until it has read at least one new line character for those concerned about possible buffering by nc this is not an issue urlopen will block until it sees the first new line character so it should be noted that urlopen will block until the first new line character is received after which data can be read from the connection in practice http responses are short multiline responses so urlopen should return quite quickly
|
QA
|
how do you get the text from an html datacell using beautifulsoup have been trying to strip out some data from html files have the logic coded to get the right cells now am struggling to get the actual contents of the cell here is my htm snip headerrows contents font size font face serif size apples produced font size font font font note that this is list item from python need the value apples produced but cannot get to it any suggestions would be appreciated suggestions on good book that explains this would earn my eternal gratitude thanks for that answer however is not there more general answer what happens if my cell does not have bold attribute say it is font size font face serif size apples produced font size font font font apples produced am trying to learn to read understand the documentation and your response will help really appreciate this help the best thing about these answers is that it is lot easier to generalize from them then have been able to do so from the beautifulsoup documentation learned to program in the fortran era and while am enjoying learning python and am amzed at its power beautifulsoup is an example making cohernet whole of the documentation is tough for me cheers
|
have base class that extend all beautiful soup classes with bunch of methods that help me get at text within group of elements that do not necessarily want to rely on the structure of one of those methods is the following def clean self val if type val is not stringtype val str val val re sub remove tags val re sub val collapse internal whitespace return val strip remove leading trailing whitespace
|
QA
|
how do perform query filtering in django templates need to perform filtered query from within django template to get set of objects equivalent to python code within view queryset modelclass objects filter somekey foo in my template would like to do for object in data somekey set filter but just cannot seem to find out how to write filter
|
you cannot do this which is by design the django framework authors intended strict separation of presentation code from data logic filtering models is data logic and outputting html is presentation logic so you have several options the easiest is to do the filtering then pass the result to render to response or you could write method in your model so that you can say for object in data filtered set finally you could write your own template tag although in this specific case would advise against that
|
QA
|
elegant structured text file parsing need to parse transcript of live chat conversation my first thought on seeing the file was to throw regular expressions at the problem but was wondering what other approaches people have used put elegant in the title as have previously found that this type of task has danger of getting hard to maintain just relying on regular expressions the transcripts are being generated by www providesupport com and emailed to an account then extract plain text transcript attachment from the email the reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via crm here is an example of transcript file chat transcript visitor random website visitor operator milton company initech started oct finished oct random website visitor where do get the cover sheet for the tps report there are no operators available at the moment if you would like to leave message please type it in the input field below and click send button call accepted by operator milton currently in room milton random website visitor milton excuse me you believe you have my stapler random website visitor really just need the cover sheet okay milton it is not okay because if they take my stapler then will will will set the building on fire random website visitor oh found it thanks anyway random website visitor is now off line and may not reply currently in room milton milton well ok but that is the last straw milton has left the conversation currently in room room is empty visitor details your name random website visitor your question where do get the cover sheet for the tps report ip address host name referrer unknown browser os mozilla compatible msie windows nt net clr infopath net clr
|
build parser cannot decide if your data is regular enough for that but it might be worth looking into
|
QA
|
how to use super in python can someone explain to me the difference between doing class child somebaseclass def init self super child self init and this class child somebaseclass def init self somebaseclass init self have seen super being used quite lot in classes with only single inheritance can see why you would use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation
|
does not all of this assume that the base class is inherited from object class def init self print init class def init self print init super self init will not work class must be derived from object class object
|
QA
|
elegant structured text file parsing need to parse transcript of live chat conversation my first thought on seeing the file was to throw regular expressions at the problem but was wondering what other approaches people have used put elegant in the title as have previously found that this type of task has danger of getting hard to maintain just relying on regular expressions the transcripts are being generated by www providesupport com and emailed to an account then extract plain text transcript attachment from the email the reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via crm here is an example of transcript file chat transcript visitor random website visitor operator milton company initech started oct finished oct random website visitor where do get the cover sheet for the tps report there are no operators available at the moment if you would like to leave message please type it in the input field below and click send button call accepted by operator milton currently in room milton random website visitor milton excuse me you believe you have my stapler random website visitor really just need the cover sheet okay milton it is not okay because if they take my stapler then will will will set the building on fire random website visitor oh found it thanks anyway random website visitor is now off line and may not reply currently in room milton milton well ok but that is the last straw milton has left the conversation currently in room room is empty visitor details your name random website visitor your question where do get the cover sheet for the tps report ip address host name referrer unknown browser os mozilla compatible msie windows nt net clr infopath net clr
|
just quick post have only glanced at your transcript example but have recently also had to look into text parsing and hoped to avoid going the route of hand rolled parsing did happen across ragel which have only started to get my head around but it is looking to be pretty useful
|
QA
|
javascript style dot notation for dictionary keys unpythonic have started to use constructs like these class dictobj object def init self self def getattr self return self get none def setattr self super setattr self update based on this thread have revised the dictobj implementation to class dotdict dict def getattr self attr return self get attr none setattr dict setitem delattr dict delitem class autoenum object def init self self counter self def getattr self if not in self self self counter self counter return self where dictobj is dictionary that can be accessed via dot notation dictobj something one find it more aesthetically pleasing than something note that accessing an undefined key returns none instead of raising an exception which is also nice update smashery makes good point which mhawke expands on for an easier solution am wondering if there are any undesirable side effects of using dict instead of defining new dictionary if not like mhawke solution lot autoenum is an auto incrementing enum used like this cmd autoenum cmds peek cmd peek look cmd peek help cmd help poke cmd poke modify cmd poke both are working well for me but am feeling unpythonic about them are these in fact bad constructs
|
as far as know python classes use dictionaries to store their attributes anyway that is hidden from the programmer so it looks to me that what you have done there is effectively emulate python class using python class
|
QA
|
elegant structured text file parsing need to parse transcript of live chat conversation my first thought on seeing the file was to throw regular expressions at the problem but was wondering what other approaches people have used put elegant in the title as have previously found that this type of task has danger of getting hard to maintain just relying on regular expressions the transcripts are being generated by www providesupport com and emailed to an account then extract plain text transcript attachment from the email the reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via crm here is an example of transcript file chat transcript visitor random website visitor operator milton company initech started oct finished oct random website visitor where do get the cover sheet for the tps report there are no operators available at the moment if you would like to leave message please type it in the input field below and click send button call accepted by operator milton currently in room milton random website visitor milton excuse me you believe you have my stapler random website visitor really just need the cover sheet okay milton it is not okay because if they take my stapler then will will will set the building on fire random website visitor oh found it thanks anyway random website visitor is now off line and may not reply currently in room milton milton well ok but that is the last straw milton has left the conversation currently in room room is empty visitor details your name random website visitor your question where do get the cover sheet for the tps report ip address host name referrer unknown browser os mozilla compatible msie windows nt net clr infopath net clr
|
you might want to consider full parser generator regular expressions are good for searching text for small substrings but they are woefully under powered if you are really interested in parsing the entire file into meaningful data they are especially insufficient if the context of the substring is important most people throw regexes at everything because that is what they know they have never learned any parser generating tools and they end up coding lot of the production rule composition and semantic action handling that you can get for free with parser generator regexes are great and all but if you need parser they are no substitute
|
QA
|
javascript style dot notation for dictionary keys unpythonic have started to use constructs like these class dictobj object def init self self def getattr self return self get none def setattr self super setattr self update based on this thread have revised the dictobj implementation to class dotdict dict def getattr self attr return self get attr none setattr dict setitem delattr dict delitem class autoenum object def init self self counter self def getattr self if not in self self self counter self counter return self where dictobj is dictionary that can be accessed via dot notation dictobj something one find it more aesthetically pleasing than something note that accessing an undefined key returns none instead of raising an exception which is also nice update smashery makes good point which mhawke expands on for an easier solution am wondering if there are any undesirable side effects of using dict instead of defining new dictionary if not like mhawke solution lot autoenum is an auto incrementing enum used like this cmd autoenum cmds peek cmd peek look cmd peek help cmd help poke cmd poke modify cmd poke both are working well for me but am feeling unpythonic about them are these in fact bad constructs
|
like dot notation lot better than dictionary fields personally the reason being that it makes autocompletion work lot better
|
QA
|
elegant structured text file parsing need to parse transcript of live chat conversation my first thought on seeing the file was to throw regular expressions at the problem but was wondering what other approaches people have used put elegant in the title as have previously found that this type of task has danger of getting hard to maintain just relying on regular expressions the transcripts are being generated by www providesupport com and emailed to an account then extract plain text transcript attachment from the email the reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via crm here is an example of transcript file chat transcript visitor random website visitor operator milton company initech started oct finished oct random website visitor where do get the cover sheet for the tps report there are no operators available at the moment if you would like to leave message please type it in the input field below and click send button call accepted by operator milton currently in room milton random website visitor milton excuse me you believe you have my stapler random website visitor really just need the cover sheet okay milton it is not okay because if they take my stapler then will will will set the building on fire random website visitor oh found it thanks anyway random website visitor is now off line and may not reply currently in room milton milton well ok but that is the last straw milton has left the conversation currently in room room is empty visitor details your name random website visitor your question where do get the cover sheet for the tps report ip address host name referrer unknown browser os mozilla compatible msie windows nt net clr infopath net clr
|
consider using ragel http www complang org ragel that is what powers mongrel under the hood parsing string multiple times is going to slow things down dramatically
|
QA
|
javascript style dot notation for dictionary keys unpythonic have started to use constructs like these class dictobj object def init self self def getattr self return self get none def setattr self super setattr self update based on this thread have revised the dictobj implementation to class dotdict dict def getattr self attr return self get attr none setattr dict setitem delattr dict delitem class autoenum object def init self self counter self def getattr self if not in self self self counter self counter return self where dictobj is dictionary that can be accessed via dot notation dictobj something one find it more aesthetically pleasing than something note that accessing an undefined key returns none instead of raising an exception which is also nice update smashery makes good point which mhawke expands on for an easier solution am wondering if there are any undesirable side effects of using dict instead of defining new dictionary if not like mhawke solution lot autoenum is an auto incrementing enum used like this cmd autoenum cmds peek cmd peek look cmd peek help cmd help poke cmd poke modify cmd poke both are working well for me but am feeling unpythonic about them are these in fact bad constructs
|
with regards to the dictobj would the following work for you blank class will allow you to arbitrarily add to or replace stuff in container object class container object pass mycontainer container mycontainer spam in can mycontainer eggs in she will if you want to not throw an attributeerror when there is no attribute what do you think about the following personally would prefer to use dict for clarity or to use try except clause class quietcontainer object def getattr self attribute try return object getattr self attribute except attributeerror return none cont quietcontainer print cont me none right
|
QA
|
including pyds dlls in py exe builds one of the modules for my app uses functions from pyd file there is an option to exclude dlls exclude dlls but is there one for including them the build process does not seem to be copying the pyd in my module despite copying the rest of the files py also need to include dll how do get py exe to include both pyd and dll files
|
maybe you could use the data files option to setup import glob setup name myapp other options data files glob glob dll glob glob pyd data files should be list of tuples where each tuple contains the target directory list of files to copy this will not put the files into library zip which should not be problem for dlls but do not know about pyd files
|
QA
|
what would be better implementation of all combinations in lexicographic order of jagged list was put in position today in which needed to enumerate all possible combinations of jagged list for instance naive approach would be for in for in for in yield this is functional but not general in terms of the number of lists that can be used here is more generalized approach from numpy import zeros array nonzero max make subset lambda for in enumerate def combinations items num items len for in items state zeros len items dtype int finished array num items dtype int yield grab items items state while true if state num items state yield make subset items state else incrementable nonzero state finished if not len incrementable raise stopiteration rightmost max incrementable state rightmost state rightmost yield make subset items state any recommendations on better approach or reasons against the above approach
|
the naive approach can be written more compactly as generator expression for in for in for in the general approach can be written much more simply using recursive function def combinations seqs if not seqs return item for item in first rest seqs seqs if not rest return item for item in first return item items for item in first for items in combinations rest sample usage for pair in combinations abc print pair
|
QA
|
including pyds dlls in py exe builds one of the modules for my app uses functions from pyd file there is an option to exclude dlls exclude dlls but is there one for including them the build process does not seem to be copying the pyd in my module despite copying the rest of the files py also need to include dll how do get py exe to include both pyd and dll files
|
pyd and dll are different here in that pyd ought to be automatically found by modulefinder and so included as long as you have the appropriate import statement without needing to do anything if one is missed you do the same thing as if py file was missed they are both just modules use the include option for the py exe options modulefinder will not necessarily find dependencies on dlls py exe can detect some so you may need to explicitly include these with the data files option for example where you had two dll foo dll and bar dll to include and three pyd module pyd module pyd and module pyd to include setup name app other options data files foo dll bar dll options py exe includes module module module
|
QA
|
elegant structured text file parsing need to parse transcript of live chat conversation my first thought on seeing the file was to throw regular expressions at the problem but was wondering what other approaches people have used put elegant in the title as have previously found that this type of task has danger of getting hard to maintain just relying on regular expressions the transcripts are being generated by www providesupport com and emailed to an account then extract plain text transcript attachment from the email the reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via crm here is an example of transcript file chat transcript visitor random website visitor operator milton company initech started oct finished oct random website visitor where do get the cover sheet for the tps report there are no operators available at the moment if you would like to leave message please type it in the input field below and click send button call accepted by operator milton currently in room milton random website visitor milton excuse me you believe you have my stapler random website visitor really just need the cover sheet okay milton it is not okay because if they take my stapler then will will will set the building on fire random website visitor oh found it thanks anyway random website visitor is now off line and may not reply currently in room milton milton well ok but that is the last straw milton has left the conversation currently in room room is empty visitor details your name random website visitor your question where do get the cover sheet for the tps report ip address host name referrer unknown browser os mozilla compatible msie windows nt net clr infopath net clr
|
with perl you can use parse recdescent it is simple and your grammar will be maintainable later on
|
QA
|
best approach with dynamic classes using python globals am working on web application that will return variable set of modules depending on user input each module is python class with constructor that accepts single parameter and has an html property that contains the output pulling the class dynamically from the global namespace works result globals classname param html and it is certainly more succinct than if classname foo result foo param html elif classname bar what is considered the best way to write this stylistically are there risks or reasons not to use the global namespace
|
another way to build the map between class names and classes when defining classes add an attribute to any class that you want to put in the lookup table class foo lookup true def init self params and so on once this is done building the lookup map is class lookup zip globals for in dir if hasattr globals lookup
|
QA
|
incoming poplib refactoring using windows python hi guys could you please help me refactor this so that it is sensibly pythonic import sys import poplib import string import stringio rfc import datetime import logging def dump pop emails self self logger info open pop account with username self account self account self popinstance poplib pop self account self logger info self popinstance getwelcome self popinstance user self account self popinstance pass self account try nummsgs totalsize self popinstance stat for thisnum in range nummsgs server msg body octets self popinstance retr thisnum text string join body mesg stringio stringio text message rfc message mesg name email message getaddr from emailpath str self emailpath self inboxfolder email message getheader subject eml emailpath self replace whitespace emailpath file open emailpath wb file write text file close self popinstance dele thisnum finally self logger info self popinstance quit def replace whitespace self name name str name return name replace also in the replace whitespace method would like to have some kind of cleaning routine which takes out all illegal characters which could cause processing basically want to write the email to the inbox directory in standard way am doing something wrong here
|
do not see anything significant wrong with that code is it behaving incorrectly or are you just looking for general style guidelines few notes instead of logger info foo bar baz use foo bar baz this avoids the overhead of string formatting if the message will not be printed put try finally around opening emailpath use join body instead of string join body instead of message getaddr from just message from
|
QA
|
javascript style dot notation for dictionary keys unpythonic have started to use constructs like these class dictobj object def init self self def getattr self return self get none def setattr self super setattr self update based on this thread have revised the dictobj implementation to class dotdict dict def getattr self attr return self get attr none setattr dict setitem delattr dict delitem class autoenum object def init self self counter self def getattr self if not in self self self counter self counter return self where dictobj is dictionary that can be accessed via dot notation dictobj something one find it more aesthetically pleasing than something note that accessing an undefined key returns none instead of raising an exception which is also nice update smashery makes good point which mhawke expands on for an easier solution am wondering if there are any undesirable side effects of using dict instead of defining new dictionary if not like mhawke solution lot autoenum is an auto incrementing enum used like this cmd autoenum cmds peek cmd peek look cmd peek help cmd help poke cmd poke modify cmd poke both are working well for me but am feeling unpythonic about them are these in fact bad constructs
|
this is simpler version of your dictobj class class dictobj object def getattr self attr return self dict get attr dictobj something one print something one print somethingelse none
|
QA
|
incoming poplib refactoring using windows python hi guys could you please help me refactor this so that it is sensibly pythonic import sys import poplib import string import stringio rfc import datetime import logging def dump pop emails self self logger info open pop account with username self account self account self popinstance poplib pop self account self logger info self popinstance getwelcome self popinstance user self account self popinstance pass self account try nummsgs totalsize self popinstance stat for thisnum in range nummsgs server msg body octets self popinstance retr thisnum text string join body mesg stringio stringio text message rfc message mesg name email message getaddr from emailpath str self emailpath self inboxfolder email message getheader subject eml emailpath self replace whitespace emailpath file open emailpath wb file write text file close self popinstance dele thisnum finally self logger info self popinstance quit def replace whitespace self name name str name return name replace also in the replace whitespace method would like to have some kind of cleaning routine which takes out all illegal characters which could cause processing basically want to write the email to the inbox directory in standard way am doing something wrong here
|
further to my comment on john answer found out what the issue was there were illegal characters in the name field and subject field which caused python to get the hiccups as it tried to write the email as directory after seeing and john point number does not work so left it as before also is point no correct have implemented your suggestion correctly def dump pop emails self self logger info open pop account with username self account self account self popinstance poplib pop self account self logger info self popinstance getwelcome self popinstance user self account self popinstance pass self account try nummsgs totalsize self popinstance stat for thisnum in range nummsgs server msg body octets self popinstance retr thisnum text join body mesg stringio stringio text message rfc message mesg name email message getaddr from emailpath str self emailpath self inboxfolder self sanitize string email message getheader subject eml emailpath self replace whitespace emailpath print emailpath file open emailpath wb file write text file close self popinstance dele thisnum finally self logger info self popinstance quit def replace whitespace self name name str name return name replace def sanitize string self name illegal chars name str name for item in illegal chars name name replace item return name
|
QA
|
javascript style dot notation for dictionary keys unpythonic have started to use constructs like these class dictobj object def init self self def getattr self return self get none def setattr self super setattr self update based on this thread have revised the dictobj implementation to class dotdict dict def getattr self attr return self get attr none setattr dict setitem delattr dict delitem class autoenum object def init self self counter self def getattr self if not in self self self counter self counter return self where dictobj is dictionary that can be accessed via dot notation dictobj something one find it more aesthetically pleasing than something note that accessing an undefined key returns none instead of raising an exception which is also nice update smashery makes good point which mhawke expands on for an easier solution am wondering if there are any undesirable side effects of using dict instead of defining new dictionary if not like mhawke solution lot autoenum is an auto incrementing enum used like this cmd autoenum cmds peek cmd peek look cmd peek help cmd help poke cmd poke modify cmd poke both are working well for me but am feeling unpythonic about them are these in fact bad constructs
|
it is not bad if it serves your purpose practicality beats purity saw such approach elserwhere eg in paver so this can be considered common need or desire
|
QA
|
alternatives to wizard am making program that fits the wizard concept ideally the user is walked through the steps to create character for game however am realizing that the limitations of the wizard are making it difficult to design elegant logic flow for example because all pages of the wizard are initalized at the same time cannot have the values entered in one page available to the next one have to put button on each page to get the values from previous page rather than simply having fields auto populated have thought about alternatives to using the wizard think the best idea is to have some buttons on one panel that change the information on another panel splitter window however cannot find any documentation in wxpython on how to dynamically change the panel everything have found so far is really pretty static hence the use of the wizard even the wxpython in action book does not mention it are there any tutorials for making dynamic panels or better management of wizard
|
here is simple example this way you can make your wizard work like finite state machine where states are different pages that are initialized on demand also the data is shared between pages import wx import wx lib newevent pagechangeevent evt page change wx lib newevent newevent class data foo none bar none class page wx panel def init self parent data wx panel init self parent self parent parent self data data sizer wx boxsizer wx vertical self setsizer sizer label wx statictext self label page foo self foo wx textctrl self goto page wx button self label go to page for in label self foo goto page sizer add wx top goto page bind wx evt button self onpage def onpage self event self data foo self foo value wx postevent self parent pagechangeevent page page class page wx panel def init self parent data wx panel init self parent self parent parent self data data sizer wx boxsizer wx vertical self setsizer sizer label wx statictext self label page bar self bar wx textctrl self goto finish wx button self label finish for in label self bar goto finish sizer add wx top goto finish bind wx evt button self onfinish def onfinish self event self data bar self bar value wx postevent self parent pagechangeevent page finish def finish parent data wx messagebox foo nbar data foo data bar wx getapp exitmainloop class test wx frame def init self wx frame init self none self data data self current page none self bind evt page change self onpagechange wx postevent self pagechangeevent page page def onpagechange self event page event page self self data if page none return if self current page self current page destroy self current page page page layout page fit page refresh app wx pysimpleapp app topwindow test app topwindow show app mainloop
|
QA
|
how do you use the cursor for reading multiple files in database in python in python how do you read multiple files from mysql database using the cursor or loop one by one and store the output in separate table
|
do not understand your question what are files what is your table structure but here goes simple sample import mysqldb conn mysqldb connect host localhost user root password merlin db files cursor conn cursor cursor execute select from files rows cursor fetchall cursor execute create table destination file varchar for row in rows cursor execute insert into destination values row
|
QA
|
how do you use the cursor for reading multiple files in database in python in python how do you read multiple files from mysql database using the cursor or loop one by one and store the output in separate table
|
here is an example assuming you have created the table you want to move to with descriptive names import mysqldb conn mysqldb connect user username db dbname cur conn cursor cur execute select files from old table where conditions met cur fetchall for item in cur execute update new table set new field item item should be tuple with one value else use item with comma
|
QA
|
javascript style dot notation for dictionary keys unpythonic have started to use constructs like these class dictobj object def init self self def getattr self return self get none def setattr self super setattr self update based on this thread have revised the dictobj implementation to class dotdict dict def getattr self attr return self get attr none setattr dict setitem delattr dict delitem class autoenum object def init self self counter self def getattr self if not in self self self counter self counter return self where dictobj is dictionary that can be accessed via dot notation dictobj something one find it more aesthetically pleasing than something note that accessing an undefined key returns none instead of raising an exception which is also nice update smashery makes good point which mhawke expands on for an easier solution am wondering if there are any undesirable side effects of using dict instead of defining new dictionary if not like mhawke solution lot autoenum is an auto incrementing enum used like this cmd autoenum cmds peek cmd peek look cmd peek help cmd help poke cmd poke modify cmd poke both are working well for me but am feeling unpythonic about them are these in fact bad constructs
|
your dictobj example is actually quite common object style dot notation access can be win if you are dealing with things that resemble objects ie they have fixed property names containing only characters valid in python identifiers stuff like database rows or form submissions can be usefully stored in this kind of object making code little more readable without the excess of item access the implementation is bit limited you do not get the nice constructor syntax of dict len comparisons in iteration or nice reprs you can of course implement those things yourself but in the new style classes world you can get them for free by simply subclassing dict class attrdict dict getattr dict getitem setattr dict setitem delattr dict delitem to get the default to none behaviour simply subclass python collections defaultdict class instead of dict
|
QA
|
how can generate report file odf pdf from django view would like to generate report file from view template in django preferred file formats would be openoffice odf or pdf what is the best way to do this do want to reuse the page layout defined in the template possibly by redefining some blocks in derived template ideally the report should be inserted into an existing template file so can provide the overall page layout headers and footer in the generated output format
|
pisa xhtml pdf should get you covered for pdf it even includes an example django project
|
QA
|
incoming poplib refactoring using windows python hi guys could you please help me refactor this so that it is sensibly pythonic import sys import poplib import string import stringio rfc import datetime import logging def dump pop emails self self logger info open pop account with username self account self account self popinstance poplib pop self account self logger info self popinstance getwelcome self popinstance user self account self popinstance pass self account try nummsgs totalsize self popinstance stat for thisnum in range nummsgs server msg body octets self popinstance retr thisnum text string join body mesg stringio stringio text message rfc message mesg name email message getaddr from emailpath str self emailpath self inboxfolder email message getheader subject eml emailpath self replace whitespace emailpath file open emailpath wb file write text file close self popinstance dele thisnum finally self logger info self popinstance quit def replace whitespace self name name str name return name replace also in the replace whitespace method would like to have some kind of cleaning routine which takes out all illegal characters which could cause processing basically want to write the email to the inbox directory in standard way am doing something wrong here
|
this is not refactoring it does not need refactoring as far as can see but some suggestions you should use the email package rather than rfc replace rfc message with email message and use email utils parseaddr message from to get the name and email address and message subject to get the subject use os path join to create the path this emailpath str self emailpath self inboxfolder email message getheader subject eml becomes emailpath os path join self emailpath self inboxfolder email message getheader subject eml if self inboxfolder starts with slash or self emailpath ends with one you could replace the first with comma also it does not really hurt anything but you should probably not use file as variable name since it shadows built in type checkers like pylint or pychecker would warn you about that if you are not using self popinstance outside of this function seems unlikely given that you connect and quit within the function then there is no point making it an attribute of self just use popinstance by itself use xrange instead of range instead of just importing stringio do this try import cstringio as stringio except importerror import stringio if this is pop mailbox that can be accessed by more than one client at time you might want to put try except around the retr call to continue on if you cannot retrieve one message as john said use join rather than string join use try finally to only close the file if it is opened and pass the logging parameters separately the one refactoring issue could think of would be that you do not really need to parse the whole message since you are just dumping copy of the raw bytes and all you want is the from and subject headers you could instead use popinstance top to get the headers create the message blank body from that and use that for the headers then do full retr to get the bytes this would only be worth doing if your messages were large and so parsing them took long time would definitely measure before made this optimisation for your function to sanitise for the names it depends how nice you want the names to be and how certain you are that the email and subject make the filename unique seems fairly unlikely you could do something like emailpath join for in emailpath if in string letters string digits and you would end up with just alphanumeric characters and the underscore and space which seems like readable set given that your filesystem with windows is probably case insensitive you could lowercase that also add lower to the end you could use emailpath translate if you want something more complex
|
QA
|
rfc date representation in python is there fairly easy way to convert datetime object into an rfc http date time string string with the format sun nov gmt using strftime does not work since the strings are locale dependant do have to build the string by hand
|
you can set lc time to force stftime to use specific locale locale setlocale locale lc time en us en us datetime datetime now strftime locale nl langinfo locale fmt wed oct am
|
QA
|
rfc date representation in python is there fairly easy way to convert datetime object into an rfc http date time string string with the format sun nov gmt using strftime does not work since the strings are locale dependant do have to build the string by hand
|
you can use wsgiref handlers format date time from the stdlib which does not rely on locale settings from wsgiref handlers import format date time from datetime import datetime from time import mktime now datetime now stamp mktime now timetuple print format date time stamp wed oct gmt you can use email utils formatdate from the stdlib which does not rely on locale settings from email utils import formatdate from datetime import datetime from time import mktime now datetime now stamp mktime now timetuple print formatdate timeval stamp localtime false usegmt true wed oct gmt if you can set the locale process wide then you can do import locale datetime locale setlocale locale lc time en us datetime datetime utcnow strftime gmt if you do not want to set the locale process wide you could use babel date formating from datetime import datetime from babel dates import format datetime now datetime utcnow format eee dd lll yyyy hh mm ss print format datetime now format locale en gmt manual way to format it which is identical with wsgiref handlers format date time is def httpdate dt return string representation of date according to rfc http the supplied date must be in utc weekday mon tue wed thu fri sat sun dt weekday month jan feb mar apr may jun jul aug sep oct nov dec dt month return gmt weekday dt day month dt year dt hour dt minute dt second
|
QA
|
rfc date representation in python is there fairly easy way to convert datetime object into an rfc http date time string string with the format sun nov gmt using strftime does not work since the strings are locale dependant do have to build the string by hand
|
you can use the formatdate function from the python standard email module from email utils import formatdate print formatdate timeval none localtime false usegmt true gives the current time in the desired format wed oct gmt in fact this function does it by hand without using strftime
|
QA
|
rfc date representation in python is there fairly easy way to convert datetime object into an rfc http date time string string with the format sun nov gmt using strftime does not work since the strings are locale dependant do have to build the string by hand
|
well here is manual function to format it def httpdate dt return string representation of date according to rfc http the supplied date must be in utc weekday mon tue wed thu fri sat sun dt weekday month jan feb mar apr may jun jul aug sep oct nov dec dt month return gmt weekday dt day month dt year dt hour dt minute dt second
|
QA
|
parsing different date formats from feedparser in python am trying to get the dates from entries in two different rss feeds through feedparser here is what am doing import feedparser as fp reddit fp parse http www reddit com rss cc fp parse http contentconsumer com feed print reddit entries date print cc entries date and here is how they come out wed oct want to get to the point where can find out which is newer easily have tried using the datetime module of python and searching through the feedparser documentation but cannot get past this problem any help would be much appreciated
|
parsing of dates is pain with rss feeds in the wild and that is where feedparser can be big help if you use the parsed properties like updated parsed feedparser will have done the work and will return tuple python date in utc see http packages python org feedparser date parsing html for more gory details
|
QA
|
alternatives to wizard am making program that fits the wizard concept ideally the user is walked through the steps to create character for game however am realizing that the limitations of the wizard are making it difficult to design elegant logic flow for example because all pages of the wizard are initalized at the same time cannot have the values entered in one page available to the next one have to put button on each page to get the values from previous page rather than simply having fields auto populated have thought about alternatives to using the wizard think the best idea is to have some buttons on one panel that change the information on another panel splitter window however cannot find any documentation in wxpython on how to dynamically change the panel everything have found so far is really pretty static hence the use of the wizard even the wxpython in action book does not mention it are there any tutorials for making dynamic panels or better management of wizard
|
you could try using workflow engine like wftk in this particular case author has done some work on wx based apps using wftk and can probably direct you to examples
|
QA
|
open source profiling frameworks have you ever wanted to test and quantitatively show whether your application would perform better as static build or shared build stripped or non stripped upx or no upx gcc or gcc hash or btree etc etc if so this is the thread for you there are hundreds of ways to tune an application but how do we collect organize process visualize the consequences of each experiment have been looking for several months for an open source application performance engineering profiling framework similar in concept to mozilla perftastic where can develop build test profile hundreds of incarnations of different tuning experiments some requirements platform suse and suse data format very flexible compact simple hierarchical there are several possibilities including custom csv rrd protocol buffers json no xml there is lots of data and xml is tooo verbose data acquisition flexible and customizable plugins there is lots of data to collect from the application including performance data from proc sys time wall time cpu utilization memory profile leaks valgrind logs arena fragmentation localhost sockets binary size open fds etc and some from the host system my language of choice for this is python and would develop these plugins to monitor and or parse data in all different formats and store them in the data format of the framework tagging all experiments would be tagged including data like gcc version and compile options platform host app options experiment build tag etc graphing history comparative hierarchical dynamic and static the application builds are done by custom ci sever which releases new app version several times per day the last years straight this is why we need continuous trend analysis when we add new features make bug fixes change build options we want to automatically gather profiling data and see the trend this is where generating various static builds is needed for analysis mozilla dynamic graphs are great for doing comparative graphing it would be great to have comparative graphing between different tags for example compare build versions compare platforms compare build options etc we have test suite of tests data will be gathered per test and grouped from inter test data to per test to per tagged group to complete regression suite possibilities include rrdtool orca graphite analysis on grouping basis min max median average standard deviation etc presentation all of this would be presented and controlled through app server preferably django or tg would be best inspiration centreon cacti
|
am not sure what your question is precisely but for profiling java web applications you can use the netbeans profiler and profiler available on sourceforge have used both and can recommend them over eclipse tptp see http stackoverflow com questions how to set up eclipse tptp and http profiler sourceforge net edit sorry just noticed you tagged this as python question so this must not be valid answer for you
|
QA
|
batch renaming of files in directory is there an easy way to rename group of files already contained in directory using python example have directory full of doc files and want to rename them in consistent way doc new doc doc new doc
|
try http www mattweber org python script renamepy like to have my music movie and picture files named certain way when download files from the internet they usually don follow my naming convention found myself manually renaming each file to fit my style this got old realy fast so decided to write program to do it for me this program can convert the filename to all lowercase replace strings in the filename with whatever you want and trim any number of characters from the front or back of the filename the program source code is also available
|
QA
|
pretty continuous integration for python this is slightly vain question but buildbot output is not particularly nice to look at for example compared to phpundercontrol jenkins hudson cruisecontrol rb and others buildbot looks rather archaic am currently playing with hudson but it is very java centric although with this guide found it easier to setup than buildbot and produced more info basically is there any continuous integration systems aimed at python that produce lots of shiny graphs and the likes update since this time the jenkins project has replaced hudson as the community version of the package the original authors have moved to this project as well jenkins is now standard package on ubuntu debian redhat fedora centos and others the following update is still essentially correct the starting point to do this with jenkins is different update after trying few alternatives think will stick with hudson integrity was nice and simple but quite limited think buildbot is better suited to having numerous build slaves rather than everything running on single machine like was using it setting hudson up for python project was pretty simple download hudson from http hudson ci org run it with java jar hudson war open the web interface on the default address of http localhost go to manage hudson plugins click update or similar install the git plugin had to set the git path in the hudson global preferences create new project enter the repository scm polling intervals and so on install nosetests via easy install if it is not already in the build step add nosetests with xunit verbose check publish junit test result report and set test report xmls to nosetests xml that is all that is required you can setup email notifications and the plugins are worth look few am currently using for python projects sloccount plugin to count lines of code and graph it you need to install sloccount separately violations to parse the pylint output you can setup warning thresholds graph the number of violations over each build cobertura can parse the coverage py output nosetest can gather coverage while running your tests using nosetests with coverage this writes the output to coverage xml
|
do not know if it would do bitten is made by the guys who write trac and is integrated with trac apache gump is the ci tool used by apache it is written in python
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.