Pyastro
Where can I find the code... I have checked starship, "the vaults" and googled for a long time. either they point to starshup(wiki) where it doesn't exists, or to dead links. Any help would be much appreciated. TIA -- http://mail.python.org/mailman/listinfo/python-list
PyGeo
has anyone successfully installed PyGeo under python 2.7 (prefer ubuntu 10.04) , the site says http://www.wspiegel.de/pymaxima/index_en.html "Note: The installation of PyGeo work's only under Python 2.4 (The further development of pygeo seems to be stopped)" is this to do with re-org of site-packages, dist_packages etc. any help most appreciated. TIA -- http://mail.python.org/mailman/listinfo/python-list
Re: PyGeo
On 30/08/10 05:00, Thomas Jollans wrote: On Sunday 29 August 2010, it occurred to L to exclaim: has anyone successfully installed PyGeo under python 2.7 (prefer ubuntu 10.04) , the site says http://www.wspiegel.de/pymaxima/index_en.html "Note: The installation of PyGeo work's only under Python 2.4 (The further development of pygeo seems to be stopped)" is this to do with re-org of site-packages, dist_packages etc. any help most appreciated. I don't know. I haven't tried. Maybe somebody else here has, but don't count on it. Have you tried it? If not, then why not? Try it. Maybe it just works. As far as I know, distutils haven't changed much, carefully avoiding any changes that could break packages. I think it's entirely possible that the web page author claiming "the installation" doesn't work was referring only to the Windows installer. Have fun, Thomas I have tried it and as soon as you try any of the examples in the examples dir it cannot find numpy etc I have manually move the pygeo dirs and contents to /usr/lib/python2.6/dis-packages, (this is the directory where numpy, numeric and scipy were installed when using synaptic ) made sure thatread and write permissions set for ALL FILES and DIRECTORIES to RW using sudo chmod 777 any ideas. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyGeo
On 30/08/10 18:59, Thomas Jollans wrote: On Monday 30 August 2010, it occurred to L to exclaim: I have tried it and as soon as you try any of the examples in the examples dir it cannot find numpy etc I have manually move the pygeo dirs and contents to /usr/lib/python2.6/dis-packages, (this is the directory where numpy, numeric and scipy were installed when using synaptic ) made sure thatread and write permissions set for ALL FILES and DIRECTORIES to RW using sudo chmod 777 Wait -- did you just try to use pymaxima, or did you properly (try to) install the dependencies? You need VPython. It's in the ubuntu archives. http://packages.ubuntu.com/lucid/python-visual And then you need to download and install pygeo. http://pygeo.sourceforge.net/download.html It probably uses distutils, so you'd extract the source archive and run sudo python setup.py install If THAT gives you any errors, then please come back here, with the exact error messages. If it works, then PyGeo should be installed. If it still doesn't work, then there's certainly a chance it won't work, but you can still ask here for help, with the exact error messages, so we have something to build upon when trying to figure out what's wrong. - Thomas No, I have not tried pymaxma ( I have maxima and wxmaxima install via synaptic, tested and all works OK) yes, that is what I did for install. Vpython already install via synaptic, ran a number of examples and all produced the expected output. also the PyGeo readme text mentions Numerical python (I think it means Numeric, but I also have NumPy installed) to install i did the following steps PyGeo downloaded form sourceforge tar xvfc PyGeo-1.0a1.tar.gz cd PyGeo-1.0a1 python setup.py install NO ERROR MESSAGES ecountered IT DID NOT WORK coplaing about the NUMERIC module I repeated the install and issued the parameter to 'python steup.py install.) to force the directory name to be the same where the other python modules are (see listing below) NO ERROR MESSAGES ecountered Note what I did to ensure permissions etc (see my second post for directories etc) install successful, but running the example from ...examples/real/ using IDLE I get IDLE 2.6.5 No Subprocess >>> Traceback (most recent call last): File "/usr/lib/python2.6/dist-packages/pygeo/examples/real/dandelinspheres2.py", line 2, in from pygeo.base.abstract_elements_real import _Sphere, _Point File "/usr/lib/python2.6/dist-packages/pygeo/__init__.py", line 3, in from pygeo.vpyframe import display File "/usr/lib/python2.6/dist-packages/pygeo/vpyframe.py", line 38, in class display( visual.ui.display): AttributeError: 'module' object has no attribute 'ui' >>> /usr/lib/python2.6/dist-packages has the following directories and permissions drwxr-xr-x 2 root root4096 2010-04-29 22:42 appindicator drwxr-xr-x 3 root root4096 2010-04-29 22:43 apport drwxr-xr-x 2 root root4096 2010-07-29 17:56 AppTools-3.3.0.egg-info drwxr-xr-x 3 root root4096 2010-08-10 12:43 apt drwxr-xr-x 2 root root4096 2010-04-29 22:43 aptdaemon drwxr-xr-x 2 root root4096 2010-08-10 12:43 aptsources drwxr-xr-x 3 root root4096 2010-04-29 22:43 AptUrl drwxr-xr-x 5 root root4096 2010-07-28 21:14 butterfly drwxr-xr-x 5 root root4096 2010-04-29 22:41 checkbox drwxr-xr-x 2 root root4096 2010-04-29 22:43 checkbox_gtk drwxr-xr-x 2 root root4096 2010-04-29 22:43 CommandNotFound drwxr-xr-x 2 root root4096 2010-08-10 12:43 computerjanitor drwxr-xr-x 3 root root4096 2010-04-29 22:42 configglue drwxr-xr-x 2 root root4096 2010-04-29 22:42 configglue-0.2dev.egg-info drwxr-xr-x 7 root root4096 2010-04-29 22:42 Crypto drwxr-xr-x 7 root root4096 2010-04-29 22:44 desktopcouch drwxr-xr-x 2 root root4096 2010-08-28 17:36 distribute-0.6.10.egg-info drwxr-xr-x 2 root root4096 2010-08-10 12:43 DistUpgrade drwxr-xr-x 3 root root4096 2010-08-28 17:36 DistUtilsExtra drwxr-xr-x 26 root root4096 2010-07-29 17:56 enthought drwxr-xr-x 2 root root4096 2010-07-29 17:56 EnthoughtBase-3.0.3.egg-info drwxr-xr-x 2 root root4096 2010-07-29 17:56 EnvisageCore-3.1.1.egg-info drwxr-xr-x 2 root root4096 2010-07-29 17:56 EnvisagePlugins-3.1.1.egg-info drwxr-xr-x 2 root root4096 2010-08-15 11:38 GDebi drwxr-xr-x 7 root root4096 2010-04-29 22:28 glchess drwxr-xr-x 2 root root4096 2010-04-29 22:43 gnome_app_install-0.4.2ubuntu2.egg-info drwxr-xr-x 2 root root4096 2010-04-29 22:43 GnomeCodecInstall drwxr-xr-x 3 root root4096 2010-04-29 22:28 gnome_sudoku drwxr-xr-x 2 root root4096 2010-08-28 18:02 Gnuplot drwxr-xr-x 3 root root4096 2010-04-29 22:32 gst-0.10 drwxr-xr-x 3 root root4096 2010-04-29 22:32 gtk-2.0 drwxr-xr-x 4 root root4096 2010-07-28 21:14 gw
Help with 'self' and 'set_usage'
Hi all, I'm interning and have been given the job of extending a program that has been written by someone else. I've never used Python before so it's a bit of a struggle but I've got to say I'm loving the language so far. In on of the scripts there is def set_usage(self,s): self.usage_str = s Could anyone shed some light on this? I can't find mention of this anywhere in any Python documentation or anywhere else in the code where usage_str might be defined. Can you just create variables in that object by writing self.name = "david" self.hobby = "fishing"?? If this is any help it is used later in the program (or in other scripts) like prog.set_usage("""%prog [options] """) Thanks for your help, I have spent a good while googling python docs, code snippets and reading through a Python book I have on my desk to no avail. Cheers in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with 'self' and 'set_usage'
On Tuesday, 9 July 2013 18:03:41 UTC+1, L O'Shea wrote: > Hi all, > > I'm interning and have been given the job of extending a program that has > been written by someone else. I've never used Python before so it's a bit of > a struggle but I've got to say I'm loving the language so far. > > > > In on of the scripts there is > > > > def set_usage(self,s): > > self.usage_str = s > > > > Could anyone shed some light on this? I can't find mention of this anywhere > in any Python documentation or anywhere else in the code where usage_str > might be defined. Can you just create variables in that object by writing > self.name = "david" self.hobby = "fishing"?? > > > > If this is any help it is used later in the program (or in other scripts) like > > > > prog.set_usage("""%prog [options] """) > > > > Thanks for your help, I have spent a good while googling python docs, code > snippets and reading through a Python book I have on my desk to no avail. > > > > Cheers in advance. Thanks for the advice everyone that was really helpful! Gotta love the USA/UK time difference I can post a question here at the end of the day and it be answered by morning - Not that it took any of you very long! Stay tuned for more Python questions :) -- http://mail.python.org/mailman/listinfo/python-list
Understanding other people's code
Hi all, I've been asked to take over a project from someone else and to extend the functionality of this. The project is written in Python which I haven't had any real experience with (although I do really like it) so I've spent the last week or two settling in, trying to get my head around Python and the way in which this code works. The problem is the code was clearly written by someone who is exceptionally good and seems to inherit everything from everywhere else. It all seems very dynamic, nothing is written statically except in some configuration files. Basically the problem is I am new to the language and this was clearly written by someone who at the moment is far better at it than I am! I'm starting to get pretty worried about my lack of overall progress and so I wondered if anyone out there had some tips and techniques for understanding other peoples code. There has to be 10/15 different scripts with at least 10 functions in each file I would say. Literally any idea will help, pen and paper, printing off all the code and doing some sort of highlighting session - anything! I keep reading bits of code and thinking "well where the hell has that been defined and what does it mean" to find it was inherited from 3 modules up the chain. I really need to get a handle on how exactly all this slots together! Any techniques,tricks or methodologies that people find useful would be much appreciated. -- http://mail.python.org/mailman/listinfo/python-list
help on python regular expression named group
Dear All, Here is my script : #!/usr/bin/python import re # A string. logs = "date=2012-11-28 time=21:14:59" # Match with named groups. m = re.match("(?P(date=(?P[^\s]+))\s+(time=(?P[^\s]+)))", logs) # print print m.groupdict() Output: {'date': '2012-11-28', 'datetime': '*date=2012-11-28 time=21:14:59*', 'time': '21:14:59'} Required output : == {'date': '2012-11-28', 'datetime': '*2012-11-28 21:14:59*', 'time': '21:14:59'} need help to correct the below regex (?P(date=(?P[^\s]+))\s+(time=(?P[^\s]+)))" so that It will have : 'datetime': '2012-11-28 21:14:59' instead of 'datetime': 'date=2012-11-28 time=21:14:59' any help would be greatly appreciated Thanks Mohan L -- http://mail.python.org/mailman/listinfo/python-list
Re: help on python regular expression named group
On Tue, Jul 16, 2013 at 2:12 PM, Joshua Landau wrote: > On 16 July 2013 07:55, Mohan L wrote: > > > > Dear All, > > > > Here is my script : > > > > #!/usr/bin/python > > import re > > > > # A string. > > logs = "date=2012-11-28 time=21:14:59" > > > > # Match with named groups. > > m = > > > re.match("(?P(date=(?P[^\s]+))\s+(time=(?P[^\s]+)))", > > logs) > > > > # print > > print m.groupdict() > > > > Output: > > > > > > {'date': '2012-11-28', 'datetime': 'date=2012-11-28 time=21:14:59', > 'time': > > '21:14:59'} > > > > > > Required output : > > == > > > > {'date': '2012-11-28', 'datetime': '2012-11-28 21:14:59', 'time': > > '21:14:59'} > > > > need help to correct the below regex > > > > (?P(date=(?P[^\s]+))\s+(time=(?P[^\s]+)))" > > > > so that It will have : 'datetime': '2012-11-28 21:14:59' instead of > > 'datetime': 'date=2012-11-28 time=21:14:59' > > > > any help would be greatly appreciated > > Why do you need to do this in a single Regex? Can't you just " > ".join(..) the date and time? > I using another third party python script. It takes the regex from configuration file. I can't write any code. I have to do all this in single regex. Thanks Mohan L -- http://mail.python.org/mailman/listinfo/python-list
Retrieving result from embedded execution
Hello everyone, We are trying to implement our own interactive interpreter in our applicationusing an embedded Python interpreter. I was wondering what would be the best way to retreive as text the result of executing Python code. The text must be exactly the same as it would be in thestandalone interpreter. We used to do this by changing the embedded interpreter's sys.stdout and sys.stderrwith a FILE created in C++. We could then execute code using the PyRun_InteractiveOnefunction and easily retrieve the result from the FILE. The problem is, our applicationshouldn't create any files if possible. We also tried replacing sys.stdout and sys.stderr with a custom made Python objectwhich could be more easily read from C++. We then used the function PyRun_Stringto execute the code. The problem here is that using the Py_file_input start tokendoesn't write everything we need to sys.stdout. (i.e. executing 2+2 does not write 4).It also doesn't print a traceback to sys.stderr when there is an exception. Using theother two start tokens is impossible since we need to be able to execute more than one instruction at once. We also tried using the function PyRun_SimpleString but weencounter the same problems. We are using python 2.7. Any suggestions? Thank you for your time. Also, I'm new to mailling lists, what is the proper way to reply to someone? Should Ireply directly to someone's email adress or is there a way to answer trough the server. F. Lab -- http://mail.python.org/mailman/listinfo/python-list
RE: Embedded python console and FILE* in python 3.2
> Is the `code` module (http://docs.python.org/library/code.html) an > insufficiently exact copy of an interpreter for you? The problem isn't really to emulate the behavior of the interpreter as to obtain the result of the execution as a string in c++. The code module doesn't seem to help with this matter. > I assume you could simply use PyFile_FromFd? According to the documentation using PyFile_FromFd seems unadvised, but I'll give it a try. > The more elegant solution might be to create custom Python file-like> objects > for std{in,out,err} that communicate directly with your application.I thought > about this, but I need the console window to be non-modal and I'm afraid that > replacing stdin witha custom file-like object would cause a blocking call. > Executing python in a second thread would solve this problembut our > application isn't multi-threaded and executing python in another thread > causes errors. Maybe I could use a file-like object to communicate the results to my c++ application and use the code module to execute code only when the c++ application needs it. Thanks a lot for the tips, have a nice day. F.L. -- http://mail.python.org/mailman/listinfo/python-list
RE: Embedded python console and FILE* in python 3.2
> If you use the same workflow as you do currently, it won't You're right it shouldn't cause a blocking call. > Come to think of it, you might as well just use StringIO. Yes I could probably replace std{in, out, err} with stringIO objects and retrieve their contents throughthe api. I'll look into it, thank again. F.L. > Date: Mon, 8 Aug 2011 19:52:14 +0200 > From: t...@jollybox.de > To: python-list@python.org > Subject: Re: Embedded python console and FILE* in python 3.2 > > On 08/08/11 19:44, Thomas Jollans wrote: > > > > > 1. Feed input to your custom stdin object, which will buffer the code. > > 2. Call PyRun_IteractiveOne - it will read from your object, which will > >return the buffer contents. > > 3. The result is somehow handled by custom stdout and stderr objects. > > > > Come to think of it, you might as well just use StringIO. > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: ipython prompt does not appear in windows
See here for a workaround: https://bugs.launchpad.net/ipython/+bug/290228 First result on Google for the query "ipython emacs windows", BTW. On May 17, 3:00 am, rusi wrote: > If I use ipython under emacs on linux it works (at least basic REPL) > ie I can type an expression and I get a result followed by a prompt > > On windows ipython works at the shell. > Plain python works in emacs as well. > > But inside emacs I dont see a prompt in ipython although I see it in > python. > I have to type an expression and then the prompt appears. > > Any clues? -- http://mail.python.org/mailman/listinfo/python-list
Python 3.5.1 C API, the global available available is not destroyed when delete the module
Hi, I have a app loading python35.dll. Use python API PyImport_AddModule to run a py file. And use PyDict_DelItemString to delete the module. There is a global vailable in the py file. The global variable is not destroyed when calling PyDict_DelItemString to delete the module. That cause the memory leak. But it is ok with python33.dll, the global variable can be destroyed when calling PyDict_DelItemString to delete the module. How to resolve the problem? Is there a workaround? I need to use python35.dll and wish the global variable in a module can be released automatically when call PyDict_DelItemString to delete the module. Here is the python test code: class Simple: def __init__( self ): print('Simple__init__') def __del__( self ): print('Simple__del__') simple = Simple() Thanks, Jack -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 3.5.1 C API, the global available available is not destroyed when delete the module
Thanks for the replay. I run this script as __main__ module, this module is removed from sys.modules, and the ref count becomes 0. 2016-09-20 0:00 GMT+08:00 Chris Angelico : > On Mon, Sep 19, 2016 at 4:47 PM, dl l wrote: > > I have a app loading python35.dll. Use python API PyImport_AddModule > > to run a py file. And use PyDict_DelItemString to delete the module. > > There is a global vailable in the py file. The global variable is not > > destroyed when calling PyDict_DelItemString to delete the module. That > > cause the memory leak. > > Does the module still exist in sys.modules? If so, it's not leaked - > it's still in use. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 3.5.1 C API, the global available available is not destroyed when delete the module
Hi Steven, Thanks for reply. I logged bug https://bugs.python.org/issue28202. I added more info in this bug :). Yes, it's a workaround to set the global variables to None. But My app just provide a framework for my customers to run python scripts. That's means the workaround requires my customers to update their python scripts. That may make them unhappy :(. Is there a workaround in my code C++ side to call Python C APIs to resolve the memory leak issue? 2016-09-20 13:49 GMT+08:00 Steven D'Aprano < steve+comp.lang.pyt...@pearwood.info>: > On Monday 19 September 2016 16:47, dl l wrote: > > > Hi, > > > > I have a app loading python35.dll. Use python API PyImport_AddModule > > to run a py file. And use PyDict_DelItemString to delete the module. > > There is a global vailable in the py file. The global variable is not > > destroyed when calling PyDict_DelItemString to delete the module. That > > cause the memory leak. > > See: > > https://bugs.python.org/issue28202 > > > But it is ok with python33.dll, the global variable can be destroyed > > when calling PyDict_DelItemString to delete the module. > > You are calling PyDict_DelItemString on sys.modules, but that won't clear > the > reference to the module if there are any other references to it. > > > > How to resolve the problem? Is there a workaround? I need to use > > python35.dll and wish the global variable in a module can be released > > automatically when call PyDict_DelItemString to delete the module. > > The global object will not be released so long as any other object refers > to > it. If the global object is still alive, it will keep the module alive. > > Are you sure that the object has no other references to it? Have you put > it in > a list or dict or some other object? > > > > Here is the python test code: > > > > class Simple: > > def __init__( self ): > > print('Simple__init__') > > def __del__( self ): > > print('Simple__del__') > > > > simple = Simple() > > > You cannot rely on the __del__ method running at any specific time. It > might > not run until your application exists. > > > That test code is not sufficient. How do you call the test code? If you do > this > from main: > > > import mymodule # module above > del sys.modules['mymodule'] > > > > that will delete the sys.modules cache entry, but the module object is > still > alive. If you are absolutely sure there are no other references to the > global > variable and the module, then it sounds like a leak. > > Can you confirm that the gc is enabled? > > > For a work-around, I can only suggest manually killing the global. What > happens > if you do this: > > del sys.modules['mymodule'] > mymodule.simple = None > del mymodule > > > or equivalent? > > > > > > -- > Steven > git gets easier once you get the basic idea that branches are homeomorphic > endofunctors mapping submanifolds of a Hilbert space. > > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 3.5.1 C API, the global available available is not destroyed when delete the module
Thank you all for the help. I found the problem is resolved if call PyGC_Collect() after PyDict_DelItemString(). Is it expected to call PyGC_Collect() here for Python 3.5 which is not needed for Python 3.3? 2016-09-20 16:01 GMT+08:00 Chris Angelico : > On Tue, Sep 20, 2016 at 4:19 PM, dl l wrote: > > Yes, it's a workaround to set the global variables to None. But My app > just > > provide a framework for my customers to run python scripts. That's means > > the workaround requires my customers to update their python scripts. That > > may make them unhappy :(. Is there a workaround in my code C++ side to > call > > Python C APIs to resolve the memory leak issue? > > > > Python's import system is fundamentally not designed for what I > believe is your use-case here, of running potentially-edited user > code. Instead, I suggest keeping 'import' for stable modules that > don't get updated without restarting the process, and for the more > dynamic code, build something using exec (or PyRun_StringFlags, which > I believe is the C equivalent). Object lifetimes will then be entirely > under your control. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 3.5.1 C API, the global available available is not destroyed when delete the module
I understood call PyGC_collect to release object cycles. But in my python test code, seems there is NO reference cycle on the Simple object in the python test code. Why needs to call PyGC_Collect() here? = class Simple: def __init__( self ): print('Simple__init__') def __del__( self ): print('Simple__del__') simple = None def run(): global simple simple = Simple() if __name__ == '__main__': run() == 2016-09-21 13:09 GMT+08:00 dieter : > dl l writes: > > I found the problem is resolved if call PyGC_Collect() after > > PyDict_DelItemString(). Is it expected to call PyGC_Collect() here for > > Python 3.5 which is not needed for Python 3.3? > > Usually, Python uses reference counting to determine when an object > can be deleted (and then reclaims its memory). > However, reference counting cannot determine an object's obsoleteness > when it is involved in a reference cycle. To address most of these > cases, Python has an alternative way to determine object obsoleteness > based on marking the accessible objects and garbage collecting > what is inaccessible. The alternative way is what "PyGC_collect" starts. > > If part of the objects where involved in a reference cycle, > you would have to call "PyGC_collect" also in Python 3.3 in order > to get a (mostly) clean memory state. > It might be, that Python 3.5 introduces more cycles than Python 3.3. > However, more likely, your code was responsible for the cycle creation > (and not Python itself). Likely, you just did not notice the problem > back for Python 3.3. > > Note that "PyGC_collect", too, is not garanteed to give a memory clean > state. It does not release object cycles involving objects with > an explicite destructor ("__del__" method). Those cycles are > made available to the application (consult the documentation of the > "gc" module) which can then decide what to do about them > (e.g. break the cycles and release the associated objects). > > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Python C API: How to debug reference leak?
I want to check the references of an object. Any way to get the references of an object with Python C API? Like: gc.get_referrs(), is there similar API in C lib? -- https://mail.python.org/mailman/listinfo/python-list
Re: Python C API: How to debug reference leak?
Thanks for reply. Is there any function in C to get the reference objects of a object? I want to debug where are referencing the object. 2016-09-27 15:01 GMT+08:00 dieter : > dl l writes: > > I want to check the references of an object. Any way to get the > references > > of an object with Python C API? Like: gc.get_referrs(), is there similar > > API in C lib? > > "gc" is a module. You can import and access modules from the C API. > Thus, you can use "gc.get_referers" from "C" code. > > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
PyImport_AddModule vs PyImport_Import
What is the difference between PyImport_AddModule and PyImport_Import? When need to use PyImport_AddModule? When need to use PyImport_Import? -- https://mail.python.org/mailman/listinfo/python-list
Re: PyImport_AddModule vs PyImport_Import
Thanks. That's helpful. I did not notice the note. 2016-09-27 19:24 GMT+08:00 Ned Batchelder : > On Tuesday, September 27, 2016 at 3:54:01 AM UTC-4, dl l wrote: > > What is the difference between PyImport_AddModule and PyImport_Import? > > > > When need to use PyImport_AddModule? > > > > When need to use PyImport_Import? > > Does this paragraph from the docs help? > > > Note > > > > This function does not load or import the module; if the module wasn’t > already loaded, you will get an empty module object. Use > PyImport_ImportModule() or one of its variants to import a module. Package > structures implied by a dotted name for name are not created if not already > present. > > https://docs.python.org/2/c-api/import.html#c.PyImport_AddModule > > > --Ned. > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: Python C API: How to debug reference leak?
When I debug in C++, I see the reference count of a PyObject is 1. I don't know where is referencing this object. How can I find out where is referencing this object? 2016-09-27 15:47 GMT+08:00 dl l : > Thanks for reply. Is there any function in C to get the reference objects > of a object? I want to debug where are referencing the object. > > 2016-09-27 15:01 GMT+08:00 dieter : > >> dl l writes: >> > I want to check the references of an object. Any way to get the >> references >> > of an object with Python C API? Like: gc.get_referrs(), is there similar >> > API in C lib? >> >> "gc" is a module. You can import and access modules from the C API. >> Thus, you can use "gc.get_referers" from "C" code. >> >> -- >> https://mail.python.org/mailman/listinfo/python-list >> > > -- https://mail.python.org/mailman/listinfo/python-list
[pyinotify] help required to send only one mail for chunk of events
Hi All, I am using the bellow script to watch directories. Using 20 seconds to aggregate together a larger chunk of events and enabled coalescing of events. I wanted to send an email notification with content of logfile after 15 mins on any change. The idea is I want to send only one mail for chunk of events.Say for example, I want to send only one email when some one extract a tar.gz file in watched directory. I can write method to send email (say send_mail) which accept content of logfile. But I am not sure How to integrate it with below code so that my send_mail method get triggered only once for chunk of events. Any help will be really appreciated. Thanks for your time and efforts. Here is code: #!/usr/bin/env python import sys try: import pyinotify except: print "pyinotify not installed" sys.exit(1) import datetime from ConfigParser import SafeConfigParser class MyEventHandler(pyinotify.ProcessEvent): log = "" flog = None def process_IN_CREATE(self, event): """ This method processes a specific type of event: IN_CREATE. event is an instance of Event. """ self.write_msg("CREATING", event.pathname) def process_IN_DELETE(self, event): """ This method processes a specific type of event: IN_DELETE. event is an instance of Event. """ self.write_msg("DELETING", event.pathname) def process_IN_MODIFY(self, event): """ This method processes a specific type of event: IN_MODIFY. event is an instance of Event. """ self.write_msg("MODIFIED", event.pathname) def process_IN_OPEN(self, event): """ This method processes a specific type of event: IN_OPEN. event is an instance of Event. """ self.write_msg("OPENED", event.pathname) def process_IN_ACCESS(self, event): """ This method processes a specific type of event: IN_ACCESS. event is an instance of Event. """ self.write_msg("ACCESSED", event.pathname) def process_IN_ATTRIB(self, event): """ This method processes a specific type of event: IN_ATTRIB. event is an instance of Event. """ self.write_msg("ATTRIB", event.pathname) def process_IN_DELETE_SELF(self, event): """ This method processes a specific type of event: IN_DELETE_SELF. event is an instance of Event. """ self.write_msg("DELETE_SELF", event.pathname) def process_IN_MOVED_FROM(self, event): """ This method processes a specific type of event: IN_MOVED_FROM. event is an instance of Event. """ self.write_msg("FILE MOVED FROM", event.pathname) def process_IN_MOVED_TO(self, event): """ This method processes a specific type of event: IN_MOVED_TO. event is an instance of Event. """ try: msg = event.src_pathname + " -> " + event.pathname except: msg = event.pathname self.write_msg("FILE MOVED INTO", msg) def openlog(self, logfile): """ This method opens log file in append mode. """ self.log = logfile self.flog = file(self.log, 'a') def write_msg(self, event, msg): """ This method writes evens in logfile as well as stdout. """ out_msg = self.generate_timestamp() + "\t" + event + ": " + msg + "\n" if len(self.log) > 0: self.flog.write(out_msg) self.flog.flush() print "LOGGED", out_msg else: print "NOT LOGGED", out_msg def generate_timestamp(self): """ This method generate and return timestamp for log. Timestamp format is /MM/DD-HH:MM:SS. """ d = datetime.datetime.now() datestr = "%d/%.2d/%.2d-%.2d:%.2d:%.2d" % (d.year, d.month, d.day, d.hour, d.minute, d.second) return datestr def main(): parser = SafeConfigParser() parser.read('/etc/mywatcherscript.ini') ### The watch manager stores the watches and provides operations on watches ### wm = pyinotify.WatchManager() ### List of watched events. To specify two or more events just orize them ### mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY # List of watch path #watched_path_list=['/var/log','/tmp'] watched_path_list=parser.get('mywatcherscript', 'watched_path_list').split(',') pid_file_name=parser.get('mywatcherscript', 'pid_file_name') logfile=parser.get('mywatcherscript', 'logfile') # Add watch(s) on the provided path(s) with associated flag value. # Parameters: # path - Path to watch, the path can either be a file or a directory. #Also accepts a sequence (list) of paths. # mask (int) - Bitmask of events. # rec (bool) - Recursively add watches from path on all its subdirectories. # auto_add (bool) - Automatically add watches on newly created directories in watched parent directory. # # Returns: dict of {str: int} # dict of paths associated to watch descriptors. wm.add_watch(watched_path_list, mask, rec=True, auto_add=True) # event handler eh = MyEventHandler() eh.openlog(logfile) # notifier # Put an arbitrary large value (20 seconds) to aggregate together a larger # chunk of events. For instance if you repeat several times a given action # on the same file its events will be coalesced into a single event and only # one event of this type will be reported (for this period). notifier = pyinotify.Notifier(wm, eh, read_freq=20) #notifier = pyinotify.Notifier(wm, eh) # Enable coalescing of events. notifier.c
Help to understand the data structure
Hi All, I am using get_devices_list method from this module: https://github.com/Tufin/pytos/blob/master/pytos/securetrack/helpers.py. Here is my two like code and output looks like: https://pastebin.com/K9KBeqYL I am not able to manage to further loop the data to print below output: devicename1 10 devicename2 11 devicename3 12 I spend quit some time still not able to figure out how to parse. Can some one through some light on how to phrase it. -- Thanks & Regards Mohan L -- https://mail.python.org/mailman/listinfo/python-list
Re: Help to understand the data structure
Hi All, Please ignore it, I was able to figure out it. for dev in devlist: print (dev.name, dev.id) -- Thanks & Regards Mohan L On Fri, Sep 27, 2019 at 8:41 PM Mohan L wrote: > Hi All, > > I am using get_devices_list method from this module: > https://github.com/Tufin/pytos/blob/master/pytos/securetrack/helpers.py. > Here is my two like code and output looks like: > https://pastebin.com/K9KBeqYL > > > I am not able to manage to further loop the data to print below output: > > > devicename1 10 > > devicename2 11 > > devicename3 12 > > > I spend quit some time still not able to figure out how to parse. Can some > one through some light on how to phrase it. > > > -- > Thanks & Regards > Mohan L > > > -- https://mail.python.org/mailman/listinfo/python-list
Re: Character Sequence Generation
Jeff Schwab wrote: > [EMAIL PROTECTED] wrote: > > Jeff Schwab wrote: > > > >>What's the best way to generate a sequence of characters in Python? I'm > >>looking for something like this Perl code: 'a' .. 'z' . > > > > > import string > > > > > print string.ascii_lowercase > > > > abcdefghijklmnopqrstuvwxyz > > Thanks. Is there a good way to generate the characters dynamically? ''.join([chr(i) for i in range(97,123)]) -- http://mail.python.org/mailman/listinfo/python-list
Could this C extension be leaking memory?
I am trying this out, parts of it are direct from the Python 2.4 manual. //--- icallbk.c #include "Python.h" PyObject *fcallback = NULL; static PyObject* call_func(PyObject* self, PyObject* args) { PyObject *result; PyObject *arglist; int arg = 123; arglist = Py_BuildValue("(i)", arg); result = PyEval_CallObject(fcallback, arglist); Py_DECREF(arglist); Py_DECREF(result); Py_RETURN_NONE; } static PyObject * set_callback(PyObject *self, PyObject *args) { PyObject *result = NULL; PyObject *temp; if (PyArg_ParseTuple(args, "O:set_callback", &temp)) { if (!PyCallable_Check(temp)) { PyErr_SetString(PyExc_TypeError, "parameter must be callable"); return NULL; } Py_XINCREF(temp); /* Add a reference to new callback */ Py_XDECREF(fcallback); /* Dispose of previous callback */ fcallback = temp; /* Remember new callback */ /* Boilerplate to return "None" */ Py_INCREF(Py_None); result = Py_None; } return result; } static PyMethodDef icallbk_methods[] = { { "call_func", call_func, METH_VARARGS, "call_func" }, { "set_callback", set_callback, METH_VARARGS, "set_callback" }, { 0,0,0,0 } }; PyMODINIT_FUNC initicallbk(void) { (void) Py_InitModule("icallbk", icallbk_methods); } """ I use the following code to run the extension above. """ # cb.py: Code to run the extension above. import icallbk as c def f(a): print a c.set_callback(f) c.call_func() """ But when I run that for a hundred times, I think the system is losing 100KB or thereabouts that is no longer re-claimed. Can someone confirm this, and if it so, kindly inform me what is wrong with the code? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: execution order in list/generator expression
[EMAIL PROTECTED] wrote: > Hi, > > I am wondering how this is evaluated. > > a=(x for x in [1,2,3,4]) > p=[4,5] > > c=[x for x in p if x in list(a)] > > c is [] > > but if I expand a first, like a = list(a) > > c is [4] > > So it seems that the "if" part don't get expanded ? Well, for every element in p it recalculates list(a). Since the generator is exhausted after making a list from it, it gives you nothing afterwards. So after it checks the first element, it's equivalent to [x for x in p if x in []]. -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing at runtime
http://www.python.org/doc/2.4.2/lib/built-in-funcs.html or, if you want an answer in code now and don't want to read the docs def my_import(name): module = __import__(name) globals()[name] = module #not a good idea Or, seeing as how you won't be directly accessing them by name, anyways modules = [__import__(name) for name in module_names] -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing Modules
Sam Pointon wrote: > On the second point, a combination of sys.path, os.listdir and > __import__ should do what you're after, although sifting through the > whole of sys.path and subfolders from Python, rather than the > interpreter itself, could be slow. (And it'll be redundant as well - > __import__ will have do the same thing, though you could fix that by > using the imp module). > > -Should- work, but not tested, so don't blame me if it doesn't: > [code] __import__(modulename) is not equivalent to import modulename; __import__ returns a module object >>> __import__('pickle') >>> pickle -- http://mail.python.org/mailman/listinfo/python-list
Re: Cheapest pocket device to code python on
[EMAIL PROTECTED] wrote: > What is the cheapest/affordable pocket device that I can code python > on? I think the closest I have seen is pocketpc from this page: > > http://www.murkworks.com/Research/Python/PocketPCPython/Overview I would not recommend trying to code on a handheld device. Small screen size and [usually] small keyboards make it less-than-practical. Stick with a laptop, or write it in a notebook, if you must. -- http://mail.python.org/mailman/listinfo/python-list
Is mod_python 3.1 good for commercial blogging/CMS?
I am writing a web application that is comparable to a content management system used in blogging. I really want to use Python after having done some evaluation coding using Python 2.3.5 with mod_python 3.1.4 running on Apache 2.0 with the Publisher handler. However, I am still very hesitant to settle on Python. All my research brings up the same collection of scant articles and old mailing list messages that reference each other. I am not interested in using frameworks, partly because I am confused by them, but mostly because I don't want to add another layer of software complexity on top of my code since I already am expecting a hard time finding low-cost dedicated hosting with Apache 2 and mod_python 3 support. I have made a few assumptions regarding Python and mod_python's value. Hopefully the experts here can help correct any of my assumptions and give me some more comfort in committing to Python. 1. I want to use CGI through Publisher handler, instead of CGI handler or PSP. Despite the speed increase mod_python gives me, there is a problem of persistence that can be a problem when dealing with a site that will hosts potentially hundreds of simultaneous users. 2. I have found nothing to quantify the stability and reliability of mod_python 3, and in the absence of a list of major commercial sites that use mod_python, I am left feeling as is there might be technical (read as stability/security) reasons to favor mod_perl over mod_python. 3. I am not very attracted to PSP because I want to separate the logic from the presentation as completely as possible, and PHP and other template languages including PSP seem difficult to do that in. Learning template systems like PyMeld is an unattractive option for me since I don't understand their benefit. Why can't I just use req.write() to output my markup, relying completely on external CSS after the fact? My thought is that HTML templates provide a minimum set of static code that doesn't require extra processing, thus keeping performance up. However, if I minimize my use of req.write() will it make a difference? 4 A final question, is mod_python 2.7 suitable for use in a commercial production system? All I'm doing is text processing, string manipulation, database calls, and some very minor mathematics. If the Apache 1.3 series mod works fine, can I relieve myself of some stress and go with that combo? I'd appreciate some practical advise on this. I am funding this myself on a small budget with no hard deadline, so it is critical to me that I choose a language that will minimize my costs. Are my assumptions correct, or am I falling prey to FUD? Anthony -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
Gustav Hållberg wrote: > I tried finding a discussion around adding the possibility to have > optional underscores inside numbers in Python. This is a popular option > available in several "competing" scripting langauges, that I would love > to see in Python. > > Examples: > 1_234_567 > 0xdead_beef > 3.141_592 > > Would appreciate if someone could find a pointer to a previous > discussion on this topic, or add it to a Python-feature-wishlist. > > - Gustav I'm not sure what the _s are for, but I'm guessing they serve as separators ("." or "," depending on where you're from). I think the _s look ugly to me, besides, underscores look more like spaces than separators. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is mod_python 3.1 good for commercial blogging/CMS?
In article <[EMAIL PROTECTED]>, "Ben Sizer" <[EMAIL PROTECTED]> wrote: > Anthony L. wrote: > > 1. I want to use CGI through Publisher handler, instead of CGI handler > > or PSP. Despite the speed increase mod_python gives me, there is a > > problem of persistence that can be a problem when dealing with a site > > that will hosts potentially hundreds of simultaneous users. > > What problem? Could you elaborate further? Hi Ben. This is what I myself am trying to find out. From what I gather, hosts dislike long running processes, and so one reason for not supporting Python and mod_python is that, plus multiple instances of the python interpreter. Granted, a lot of this looks like old information combined with FUD, so I am suspicious. After all, high-traffic sites using mod_perl seem okay. > In theory, people use these templates to /improve/ the separation > between logic and presentation. When you just use req.write() you're > inevitably mixing logic and presentation. At least with the template > systems, you do the presentation once and the logic fills in the gaps. > It's even possible to edit the presentation in many WYSIWYG web editors > without affecting the code. Yes, I see your point. In this case it works for me (at the moment) because the HTML design will remain as is without subject to editing, whereas the look and feel (controlled by CSS) will be user-editable. > I don't think performance is a factor, really. HTML templates tend to > exist so that you can structure the page without worrying about the > Python code. They work well for fairly uniform pages that largely > require the same sort of data on each page. I am more of a programmer > than a designer so I prefer to think in terms of code and emit HTML as > it suits me. Okay, I might have been unfair in looking away from PSP then. Thanks Ben. Anthony -- http://mail.python.org/mailman/listinfo/python-list
Re: Is mod_python 3.1 good for commercial blogging/CMS?
In article <[EMAIL PROTECTED]>, Francois Lepoutre <[EMAIL PROTECTED]> wrote: > > 3. I am not very attracted to PSP because I want to separate the logic > > from the presentation as completely as possible [...] > > In view of your project why not consider cherrypy as well? It may > be an alternative to consider. Hi Francois, I'm getting more open to considering other frameworks. As I mentioned earlier, I am aware that I am swimming against the current by not simply using Apache 1 and PHP, so I wanted to avoid investing in yet another esoteric piece of software. Thankfully, after a discussion with some prospective hosts today, I have the freedom to consider CherryPy and Django. > > manipulation, database calls, and some very minor mathematics. If the > > Apache 1.3 series mod works fine, can I relieve myself of some stress > > and go with that combo? > > Why not? But why not work with apache 2.x. mod_python works fine on > this platform. Oh, it's not that I have anything against Apache 2. My preference is to work with mod_python 3, and that requires Apache 2, which I want. I was just considering a less desirable pythonic option. Even among commodity shared hosting providers I've found the presence of earlier versions of python and mod_python. > no FUD here. Read the mod_python carefully, run your tests and make up > your choice. This is definitely a workable environment. > > Francois Thanks Francois. I am going to stick with Python for this. As it turns out, I'll have the freedom to use the software configuration I want, so now I don't have to worry about committing to Python, only discover that my Python code is useable only as a prototype for PHP or Perl. :) Anthony -- http://mail.python.org/mailman/listinfo/python-list
Re: Is mod_python 3.1 good for commercial blogging/CMS?
In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] (John J. Lee) wrote: > "Ben Sizer" <[EMAIL PROTECTED]> writes: > [...] > > It as not easy to work with the CGI-style code in a WYSIWYG web editor > > as it is to edit a template, which is probably the main reason for > > their use. Also, coding everything with req.write() means that each > [...] > > You seem to believe CGI is incompatible with templating. Why? The > two are entirely independent of each other. > > > John He was just referring to the idea of me perhaps editing the HTML markup in my Python code using an IDE like Dreamweaver and having a difficult time. I agree, editing an HTML doc in a WYSIWYG environment would be easier than me fishing through my req.write() calls and my strings to find my markup - which is what I am doing at the moment. Anthony -- http://mail.python.org/mailman/listinfo/python-list
Re: Command-line tool able to take multiple commands at one time?
Peter A. Schott wrote: > Per subject - I realize I can copy/paste a line at a time into an interactive > session when I'm trying to debug, but was wondering if there is any tool out > there that allows me to copy sections of working Python scripts to paste into > my > interactive console and let those run so I don't have to copy line-by-line. > > Not sure if iPython would meet that criteria or not or even if such a beast > exists. It would be helpful for debugging some of my simpler, yet still > lengthy > at times, scripts. > > Thanks in advance. > > -Pete Schott It's called IDLE (At least, the interactive session with it). Some people dislike IDLE, though. -- http://mail.python.org/mailman/listinfo/python-list
Re: Command-line tool able to take multiple commands at one time?
Peter A. Schott wrote: > OK - I justed tested and may be doing something wrong, but it didn't work > when I > just tried it. > > I have something like this: > > X = "Value1" > Y = "Value2" > Z = "Value3" > > etc at the top of my script. When I copy/paste those three lines all at once > into IDLE's interactive window, X is defined, Y and Z are not. > > That's more the behaviour I was hoping for - the ability to run parts of my > code > at a time in order to work through issues without too much trouble in > mostly-working code. > > TIA, > > -Pete Schott Oh, that kind of multi-line input. I thought you were talking about >>> def foo(bar): ...long_statement_here ...even_longer_statement_here ...return something I would just put it into a .py and run it through IDLE, change it, and rerun it. There are probably other IDEs which can already do that, but I just use IDLE. -- http://mail.python.org/mailman/listinfo/python-list
Re: XUL behavior in Python via XPCOM, Mozilla
Terry Hancock wrote: > I recently saw a claim that Mozilla XUL behaviors (normally > scripted in Javascript) can (or perhaps will) be scriptable > in Python. > > Also, "other languages such as Java or Python are supported > through XPCOM", said about Mozilla (from Luxor website). > > Yes, I know several ways to *generate* XUL from Python, and > at least one way to use XUL to create interfaces for Python > programs, but in this case, I'm talking about defining > button action behavior in XUL by calling Python scripts. > > I know that Javascript is the preferred language, but I've > seen several references to being able to do this in Python, > including a claim that a release was targeted for early > November (2005), to provide this. > > Now I can't find it again. Anyway, I was hoping someone > on c.l.p / python.org would have a reliable reference on > this. > > Thanks, > Terry > > -- > Terry Hancock ([EMAIL PROTECTED]) > Anansi Spaceworks http://www.AnansiSpaceworks.com Nufox? http://trac.nunatak.com.au/projects/nufox -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursion bug...
ex_ottoyuhr wrote: > To start with, I'm new at Python, so if this is something relatively > ordinary or a symptom of thinking in C++, I apologize... > > Anyhow, I'm currently trying to write a means of generating > genetic-programming functions in Python; the details would be a little > much for a Usenet post, but suffice it to say that it would involve > trees of objects with an opcode and a variable number, between in this > case 0 and 3, of 'arguments' -- also objects of the same sort. As a > function to implement them, I'm doing something to the effect of this: > > [ex_ottoyuhr's code] > > Sorry to have given such a long example... But anyways, the problem is > that, while I think this should generate a number of children for each > toRet equivalent to the required number of children, it's actually > appending all children generated in the function to the 'root' toRet > rather than to child functions -- so that if I ask for a tree with > depth 2, and the root would have 2 arguments, the first child would > have 1, and the second child would have 2, the result is a root with a > 5-argument-long children and two child functions with 0-argument ones. > There's some other strange stuff going on here, too; in particular, > with one particular opcode, toRet is assigned a member 'value' which is > randomly generated between 0 and 10,000. All toRets assigned value seem > to be ending up with the same result... > > Could anyone explain what I'm doing wrong? I'm beginning to suspect > that Python scope rules must not work like my native C++; have I made a > common mistake? Well, for one, in your __init__ method, you never do anything with anOpcode. You simply assign the name 'opcode' to anOpcode. The reason why everything is the same is that you're accessing TreeCommand.children or Treecommand.opcode, which is shared by all instances unless you assign to it. And you never increment generated, so I don't see why the while loop would ever end, unless you intentionally wanted that. Try this code instead: max_opcode = 20 max_with_args = 15 class TreeCommand: def __init__(self, opcode) : self.opcode = opcode self.children = [] def MakeTreeCommand(depth, maxdepth) : if depth == 0: command = TreeCommand(random.randint(0, max_with_args) elif depth == maxdepth: command = TreeCommand(random.randint(max_with_args+1, max_opcode)) else: command = TreeCommand(random.randint(0, max_opcode)) if command.opcode <= max_with_args: children_required = something_greater_than_0 else: children_required = 0 generated = 0 for i in range(children_required): command.children.append(MakeTreeCommand(depth+1, maxdepth)) return command -- http://mail.python.org/mailman/listinfo/python-list
Re: How to execute an EXE via os.system() with spaces in the directory name?
I don't have any problems with spaces in the folders. just for debugging, you could probably try os.system(CMD.replace("\\", "/") On 3 Dec 2005 19:16:10 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > I am trying to run an exe within a python script, but I'm having > trouble with spaces in the directory name. > > The following example will display the usage statement of the program, > so I know that the space in the path to the exe is being handled > correctly and that the program was executed. > > CMD= r'"C:\program files\some directory\engine\theexe.exe"' > os.system(CMD) > > But the required argument for the exe require a path to a file to be > specified. When I try to run the following, os.system(CMD2) > CMD2= r'"C:\program files\some directory\engine\theexe.exe" "C:\program > files\some directory\engine\file.txt"' > > I get this error: > Unable to open file C:\Program > > So, it looks to me like the space in the path for the argument is > causing it to fail. Does anyone have any suggestions that could help > me out? > Thanks, > Steve > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: join dictionaries using keys from one & values
ProvoWallis wrote: > Thanks so much. I never would have been able to figure this out on my > own. > > def dictionary_join(one, two): > > dict2x = dict( ((dict2[k], k) for k in dict2.iterkeys())) > dict3 = dict(((k, dict2x[v]) for k,v in dict1.iteritems())) > print dict3 > > dict1 = {1:'bbb', 2:'aaa', 3:'ccc'} > > dict2 = {'5.01':'bbb', '6.01':'ccc', '7.01':'aaa'} > > dictionary_join(dict1, dict2) You might want to make a working function. def join_dicts(d1,d2): temp = dict(((d2[k], k) for k in d2.iterkeys())) joined = dict(((k, temp[v]) for k,v in d1.iteritems())) return joined -- http://mail.python.org/mailman/listinfo/python-list
Re: what's wrong with "lambda x : print x/60,x%60"
Steve Holden wrote: > [EMAIL PROTECTED] wrote: > > "Gary Herron" <[EMAIL PROTECTED]> wrote in message > > news:[EMAIL PROTECTED] > > > >>--snip-- > >>So just use a def. It is constantly pointed out on > >>this list that the lambda provides no extra expressive power, it is > >>merely a shortcut > > > > > > No, it is not merely a shortcut. It often allows one to avoid > > polluting > > the namespace with a completely superfluous function name, thus > > reducing code smell. It can also avoid a multi-line function defintion > > which often pushes other relevant code off the current page and > > out of view, and thus lambda can increase program readability. > > > I'm getting a little tired of "namespace pollution" being trotted out as > a reason to use lambda. Defining a function, and giving it a name, isn't > "polluting the namespace", any more than assigning sub-expressions to > temporary variables is polluting the namespace. Why use temporary > variables when all you have to do is make your expressions three lines > long to avoid "polluting the namespace"? I agree, if I were to name my function `shuffle', then I wouldn't be able to name any of my intermediate functions `shuffle'! Oh the humanity! Therefore I will instead use adhere to my 0 namespace pollution policy and use this instead: __nopollution_at__all_portion = range(50) __nopollution_at__all_word = 'mint white chocolate chip' if __name__ == '__main__': print (lambda portion,word:(lambda x,word:[x.pop() for i in range(len(word))]+x)((lambda x,word:[x.pop() for i in range(len(word))]+x)((lambda x,word:[x.pop() for i in range(len(word))]+x)((lambda x,word:[x.pop() for i in range(len(word))]+x)(portion[:],word),word),word),word))(__nopollution_at__all_portion,__nopollution_at__all_word) ;-) -- http://mail.python.org/mailman/listinfo/python-list
MDaemon Warning - virus found: Error
*** WARNING ** Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado un fichero anexo(s) infectado(s). Por favor revise el reporte de abajo. AttachmentVirus name Action taken -- file.zip I-Worm.Mydoom.m Removed ** This message was not delivered due to the following reason(s): Your message was not delivered because the destination server was not reachable within the allowed queue period. The amount of time a message is queued before it is returned depends on local configura- tion parameters. Most likely there is a network problem that prevented delivery, but it is also possible that the computer is turned off, or does not have a mail system running right now. Your message could not be delivered within 2 days: Host 7.131.94.177 is not responding. The following recipients did not receive this message: Please reply to [EMAIL PROTECTED] if you feel this message to be in error. -- http://mail.python.org/mailman/listinfo/python-list
Re: what list comprehension can't
I wasn't aware that python supported "if then else". -- http://mail.python.org/mailman/listinfo/python-list
Re: Favorite non-python language trick?
Why overload when you can use class methods? -- http://mail.python.org/mailman/listinfo/python-list
Re: Favorite non-python language trick?
But by using the builtin reduce, you need to specify a function, which probably slows it down more than any speed-up from the loop in C. -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question
To recognize variables that you have assigned, just look for assignment. If your code is readible, and you know it well, you shouldn't need the $ sign in front of everything. -- http://mail.python.org/mailman/listinfo/python-list
Re: Favorite non-python language trick?
< "return a if a.value == true" < "database.query(q) unless database.connect == error (etc) if a.value == True: return a if not database.connect == error: database.query(q) Trading two words for one word doesn't necessarily make the code better. < unless false then print 1 # this prints 1 forever while not False: print 1 "unless" seems to become "while not", as opposed to "if not". Should be more consistent. -- http://mail.python.org/mailman/listinfo/python-list
Re: I need help figuring out how to fix this code.
password = raw_input("Type in the password, please: ") while password != "hello": print "Incorrect password!" Wouldn't this print "Incorrect password" untill the end of time if you didn't supply the correct password? -- http://mail.python.org/mailman/listinfo/python-list
Re: regulars expressions ?
re.findall(r'"?(.+?)"?(?:,|$)', yourtexthere) -- http://mail.python.org/mailman/listinfo/python-list
Re: regulars expressions ?
Oh, oops, sorry, that code doesn't respect the quotes. Use this code: re.findall(r'(".+?"|\S+)(?:,|$)', yourtexthere) -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: Help Figger Out My Problem
import random flips = 100 results = [random.randint(0,1) for i in range(flips)] heads = results.count(0) tails = results.count(1) print "Heads:%s" % heads print "Tails:%s" % tails I think this is more compact. -- http://mail.python.org/mailman/listinfo/python-list
Re: When someone from Britain speaks, Americans hear a "British accent"...
Thats like posting about Google here because the newsgroup is hosted on Google. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for everything?
Python for everything except things that need to be ridiculously optimized for speed. Thats what C embedded in Python and Psyco enhanced Python code is for. Oh wait, thats still all Python... -- http://mail.python.org/mailman/listinfo/python-list
Re: class attribute to instance attribute
Why make it an instance attribute? Couldn't you just look at the class attribute? If its something that depends on each instance's value assigned to the attribute, why not make it an instance attribute to start with? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to run commands in command line from a script
The code module, perhaps? http://www.python.org/doc/2.4.1/lib/module-code.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Escaping commas within parens in CSV parsing?
Try this. re.findall(r'(.+? \(.+?\))(?:,|$)',yourtexthere) -- http://mail.python.org/mailman/listinfo/python-list
Re: Escaping commas within parens in CSV parsing?
Oops, the above code doesn't quite work. Use this one instead. re.findall(r'(.+? (?:\(.+?\))?)(?:,|$)',yourtexthere) -- http://mail.python.org/mailman/listinfo/python-list
Re: Splitting string into dictionary
One line solution. dict(re.findall(r"'(.+?)' \| '(.+?)'(?:\s\||$)",yourtexthere)) -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression for pattern substitution
re.replace. I don't think there's any way to avoid it. Except maybe having an alias email address or a fake one. -- http://mail.python.org/mailman/listinfo/python-list
Re: map/filter/reduce/lambda opinions and background unscientific mini-survey
None of them are really indispensible. Map and filter cab be replaced with list comprehensions. reduce is redundant except when multiplying a series; there's a sum function for a reason. Lambda looks cleaner in some cases, but you don't gain any functionality. What really struck me, though, is the last line of the abstract: "I expect tons of disagreement in the feedback, all from ex-Lisp-or-Scheme folks. :-)" Guido wrote somewhere that the original map, filter, and reduce came from a lisp hacker who missed them. -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression for pattern substitution
Hrm, thought it had one. Guess it would help if I actually used regular expression for replacement. -- http://mail.python.org/mailman/listinfo/python-list
Re: class attribute to instance attribute
Well, I've never heard of a method like that for assigning variables. I'd rather put it in the __init__ method. -- http://mail.python.org/mailman/listinfo/python-list
Re: Favorite non-python language trick?
With the exception of reduce(lambda x,y:x*y, sequence), reduce can be replaced with sum, and Guido wants to add a product function. -- http://mail.python.org/mailman/listinfo/python-list
Re: map/filter/reduce/lambda opinions and background unscientific mini-survey
Claiming that sum etc. do the same job is the whimper of someone who doesn't want to openly disagree with Guido. Could you give an example where sum cannot do the job(besides the previously mentioned product situation? Also, map is easily replaced. map(f1, sequence) == [f1(element) for element in sequence] -- http://mail.python.org/mailman/listinfo/python-list
Re: Favorite non-python language trick?
sum(sequence[0] + [1/element for element in sequence[1:]]) I think that should work. -- http://mail.python.org/mailman/listinfo/python-list
Re: Favorite non-python language trick?
Okay, maybe that was too restrictive, reduce can *usually* be replaced with sum. Sorry about that. -- http://mail.python.org/mailman/listinfo/python-list
Re: map/filter/reduce/lambda opinions and background unscientific mini-survey
def flatten(iterable): if not hasattr(iterable, '__iter__'): return [iterable] return sum([flatten(element) for element in iterable],[]) Recursion makes things so much shorter. -- http://mail.python.org/mailman/listinfo/python-list
Re: map/filter/reduce/lambda opinions and background unscientific mini-survey
> Here's a couple of examples from my own code: > > # from a Banzhaf Power Index calculator > # adds things that aren't numbers > return reduce(operator.add, > (VoteDistributionTable({0: 1, v: 1}) for v in electoral_votes)) return sum([VoteDistributionTable({0:1, v:1} for v in electoral_votes],VoteDistributionTable({})) Any time you use operator.add, you can probably use sum(sequence,initialvalue) > # from a custom numeric class > # converts a tuple of digits into a number > mantissa = sign * reduce(lambda a, b: 10 * a + b, mantissa) I'll admit I can't figure out a way to replace reduce without writing some ugly code here, but I doubt these sorts of things appear often. -- http://mail.python.org/mailman/listinfo/python-list
Re: removing list comprehensions in Python 3.0
List comprehensions are faster than generator comprehensions for iterating over smaller sequences. -- http://mail.python.org/mailman/listinfo/python-list
Re: removing list comprehensions in Python 3.0
>>> import timeit >>> t1 = timeit.Timer('list(i for i in xrange(10))') >>> t1.timeit() 27.267753024476576 >>> t2 = timeit.Timer('[i for i in xrange(10)]') >>> t2.timeit() 15.050426800054197 >>> t3 = timeit.Timer('list(i for i in xrange(100))') >>> t3.timeit() 117.61078097914682 >>> t4 = timeit.Timer('[i for i in xrange(100)]') >>> t4.timeit() 83.502424470149151 Hrm, okay, so generators are generally faster for iteration, but not for making lists(for small sequences), so list comprehensions stay. -- http://mail.python.org/mailman/listinfo/python-list
Re: Yet Another Python Web Programming Question
Take some time to learn one of the web frameworks. If your host doesn't already have it, ask your host if they would consider adding it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Forum
I see a total of 12 posts and 8 users. -- http://mail.python.org/mailman/listinfo/python-list
Re: question on "input"
Use raw_input instead. It returns a string of whatever was typed. Input expects a valid python expression. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with inverted dictionary
import re name = "Robert" f = file('phonebook.txt','r') lines = [line.rstrip("\n") for line in f.readlines()] pat = re.compile(name, re.I) related_lines = [line for line in lines if pat.search(line)] And then you write the lines in related_lines to a file. I don't really write text to files much so, um, yeah. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating anonymous functions using eval
How is this different from a nested function? -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with inverted dictionary
I think you need to get a database. Anyways, if anything, it should create no more than 5,000 files, since 5,000 facts shouldn't talk about 30,000 animals. There have been a few discussions about looking at files in directories though, if you want to look at those. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with inverted dictionary
Oh, I seem to have missed the part saying 'or other word'. Are you doing this for every single word in the file? -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating anonymous functions using eval
Well, the string that gets passed is more or less a function definition, which is then called with exec. I don't see why you'd need to write a string out with the function definition and then call it. You could just write the function. As for the nested functions, I had been presuming that it was intended to use as a better function than lambda within a function. Sorry for the confusion. -- http://mail.python.org/mailman/listinfo/python-list
Re: automatically assigning names to indexes
import math class Vector: def __init__(self, coordinates): self.coordinates = coordinates self.magnitude = sum([c**2 for c in coordinates])**0.5 self.direction = getangle(Vector([1]+[0 for i in range(len(coordinates)-1)])) def dotproduct(self, vector): sum([a*b for a,b in zip(self.coordinates,vector.coordinates)]) def crossproduct(self, vector, pvector): return pvector*self.magnitude*vector.magnitude*math.sin(self.getangle(vector)) def getangle(self, vector): return math.acos(self.dotproduct(vector)/(self.magnitude*vector.magnitude)) def __mul__(self, scalar): return Vector([c*scalar for c in self.coordinates]) def __add__(self, vector): return Vector([c+d for c,d in zip(self.coordinates,vector.coordinates)]) def __sub__(self, vector): return Vector([c-d for c,d in zip(self.coordinates,vector.coordinates)]) What about this? -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating anonymous functions using eval
> You missed Steven's point which is to quote the message to which you are > replying. Not everyone is reading this list in a conveniently threaded > form, so you need to provide some context for them to be able to follow > along. Ah, sorry, I didn't quite get what he was referring to. -- http://mail.python.org/mailman/listinfo/python-list
Re: Odd behaviour of regexp module
Why doesn't group have an argument? group() or group(0) returns what the pattern matched, not what it returns. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem loading a file of words
teoryn wrote: > I've been spending today learning python and as an exercise I've ported > a program I wrote in java that unscrambles a word. Before describing > the problem, here's the code: > > *--beginning of file--* > #!/usr/bin/python > # Filename: unscram.py > > def sort_string(word): > '''Returns word in lowercase sorted alphabetically''' > word = str.lower(word) > word_list = [] > for char in word: > word_list.append(char) > word_list.sort() > sorted_word = '' > for char in word_list: > sorted_word += char > return sorted_word > > print 'Building dictionary...', > > dictionary = { } > > # Notice that you need to have a file named 'dictionary.txt' > # in the same directory as this file. The format is to have > # one word per line, such as the following (of course without > # the # marks): > > #test > #hello > #quit > #night > #pear > #pare > > f = file('dictionary.txt') > > # This loop builds the dictionary, where the key is > # the string after calling sort_string(), and the value > # is the list of all 'regular' words (from the dictionary, > # not sorted) that passing to sort_string() returns the key > > while True: > line = f.readline() > if len(line) == 0: > break > line = str.lower(line[:-1]) # convert to lowercase just in case > and > # remove the return at the end of > the line > sline = sort_string(line) > if sline in dictionary: # this key already exist, add to > existing list > dictionary[sline].append(line) > print 'Added %s to key %s' % (line,sline) #for testing > else: # create new key and list > dictionary[sline] = [line] > print 'Created key %s for %s' % (sline,line) #for > testing > f.close() > > print 'Ready!' > > # This loop lets the user input a scrambled word, look for it in > # dictionary, and print all matching unscrambled words. > # If the user types 'quit' then the program ends. > while True: > lookup = raw_input('Enter a scrambled word : ') > > results = dictionary[sort_string(lookup)] > > for x in results: > print x, > > print > > if lookup == 'quit': > break > *--end of file--* > > > If you create dictionary.txt as suggested in the comments, it should > work fine (assumeing you pass a word that creates a valid key, I'll > have to add exceptions later). The problem is when using a large > dictionary.txt file (2.9 MB is the size of the dictionary I tested) it > always gives an error, specifically: > (Note: ccehimnostyz is for zymotechnics, which is in the large > dictionary) > > > *--beginning of example--* > Enter a scrambled word : ccehimnostyz > Traceback (most recent call last): > File "unscram.py", line 62, in ? > results = dictionary[sort_string(lookup)] > KeyError: 'ccehimnostyz' > *--end of example--* > > > If you'd like a copy of the dictionary I'm using email me at teoryn at > gmail dot com or leave your email here and I'll send it to you (It's > 702.2 KB compressed) > > Thanks, > Kevin Heh, it reminds me of the code I used to write. def sort_string(word): return ''.join(sorted(list(word.lower( f = open('dictionary.txt','r') lines = [line.rstrip('\n') for line in f.readlines()] f.close() dictionary = dict((sort_string(line),line) for line in lines) lookup = '' while lookup != 'quit': lookup = raw_input('Enter a scrambled word:') if dictionary.has_key(lookup): word = dictionary[lookup] else: word = 'Not found.' print word You need python 2.4 to use this example. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem loading a file of words
Robert Kern wrote: > That's definitely not the kind of dictionary that he wants. > > -- > Robert Kern > [EMAIL PROTECTED] > > "In the fields of hell where the grass grows high > Are the graves of dreams allowed to die." >-- Richard Harter Oh, I missed the part where he put values in a list. -- http://mail.python.org/mailman/listinfo/python-list
Re: A Module on Time & Date
Robert Maas, see http://tinyurl.com/uh3t wrote: > > From: Robert Kern <[EMAIL PROTECTED]> > > As you can see in the datetime documentation, the module was introduced > > in Python 2.3. I recommend updating your Python installation. > > What do you mean "your"?? I don't have any Python installation of my > own. All I have is what this small local ISP provides on its Unix shell > machine which I share with hundreds of other users. There's no way I > can install a new version of anything on the system account. > Your recommendation will be disregarded as total crap. You should contact your isp and ask them to upgrade, then. -- http://mail.python.org/mailman/listinfo/python-list
Re: [pygame]how to copy a surface to an other surface with alpha value?
flyaflya wrote: > I want to join some surfaces to a new big surface with alpha cannel, I want > the new surface has same pixels(inclue r,g,b and alpha value) as the pixels > on the source surfaces. > my code as follow: > > surf = pygame.Surface((200,200)) > surf.blit(surf1, (0,0)) > surf.blit(surf2, (0,100)) > . > > but these codes can't copy alpha value to the new surface.how can I deal > with it? Try the pygame mailing list or irc channel. http://www.pygame.org/info.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: searching string url
Sounds somewhat like homework. So I won't just give you a code solution. Use the regular expression(re) module to match the urls. -- http://mail.python.org/mailman/listinfo/python-list
Re: Wheel-reinvention with Python
Ed Leafe wrote: > On Sunday 31 July 2005 22:39, Paul Rubin wrote: > > > > import dabo > > > app = dabo.dApp() > > > dApp.start() > > > > > > Sorry, I couldn't do it in 5. ;-) Oh, and that includes a full menu, > > > too. > > > > I get an ImportError exception when I try that. Any suggestions? Note > > that I don't get that exception from Tkinter. > > bash-3.00$ python > > Python 2.3.4 (#1, Oct 26 2004, 16:42:40) > > [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > > >>> import dabo > > Traceback (most recent call last): > > File "", line 1, in ? > > ImportError: No module named dabo > > >>> import Tkinter > > >>> > > Oh, c'mon now Paul, now you're trolling. You know exactly what the problem > is, and try to make it look like a bug. > > Fine: you don't want to use anything that doesn't come standard with Python. > You've made your point. We get it. There is no need to repeat yourself > constantly. > > The only point of my post was that for those without your aversion to > installing useful tools, Dabo provides a ton of functionality. Also, as my > partner Paul McNett pointed out, I could have done it in *two* lines: > > import dabo > dabo.dApp().start() > > ;-) > > -- > > -- Ed Leafe > -- http://leafe.com > -- http://dabodev.com If you're creating a new instance of your dApp(I assume its a class) with no arguments, then effectively your just creating a default program which is already defined in the dabo module. If you could write it in a few, short lines of code by defining a new class, then you might have something there. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Program
Eric wrote: > I am reading a book on Python and ran across and exercise that I just > can't seem to figure out. Its pretty simple, but I just can't get > past a certain point. > > The task is to create a program that flips a coin 100 times and keeps > track of the total of heads and tails which is printed to the screen. > > My plan was to use import random with a range of 2 and use a > conditional statement to count to 100. The problem I am encountering > is how do I keep track of the totals for heads and tails? > > Any suggestions would be appreciated. Keep in mind I am very new to > Python so there may be a more sophisticated way, but I am just trying > to use what the book has taught so far. > > Thanks, > Eric Someone else read the same book, I suppose. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/87fcaf8ffbbd69e7/c7ff2d2b5b0d776d?q=coin+flip&rnum=3#c7ff2d2b5b0d776d -- http://mail.python.org/mailman/listinfo/python-list
Re: Fat and happy Pythonistas (was Re: Replacement for keyword 'global' good idea? ...)
the detail, knew it was going to fail. There > was no way that the Python community was going to come > up with a simple majority in favor of one proposal. None. > And it was obvious from the start. > > And the sad fact is that a proposition of the form: "We > want a conditional expression; Guido should pick the > syntax he finds the least obnoxious and get on with it" > would have passed. Overwhelmingly. > > I came across a better voting process (Condorcet) > later. Unfortunately it was later or I would have > suggested it. > > Why the jihad (and I'm using the word advisedly) > against the map, filter and reduce operators? > It seems to be completely irrational from my > viewpoint. I've seen the arguements, and they > make no sense. Map and filter are not special. Why have two ways to do the same thing? Reduce is a special case, but the arguments against map and filter are quite sensible. > > BTW, I think "large and stable" would have been less offensive than "fat > > and happy", but perhaps you meant to imply we're both lazy and complacent, > > rather than just satisfied with something that works and not inclined to > > shoot for moving targets every working day. If so, I'm not sure why you'd > > say that, since the evidence doesn't support it. > > I'm not suggesting shooting at a moving target. I'm suggesting > getting the head out of the sand, looking at trends, and figuring > out the _large_ steps to take next, not the nickle and dime fixups > that are the only things I see in PEP 3000. (Not to say that some > of them aren't going to be a lot of work. Some of them are.) > > I came back from Agile2005 last week. The open space session > on Ruby was maybe 5 times as large as the one on Python. And > both of them were kind of an afterthought. Look at the OSCon > blogs. There were a number of hardcore Python people there. > They couldn't get into Ruby sessions because they were jammed. > Standing room only. More people does not mean better. > There's a report out that the "scripting languages" in general are > losing mindshare big time in Europe, Africa and the east in general. > In fact, everywhere except in North America. I'm generally somewhat > skeptical of these reports unless I can see the methodology, but it's > definitely a data point. > > Another thing that stands out: the explicit versus dynamic typing debate > has moved on from program correctness (which is a wash) to > other areas that explicit (or derived) type information can be used > for. I see this in PyFit: the languages where explicit type information > is available by reflection have cleaner implementations. The languages > with dynamic typing all have to deal with the fact that they can't get > type information by reflection, and it's a diverse mess. > > The world is moving on, in ways that I think you're not seeing. > And Python is standing still in many of those same ways. Take another look then. -Devan L -- http://mail.python.org/mailman/listinfo/python-list
Re: Some newbie cgi form questions...
googleboy wrote: > for key in form.keys():Yes, I know which fields are hidden because I > made them that way, but I am trying to figure out a way I can iterate > over the fields and do one thing with hidden fields (assign them to > variables that tell the form how to process) and a different thing with > non hidden fields (present them back to the browser with after > emailling them on to the form owner). I want this script to work fro > several forms on the same webserver, some of which will have several > different and individual names. I am also hopeful that I may be able > to extrapolate from that ways to differentiate other things from my > form input things, but we'll see how it goes. > > My html code looks like this: > > Send Feedback > > > Subject > Your name > Your email > address. > Please let me know your thoughts below. name="thoughts" cols="64" rows="12"> > > > > > > > > In other news, I have tried suggested syntaxes aboce (thanks guys!) but > I get strange errors. If the following: > > for key in form.keys(): > if not form.keys(): > print " ERROR! " > print "Please go back and fill in all fields. All fields are > required." > > I get a traceback in teh error_log file that looks like this: > > Traceback (most recent call last): > File "cgi/form.py", line 34, in ? > for key, value in form.items(): > File "/usr/local/lib/python2.3/cgi.py", line 533, in __getattr__ > raise AttributeError, name > AttributeError: items > > if this: > > for key in form.keys(): > if not form.keys()[key]: > print " ERROR! " > print "Please go back and fill in all fields. All fields are > required." > print '' > > the I get this traceback: > > Traceback (most recent call last): > File "/var/www/users/senta/html/gobooks/cgi/form.py", line 35, in ? > if not form.keys()[key]: > TypeError: list indices must be integers > > As you can see, I am using python 2.3 (my web service provider is > responsible for this - I'd use 2.4.1 if I could) > > TIA > > googleboy >>> import cgi >>> form = cgi.FieldStorage() >>> dir(form) ['FieldStorageClass', '_FieldStorage__write', '__contains__', '__doc__', '__getattr__', '__getitem__', '__init__', '__iter__', '__len__', '__module__', '__repr__', 'bufsize', 'disposition', 'disposition_options', 'done', 'file', 'filename', 'fp', 'getfirst', 'getlist', 'getvalue', 'has_key', 'headers', 'innerboundary', 'keep_blank_values', 'keys', 'length', 'list', 'make_file', 'name', 'outerboundary', 'read_binary', 'read_lines', 'read_lines_to_eof', 'read_lines_to_outerboundary', 'read_multi', 'read_single', 'read_urlencoded', 'skip_lines', 'strict_parsing', 'type', 'type_options'] The form is not a dictionary. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with Regular Expressions
Harlin Seritt wrote: > I have been looking at the Python re module and have been trying to > make sense of a simple function that I'd like to do. However, no amount > of reading or googling has helped me with this. Forgive my > stone-headedness. I have done this with .NET and Java in the past but > damn if I can't get it done with Python for some reason. As such I am > sure it is something even simpler. > > I am trying to find some matches and have them put into a list when > processing is done. I'll use a simple example like email addresses. > > My input is the following: > wordList = ['myname1', '[EMAIL PROTECTED]', '[EMAIL PROTECTED]', > '[EMAIL PROTECTED]', '[EMAIL PROTECTED]'] > > My regular expression would be something like '[EMAIL PROTECTED]' (I realize > it could and should be more detailed but that's not the point for now). > > I would like to find out how to output the matches for this expression > of my 'wordList' into a neat list variable. How do I get this done? > > Thanks, > > Harlin Seritt You need to enclose the '\w's in parentheses. The re module will only return it if you enclose it in parentheses. Also, you need to use the '+' so that \w won't just match the first alphanumeric character, but will match one or more. You also need to escape the '.' because that's matches any character. So your regular expression would be more like r'(\w+)@(\w+)\.(\w+)' Anyways, you can use a list comprehension and the groups() method of a match object to build a list of tuples [re.match(r'(\w+)@(\w+)\.(\w+)', address).groups() for address in wordList] On a side note, some of the email addresses in your list don't work. You should use wordList = ['[EMAIL PROTECTED]', '[EMAIL PROTECTED]', '[EMAIL PROTECTED]'] -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting question
Ksenia Marasanova wrote: > Hi, > > I have a list that contains nodes from a tree. Each node is a class > instance, but I'll use dictionary here to simplify the example. > So the list looks like this: > [ > {'id': 1, > 'name': 'Parent node', > 'ord_number': 1, > 'parent_id': 0, > 'url': '/parentnode/'}, > {'id': 2, > 'name': 'My node', > 'ord_number': 1, > 'parent_id': 1, > 'url': '/parentnode/mynode/'} > ] > > Where 'ord_number' is the "sibling index". It's not always properly > filled in; sometimes it's the same for several siblings, or doesn't > starts with 1. > > I want to sort this list with the following rules: > 1. The parent must always come before the children in the list > 2. Nodes with the same parent must be sorted by 'ord_number' > > The first rule is easy, cause I can use 'url' for it. List with nodes > is coming from the database, so I just do "ORDER BY url". > The second rule is kind of tricky to do in the database. I probably > would need to do something like "ORDER BY > cut_off_lastpart_from_url(url), ord_number". But there seems to be no > native string function in Postgres to do it easily, so I desided to > sort it in Python. > > So I've come up with this: > > def cmp_tree(x, y): > if x['parent_id'] == y['parent_id']: > return cmp(x['ord_number'], y['ord_number']) > else: > return cmp(x['url'], y['url']) > > nodes.sort(cmp_tree) > > but it doesn't work as expected. Apparently I don't have a clue about > how sorting function work :( > > Can anybody help? > > -- > Ksenia class Node: def __init__(self, name, url, order, pid, id): self.name = name self.url = url self.order = order self.pid = pid self.id = id def __repr__(self): return self.url def mycmp(x,y): if x.pid == y.pid: if x.order != y.order: return cmp(x.order,y.order) return cmp(x.url,y.url) return cmp(x.pid,y.pid) a = Node('ham','/test/ham/',1,0,1) b = Node('eggs','/test/ham/eggs/',1,1,2) c = Node('bacon','/test/ham/bacon/',1,1,3) d = Node('spam','/test/ham/bacon/spam/',1,3,4) Does this work for you? I haven't tested it much. -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular expression to match a #
John Machin wrote: > Aahz wrote: > > In article <[EMAIL PROTECTED]>, > > John Machin <[EMAIL PROTECTED]> wrote: > > > >>Search for r'^something' can never be better/faster than match for > >>r'something', and with a dopey implementation of search [which Python's > >>re is NOT] it could be much worse. So please don't tell newbies to > >>search for r'^something'. > > > > > > You're somehow getting mixed up in thinking that "^" is some kind of > > "not" operator -- it's the start of line anchor in this context. > > I can't imagine where you got that idea from. > > If I change "[which Python's re is NOT]" to "[Python's re's search() is > not dopey]", does that help you? > > The point was made in a context where the OP appeared to be reading a > line at a time and parsing it, and re.compile(r'something').match() > would do the job; re.compile(r'^something').search() will do the job too > -- BECAUSE ^ means start of line anchor -- but somewhat redundantly, and > very inefficiently in the failing case with dopey implementations of > search() (which apply match() at offsets 0, 1, 2, .). I don't see much difference. Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. IDLE 1.1.1 >>> import timeit >>> t1 = timeit.Timer('re.search("^\w"," will not work")','import re') >>> t1.timeit() 34.938577109660628 >>> t2 = timeit.Timer('re.match("\w"," will not work")','import re') >>> t2.timeit() 31.381461330979164 >>> 3.0/100 3.0001e-006 >>> t1.timeit() 35.282282524734228 >>> t2.timeit() 31.403153752781463 ~4 second difference after a million times through seems to be trivial. Then again, I haven't tested it for larger patterns and strings. -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular expression to match a #
John Machin wrote: > Devan L wrote: > > John Machin wrote: > > > >>Aahz wrote: > >> > >>>In article <[EMAIL PROTECTED]>, > >>>John Machin <[EMAIL PROTECTED]> wrote: > >>> > >>> > >>>>Search for r'^something' can never be better/faster than match for > >>>>r'something', and with a dopey implementation of search [which Python's > >>>>re is NOT] it could be much worse. So please don't tell newbies to > >>>>search for r'^something'. > >>> > >>> > >>>You're somehow getting mixed up in thinking that "^" is some kind of > >>>"not" operator -- it's the start of line anchor in this context. > >> > >>I can't imagine where you got that idea from. > >> > >>If I change "[which Python's re is NOT]" to "[Python's re's search() is > >>not dopey]", does that help you? > >> > >>The point was made in a context where the OP appeared to be reading a > >>line at a time and parsing it, and re.compile(r'something').match() > >>would do the job; re.compile(r'^something').search() will do the job too > >>-- BECAUSE ^ means start of line anchor -- but somewhat redundantly, and > >>very inefficiently in the failing case with dopey implementations of > >>search() (which apply match() at offsets 0, 1, 2, .). > > > > > > I don't see much difference. > > and I didn't expect that you would -- like I wrote above: "Python's re's > search() is not dopey". Your wording makes it hard to distinguish what exactly is "dopey". -- http://mail.python.org/mailman/listinfo/python-list
Re: How do these Java concepts translate to Python?
Fausto Arinos Barbuto wrote: > Ray wrote: > > > 1. Where are the access specifiers? (public, protected, private) > > AFAIK, there is not such a thing in Python. > > ---Fausto Well, technically you can use _attribute to mangle it, but technically speaking, there are no public, protected, or private things. -- http://mail.python.org/mailman/listinfo/python-list
Re: NEWB: General purpose list iteration?
def descend(iterable): if hasattr(iterable, '__iter__'): for element in iterable: descend(element) else: do_something(iterable) This will just do_something(object) to anything that is not an iterable. Only use it if all of your nested structures are of the same depth. If you used it on the following list of lists [[something],[[something_else],[other_thing]]] it would modify something, something_else, and other_thing. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary inheritance
Talin wrote: > I want to make a dictionary that acts like a class, in other words, > supports inheritance: If you attempt to find a key that isn't present, > it searches a "base" dictionary, which in turn searches its base, and so on. > > Now, I realize its fairly trivial to code something like this using > UserDict, but given that classes and modules already have this behavior, > is there some built-in type that already does this? > > (This is for doing nested symbol tables and such.) > > --- > > Also, on a completely different subject: Has there been much discussion > about extending the use of the 'is' keyword to do type comparisons a la > C# (e.g. "if x is list:") ? > > -- Talin Dictionaries aren't classes? I wasn't aware of that. Anyways, what you're looking for, I think is a class that emulates a dictionary. Probably you should just have some attribute that references a bigger dictionary. bigger_dict = {'foo':1,'baz':2,'bar':3,'foobar':4,'foobaz':5,'foobazbar':6} smaller_dict = {'spam':1,'ham':2,'bacon':3,'eggs':4} smaller_dict.fallback = bigger_dict and then the __getitem__ method might look something like def __getitem__(self, key): if self.has_key(key): return self[key] else: return self.fallback[key] -- http://mail.python.org/mailman/listinfo/python-list