Re: Two classes problem
Hi It would help if you could describe the purpose you have in mind for doing this. There is a cute way of doing what you want: ===file: a.py=== # module a.py test = 'first' class aclass: def __init__(self, mod, value): mod.test = value# Is there another way to refer to the module this class sits in? ===end: a.py=== ===file: b.py=== # file b.py import a x = a.aclass(a,'monkey') print a.test ===end: b.py=== When you run "b.py", you will see 'monkey' printed. What we have done here is passed the reference to the *module* a to the constructor for aclass, and that constructor modified the module variable "test". This is a way to avoid using 'global', or in other words, the namespaces of things are still clear (for me anyway). Cya Caleb On Thu, 3 Feb 2005 00:13:05 +0530, Gurpreet Sachdeva <[EMAIL PROTECTED]> wrote: I have two classes; a.py --> #!/usr/bin/python global test test ='' class a(b): def __init__(self,test): print test print 'Outside: '+test b.py --> #!/usr/bin/python import a a.a('Garry') I want to pass this string (or any object later) to a.py and that too outside the scope of class a. Is that possible??? If yes, how??? Thanks, Garry -- http://mail.python.org/mailman/listinfo/python-list
Re: python and visual C++
Olivier If you consider using the ctypes module, you can write a dll (windows) or a shared object (linux) using anything that can make one of those. For example, I have successfully used FreePascal to make a dynamic library on both windows and linux and use that library within python on both platforms. Heck, even the objectpascal code for the dll was unchanged on both platforms. I simply needed to recompile the objectpascal file on each using FreePascal. Also FreePascal is available on many more platforms (though not quite as many as python, I'll wager). This is the only way I ever intend making native binary additions to my own programs. Regards Caleb On Wed, 2 Feb 2005 12:35:08 +0100, Olivier Ravard <[EMAIL PROTECTED]> wrote: Hi, When I tryed to compile a python module using distutils under windows, and there is an error message if we do not have Microsoft Visual C++ 6 installed. This is because python have been compiled with MSVC6 and distutils wants it in order to compile C++ python modules. One of the reasons why I use python is because this is a free language. But I need a non free compilator to compile my C++ module !!! Choosing MSVC to compile python is a strange choice since there are other free compilators like MinGW. I think that using another compilator should be possible in order to compile python modules since I use BOOST/MinGW to develop my own modules... Diffrerent solutions appears : - peoples who compile python for windows should use a free compilator (MinGW or Microsoft Visual C++ Toolkit 2003 for example) - modify distutils in order to use another compilator Is there anyone that have experienced this "free" problem and is there a solution that I did not note. I don't want to buy MSVC... Thanks O.R. -- http://mail.python.org/mailman/listinfo/python-list
Re: Two classes problem
Steven, thanks for your help once again :) so you could write the code like: test = 'first' class aclass: def __init__(self, value): mod = __import__(__name__) mod.test = value This is sweet. I really like this technique for manipulating module-scope identifiers (from within a class or function). To the OP: In general, this seems like a bad organization strategy for your code. What is your actual use case? Agreed. It is an interesting intellectual exercise, but there is surely a better way of controlling access to 'test' in the OP's post. thx Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic file operation questions
Hi Alex Assuming you have a file called "data.txt": *** f = open('data.txt','r') lines = f.readlines() f.close() for line in lines: print line *** Will print each line of the file. You can make a huge investment by setting 2 or 3 hours aside to go through the Python tutorial, which gets installed as part of the documentation. That tutorial can get you much of the knowledge you will ever need with Python. thx Caleb On 2 Feb 2005 13:27:49 -0800, alex <[EMAIL PROTECTED]> wrote: Hi, I am a beginner with python and here is my first question: How can I read the contents of a file using a loop or something? I open the file with file=open(filename, 'r') and what to do then? Can I use something like for xxx in file: Thanks for help Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic file operation questions
Peter Yes, you can even write f = open("data.txt") for line in f: # do stuff with line f.close() This has the additional benefit of not slurping in the entire file at once. Is there disk access on every iteration? I'm guessing yes? It shouldn't be an issue in the vast majority of cases, but I'm naturally curious :) thx Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: python and visual C++
Olivier But the problem is about modules thats are developped from others with distutils... Yes, sorry, I reread your original post and now realise that you were referring to other people's modules. And with your comments there, I agree with you -> MSVC as a requirement is unfortunate. thx Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Two classes problem
Gurpreet You can manage the namespace more formally. Or to put it another way, "global" gives me the heebie-jeebies. I recently worked on a project replacing a legacy reactor model in FORTRAN, and between COMMON blocks, and GOTO statements, I didn't know up from down. How about this: *** class a: def __init__(self,test): localtest = test # do stuff with localtest def givetest(self): return localtest def printtest(self): print localtest test = 'Starting text' print 'Outside before class: '+test my_a = a(test) test = my_a.givetest() print 'Outside after class: '+test *** So here we explicitly pass "test" into the class, do stuff with it, and rewrite test again with a method. Does this satisfy the technical problem? regards Caleb On Thu, 3 Feb 2005 11:19:34 +0530, Gurpreet Sachdeva <[EMAIL PROTECTED]> wrote: The purpose is, I pass a list to a class in a module but I want to use that list out of the scope of that class and that too not in any other class or a function but in the main program... The problem is that when I import that, the statements in the module which are not in the class are executed first and then the variable gets intiallised... I will explain with the example... -global test - -class a: -def __init__(self,test): -global test -print test - -print 'Outside: '+test I want to print that variable test which I am giving to the class as an argument, in the scope of main... I know it is not a good way of programming but my situation is like this... But is this possible or not? If I pass test as 'Garry' can I (by any way) print 'Outside: Garry' with that print statement... (in the main scope) Thanks and Regards, Garry -- http://mail.python.org/mailman/listinfo/python-list
Re: Opinions on KYLIX 3 (Delphi 4 Linux)
Hi Doug Not only was Kylix a letdown, there is talk also of it being discontinued. To be fair though, it is easy to see the difficulty for Borland to deploy a Linux IDE of the same quality as Delphi when so much in different Linux distributions is variable, the widget set being a prime example: CLX just never caught on, amongst the myriad of more mature and more open toolsets. I am assuming that you have experience with pascal, or ObjectPascal as the Delphi manuals call it (if not, why Kylix?). If so, may I suggest you look into a) fpc (Free Pascal Compiler, http://www.freepascal.org) b) Lazarus (An fpc IDE, aims to be an open-source Delphi clone, supports multiple widget sets [Win32 native on Windows!], can't remember the URL) Though python is probably my favourite language for general purpose hacking, there is a lot to be said for a native compiled language (sometimes speed _is_ an issue), and in particular there is a lot to be said for fpc: - Something like 99% Turbo Pascal compliant - Very nearly Delphi compliant (object-pascal) - (IMHO) Much cleaner language than C, still natively compiled - Supports operator overloading & inlining - Can be used to develop python extensions - Supports nearly effortless cross-compiling There are some problems with Lazarus at the moment, here is the biggie: It creates binaries of around 5MB for a minimal app, and this is because, at the moment it seems like it compiles the component library into the executable. This is somewhat of a problem for me but I expect this will change within a release or two. Lazarus is _very_ much like Delphi, and works on Windows, Linux, and possibly several other platforms. cya Caleb > and net for info about Borlands KYLIX 3 and have found little technical > info about it. Their screen shots are very impressive, similar to Visual > Basic. I have sent several emails to Borlands Sales and Pre-Sales > departments. Pre-Sales bounces and Sales won't answer. I'm sitting here > with money in hand ready to buy but not from a company that won't give me > the time of day. > > Does anyone of you have experiance with KYLIX 3 and do you think I should > consider buying it? Thank You, I'll go oil my keyboard now. > > Doug > -- http://mail.python.org/mailman/listinfo/python-list
Re: OO design
Chris > 1. get arbitrary numerical data (typically large data sets in columnar > format or even via COM from other packages. I generally have to deal with > one or more sets of X,Y data) > 2. manipulate the data (scaling, least squares fitting, means, peaks, > add/subtract one XY set from another etc) > 3. plot data (original set, results of manipulation, scatterplot, > histograms > etc - I use matplotlib) Matplotlib is really coming on. I still use gnuplot out of familiarity (and features, to be sure) but one of these days I'm going to spend a bit of time on Matplotlib. > 4. export data (print, csv, shelve) I do very much the same kind of work with python. I write mostly in Delphi at work, but for processing stuff like this, I always use python when the dataset is not too big and the processing of the data is not too expensive. Despite the awesome Delphi IDE, python with a text editor is *still* more productive (for *me*) in jobs like this. > I have no problem writing bits of functional code to do any of the above. > But for the life of me I can't see how I can hook them altogether in an > OO > based framework that I can build and extend (with more data formats, > manipulations, GUI etc). To be honest, I am probably a poor source of advice here because I think I tend to overuse the class paradigm when often a more sensible approach would be a top-down strategy. I just tend to think in terms of objects, for better or worse. At least python's class declarations are not expensive in terms of setting up, so I tell myself it's ok. Lets look at what you suggested: > class XY: > def read_file > def scale_data > def plot_data > def shelve_data This is exactly the kind of thing I do as well, but maybe separate the dataset from the processing (and put the classes into separate files, if you prefer - I find the "one class per file" idea easier to manage in my editor , Vim) class XYpoint(object): def __init__(self,x=0,y=0): self.x = x self.y = y class Dataset(object): def __init__(self): self.data = [] # Will be a list of XYpoint objects - probably filled in with Gather? def Gather(self,source): pass # You fill this in, using source as you prefer def Scale(self,factorX,factorY): # Filled out with example implementation below for i in range(len(self.data)): self.data[i].x = self.data[i].x * factorX self.data[i].y = self.data[i].y * factorY def Plot(self): pass # Do what you gotta do def Shelve(self): pass # Do what you gotta do class MultipleDatasets(object): def __init__(self): self.datasets = [] # Will be a list of dataset objects, which you must populate def PlotAll(self): for i in self.datasets: i.Plot # How to plot all your datasets, for example [FWIW - This is how I write all my python programs - very very naively and simply. I just cannot remember all the fancy things enough to use when I need to get something done. This is the kind of simple syntax that lured me to python in the first place, and I have a disconcerting feeling about all the "advanced" features for "master" programmers creeping into the language lately, or at least getting discussed - I don't think I am smart enough to absorb it all - CS isn't my area] > But somehow that doesn't feel right, especially when I expect the number > of > methods will grow and grow, which would make the class very unwieldy. I would be interested to know if you think what I wrote "feels" right to you or not - It certainly feels "right" to me, but then that is hardly surprising. In any case, what I presented almost exactly fits how I "think" about the problem, and that is what I want. > bwaha. ? regards Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding # prefixing numbers
You really owe it to yourself to try the PyParsing package, if you have to do this kind of thing with any frequency. The syntactic difference between PyParsing and regular expressions is greater than the syntactic difference between Python and C. thx Caleb On Tue, 19 Jul 2005 13:35:02 +0200, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > In a text that contains references to numbers like this: #583 I want to > find them with a regular expression but I'm having problems with the > hash. Hopefully this code explains where I'm stuck: > import re re.compile(r'\b(\d\d\d)\b').findall('#123 x (#234) or:#456 #6789') > ['123', '234', '456'] re.compile(r'\b(X\d\d\d)\b').findall('X123 x (X234) or:X456 X6789') > ['X123', 'X234', 'X456'] re.compile(r'\b(#\d\d\d)\b').findall('#123 x (#234) or:#456 #6789') > [] re.compile(r'\b(\#\d\d\d)\b').findall('#123 x (#234) or:#456 #6789') > [] > > As you can guess, I'm trying to find a hash followed by 3 digits word > bounded. As in the example above, it wouldn't have been a problem if > the prefix was an 'X' but that's not the case here. > -- http://mail.python.org/mailman/listinfo/python-list
Re: is this pythonic?
Wow, I didn't know about enumerate. Many thanks Caleb On Wed, 20 Jul 2005 15:19:50 +0200, Simon Brunning <[EMAIL PROTECTED]> wrote: > On 7/20/05, Mage <[EMAIL PROTECTED]> wrote: >> Or is there better way? >> >> for (i, url) in [(i,links[i]) for i in range(len(links))]: > > for i, url in enumerate(links): > -- http://mail.python.org/mailman/listinfo/python-list
Re: is this pythonic?
Terry Yes, I must agree with you that it is something I should know. I do try to keep with things but there are always some things that slip through the cracks, like enumerate, in this case. That is why I am extremely grateful the for the activity, generosity and pure knowledge on this newsgroup to fill in the blanks for me. It is guys like you who are willing to take the time to give responses that make it what it is. In another newsgroup, I could have been flamed for letting Simon know he helped more than just the OP with his post :) Thanks Caleb On Wed, 20 Jul 2005 23:41:36 +0200, Terry Reedy <[EMAIL PROTECTED]> wrote: > >> Wow, I didn't know about enumerate. > > It is listed and explained in Lib Ref Manual, Chapter 2, on builtin > functions and types and their methods. Everyone should read at least > that > much of the Lib manual. > > Terry J. Reedy > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI - Windows: Where to get started
Probably, the best place for learning how to build GUI's for Windows, in general, is to get hold the personal edition of Delphi from the Borland website. If you want something more specific to Python, it is likely to be much tougher. You would, for example, have to decide which widget toolkit you want to use. Also, you would have to decide if you want to do GUI-building via text-files or through a graphical method. The simplest method (for the latter) I have seen so far is Glade, but perhaps other posters will have better advice than me. rgds Caleb On Tue, 26 Jul 2005 21:44:13 +0200, Ernesto <[EMAIL PROTECTED]> wrote: > Hi all, > > Would anyone know a good place to start for learning how to build > simple GUI's in Windows XP? I just want users to be able to select a > few parameters from a pull-down menu, then be able to run some batch > files using the parameters from the pull down menus. I would also need > a "Browse" menu, so users could point to a place on the local disc (ie > C:\PointSystemHere). Can anyone give a noob some tips? THANKS!!! > -- http://mail.python.org/mailman/listinfo/python-list
Re: Emacs skeletons
> Since you are on this topic, do you (or anyone else) have any type of > "code-completion" mode for python in emacs? > > Thanks > -george For what its worth, Vim has a generic type of "code-completion" that uses the file being edited to check for completion options within a word. It's not true completion (using valid completions for class hierarchies, a la Delphi/VB), but I get a lot of mileage out of it with my python coding. I fully expect Emacs has something similar, though I can't tell you how (I hardly know emacs at all). rgds Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this Pythonic?
Peter To my mind, this kind of setup (interface class, or abstact class) is more usually used in static languages to benefit polymorphism - but python is dynamically typed, so in which situations would this setup be useful in a python program? You see, I expected your post to say that it wouldn't even be necessary, but you didn't :) I have spent a little effort training myself not to bother setting up class hierarchies like this in python, due to the fact that I use Delphi a lot at work (I do pretty much the code below to let myself know when an inherited/abstract class method is being called in error). regards Caleb On Mon, 01 Aug 2005 18:52:02 +0200, Peter Hansen <[EMAIL PROTECTED]> wrote: > phil hunt wrote: >> Suppose I'm writing an abstract superclass which will have some >> concrete subclasses. I want to signal in my code that the subclasses >> will implement certan methods. Is this a Pythonic way of doing what I >> have in mind: >> class Foo: # abstract superclass >>def bar(self): >> raise Exception, "Implemented by subclass" >>def baz(self): >> raise Exception, "Implemented by subclass" > > Change those to "raise NotImplementedError('blah')" instead and you'll > be taking the more idiomatic approach. > > -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Python IDE's
You know, for several years I was one of those people who simply ignored posts like this about Vi/Vim because I happened to come across it once on a sparc machine and thought it was ridiculous that I couldn't figure out how to type a simple note. I thought that Vi (Vim) was some kind of weird and ancient legacy program that just never caught up with the times. About 3 or 4 months ago, I had a truly large amount of ascii text editing and formatting to do and in a plea for advice, I got the standard cliche replies to try "Vim". Having nothing to lose, I gave it a shot. It took only about two weeks before I was competent, but it was probably the greatest time investment I have ever made. I now use Vim for any text editing purpose, and especially python coding. No doubt, the majority of people who read your post will instantly ignore it - but I know from personal experience that it would take a very special IDE to compete with Vim for the manipulation of text (GUI design, of course, is another story altogether). regards Caleb On Mon, 01 Aug 2005 18:57:51 +0200, projecktzero <[EMAIL PROTECTED]> wrote: > VIM or Emacs. I use VIM on Windows, Mac, and VMS. I'd consider it more > of an editor than an IDE, but there are many IDE features available > with plug ins. > -- http://mail.python.org/mailman/listinfo/python-list
Re: very high-level IO functions?
York Short answer: yes We use python and R at work, and in general you will find python syntax a little cleaner for functionality they have in common. R is better for some of the more hard-wired stats stuff, though. On Mon, 19 Sep 2005 20:04:37 +0200, York <[EMAIL PROTECTED]> wrote: > Hi, > > R language has very high-level IO functions, its read.table can read a > total .csv file and recogonize the types of each column. write.table can > do the reverse. > > R's MySQL interface has high-level functions, too, e.g. dbWriteTable can >automatically build a MySQL table and write a table of R data > into it. > > Is there any python packages do similar things? > > > -York -- http://mail.python.org/mailman/listinfo/python-list
Re: p2exe using wine/cxoffice
The other thing (and this is always true) is that "better" needs definition. On purely technical grounds, on average, MSOffice is better than OO. However, holistically, OO is probably better (no lock-in, open standards, multiplatform and so on). Those soft issues do matter. On Mon, 19 Sep 2005 12:18:55 +0200, Christophe <[EMAIL PROTECTED]> wrote: > Tim Roberts a écrit : >> James Stroud <[EMAIL PROTECTED]> wrote: >> >>> I think the motivation is to ween people off of M$ products altogether, >> Well, CrossOver Office doesn't really do that. You're still running >> Microsoft Office. >> >>> ...to get them used to working an a unix environment and to the idea >>> of using open alternatives rather than thinking that commercial >>> software is somehow "better". >> Regardless of your opinion on their operating systems, only a >> religious >> zealot would try to argue that Microsoft Office is not better than any >> of >> the open source alternatives. > > Some significant parts of Microsoft Office are worse than what you get > in OO.o Mainly, you could easily argue that OOWriter is better than > Word. I wouldn't try to make the same claim for the other parts of OO.o > though :) -- http://mail.python.org/mailman/listinfo/python-list
mathschallenge.net WAS Brute force sudoku cracker
Very interesting that sudoku solving appears on the python group - there is a programming competition at mathschallenge.net (euler) where one of the puzzles is developing a sudoku solving algorithm... Actually the python entrants are giving the C guys a good run! On Mon, 19 Sep 2005 09:12:54 +0200, Antoon Pardon <[EMAIL PROTECTED]> wrote: > Op 2005-09-16, [EMAIL PROTECTED] schreef > <[EMAIL PROTECTED]>: >> >> Bas ha escrito: >> >>> Hi group, >>> >>> I came across some of these online sudoku games and thought after >>> playing a game or two that I'd better waste my time writing a solver >>> than play the game itself any longer. I managed to write a pretty dumb >>> brute force solver that can at least solve the easy cases pretty fast. >>> >>> It basically works by listing all 9 possible numbers for all 81 fields >>> and keeps on striking out possibilities until it is done. >>> [snip] >> >> This problem is desperately begging for backtracking. > > I don't think so. I regularly solve one and I never needed > to try something out, to see if it worked or not except > when there were muliple solutions. > > I think it is a beautifull problem, to make people think of > how they could code some of their thought processes, which > would be a more fruitfull experience as programming this > with backtracking. > -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie wants to compile python list of filenames in selected directories
Hi Anthony Here is some stuff to get you started (this is from memory, I'm not checking it, but should be mostly helpful): *** import os os.chdir('C:\My Documents') # Can use this to jump around to different folders fileNames = os.listdir('.') # Checks the now current folder namesToMatch = ['readme.txt','readme.doc'] # Buncha names to find for item in fileNames: # check every filename if item in namesToMatch: # is this item in the required list? print 'Match found: '+item # if you found one, say so. *** Hope this helps. Caleb On Sun, 06 Feb 2005 18:29:34 +, anthonyberet <[EMAIL PROTECTED]> wrote: Hi, I am new at Python, and very rusty at the one language I was good at, which was BASIC. I want to write a script to compare filenames in chosen directories, on windows machines. Ideally it would compose a list of strings of all the filenames in the directories, and those directories would be chosable by the user of the script. I am quite happy to do my own legwork on this , I realise it is simple stuff, but can anyone point me in the right direction to start? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: loops -> list/generator comprehensions
I would be interested to see an example of code that is more concise but yet as *clear* as the one you already have. I can actually read and understand what you've got there. That's cool :) On 6 Feb 2005 11:28:37 -0800, <[EMAIL PROTECTED]> wrote: I wrote this little piece of code to get a list of relative paths of all files in or below the current directory (*NIX): walkList = [(x[0], x[2]) for x in os.walk(".")] filenames = [] for dir, files in walkList: filenames.extend(["/".join([dir, f]) for f in files]) It works fine, I don't need to change it, but I know there is a one liner list/generator comprehension to do this - I'm just not well enough versed in comprehensions to figure it out. Can someone please show me what it is? Even better, is there a generalized way to transform simple loops into comprehensions that someone can point me to? james -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple constructors
Hi Philip C++ to Python is a steep 'unlearning' curve... That's worthy of QOTW. I decided not to reply to this thread earlier, but you just convinced me otherwise :) I work in Delphi a lot, which is in a lot of respects very similar to C. I have come to the conclusion that function overloading was introduced to allow the same calling syntax and even functionality to be applied to different *types*. This is a consequence of the fact that in Delphi and C, for example, typing is static. In a dynamic language like python, however, overloading isn't necessary. Not only can the *type* of a function argument be determined at run-time, the *number* of arguments can as well. Though Alex indicated differently earlier, I intend to always use an "if" statment inside one constructor to initialise any class in the situation where the arguments may be different in number and type. I don't have the years of experience that Alex has, however, so I may end up regretting it but right now, it seems to me to be the clearest approach in this situation. thx Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Python versus Perl ?
Hi Surfunbear I don't know about the stuff regarding jobs, resumes, etc, but I will tell you the same thing I tell everyone I meet regarding python: Set aside a morning, and work through the python tutorial that comes with the documentation. People like me are going to tell you this and that, perhaps try to convince of our particular world-view, and so on. By the end of the tutorial (more likely at halfway) you will probably know whether this is worth pursuing or not. Oh, and do this before you invest too much time in Perl :) Keep well Caleb On 6 Feb 2005 05:19:09 -0800, <[EMAIL PROTECTED]> wrote: I've read some posts on Perl versus Python and studied a bit of my Python book. I'm a software engineer, familiar with C++ objected oriented development, but have been using Perl because it is great for pattern matching, text processing, and automated testing. Our company is really fixated on risk managnemt and the only way I can do enough testing without working overtime (which some people have ended up doing) is by automating my testing. That's what got me started on Perl. I've read that many people prefer Python and that it is better than Perl. However, I want to ask a few other questions. 1. Perl seems to have alot of packaged utilities available through CPAN, the comprehensive perl network. These can aid in building parsers, web development, perl DBI is heavily used. This seems to be a very important benifit. I'm not sure that Python is as extenive at all in that regard ? Perl also has excellent pattern matching compared to sed, not sure about how Python measures up, but this seems to make perl ideally suited to text processing. 2. Python is apparantly better at object oriented. Perl has some kind of name spacing, I have used that in a limited way. Does Perl use a cheap and less than optimal Object oriented approach ? That was what someone at work said, he advocates Python. Is it likely that Perl will improve it's object oriented features in the next few years ? 3. Perl is installed on our system and alot of other systems. You don't have to make sys admins go out of there way to make it available. It's usualy allready there. I also did a search of job postings on a popular website. 108 jobs where listed that require knowledge of Perl, only 17 listed required Python. Becomeing more familiar with Perl might then be usefull for ones resume ? If Python is better than Perl, I'm curious how really significant those advantages are ? -- http://mail.python.org/mailman/listinfo/python-list
Re: loops -> list/generator comprehensions
Sure Steve Lemme see ... (indentation changed so comments associate with correct bits) Out of curiosity, do you find: filenames = [os.path.join(dirpath, filename) # This is cool for dirpath, _, filenames in os.walk('.') # This is getting tricky, whats the '_' for? Which thing goes where again in a comprehension? for filename in filenames] # The hierarchy has nailed me by this point. I will have to start over... Yes, yes I do find it more difficult to read. Maybe I just don't know python as well as I should (certainly not as well as others here!). I guess it is just familiarity. A single comprehension is ok, nesting them gets tricky, and 3 times is a strike for me. I will practise :) keep well Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: loops -> list/generator comprehensions
Wow, Steve, thanks, you went to some effort here. I prefer to give names to the values produced by os.walk -- I think it makes the usage much clearer. However, since I don't use 'dirnames', I use '_' to indicate this: Actually, I feel silly for not recognising this - I read about the Python3 suggestion for adding a "with" syntax, and the suggestion was rather to use something like _ = instname _.a = 1 _.b = 2 So I actually have seen this "_" placeholder before :) Sorry bout that. Would filenames = [os.path.join(dirpath, filename) for dirpath, dirnames, filenames in os.walk('.') for filename in filenames] have been clearer for you? Then all you have to do is remember the order of the for-loop execution: Bizarre as this may sound, it was the '_' that was throwing me off the whole thing (at the 'grok' level I generally read the newsgroup, anyway). For some weird reason, I can read *this* comprehension pretty easily! Does that make sense at all? I figure a little bit of uncertainty along the way probably derails understanding of the whole thing a little bit - and (mental note) I *must* remember this when I explain stuff to people at work, having now experienced it first hand. Thanks again Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple constructors
Sure, Nick, I agree with you completely. I generally try to make sure that my classes are limited in what they do/provide, so it is not often a problem that a class may need to be instantiated in several very different ways. But your point is well taken. Thanks Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic file operation questions
Peter, that was very clear, thanks. > So not only is > > for line in file(...): ># do stuff > > the most elegant, it is also the fastest. file.readlines() comes close, but > is only viable for "small" files. -- http://mail.python.org/mailman/listinfo/python-list
Pypy - Which C modules still need converting to py?
Hi all I saw it on a webpage a few days ago, can't seem to find it again. Tried a google search for "pypy needed translate C modules" but that didn't turn up what I was looking for. Anyone have that page ref handy listing the C modules that the pypy team need translated into python? thanks Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Python versus Perl ?
Hi m Speed is a contentious issue here. Point is, if you really need raw speed, why stop only at Perl and Python? There are plenty of statically compiled languages that will produce native binaries. The relative difference in speed between Perl and Python, whatever it is, is completely washed out by the enormous jump using, say, C for example [please, everyone else, I am aware of all the mitigating circumstances regarding, e.g. parts of the standard library written in C, etc. That is not my point.] A Good Reason for thinking along these lines (Perl/Python) is more something like speed and reliability of development. Another one is maintaintability. I must confess that I know pretty much nothing about Perl, so I can't comment about that. My opinion about Python is that it is very, very good for these things. The problem domains in which I do most of my work (chemical process modelling and simulation) really do require speed. That's why I mostly use Delphi (i.e. reasonably fast code) at work. I believe I know when speed is and is not an issue, and (by far) most of the time, my experience is that it is *not*. So I use Delphi for numerical code and python for everything else. You really will have to convince people here that execution speed is a real issue for your programming task (in order to continue this discussion). Otherwise the debate will go south real quick. Keep well Caleb On Tue, 08 Feb 2005 12:17:05 -0600, m <[EMAIL PROTECTED]> wrote: Courageous wrote: If Python is better than Perl, I'm curious how really significant those advantages are ? speedwise, i think perl is faster than python and python performed the slowest as shown in http://www.flat222.org/mac/bench/ -- http://mail.python.org/mailman/listinfo/python-list
Re: python code with indention
is it possible to write python code without any indentation? Xah You can, of course, write a silly little inline script without any control structures that will all line up at the left margain. So what? John Roth I agree, John, I don't get it. The vast majority of programmers (albiet from my limited perspective) indent their code anyway, whether required by the language or not. This was one of the first features of Python I learned about that made me sit up and take notice -- here was a truly pragmatic design choice that actually benefitted the programmer (by not having to type all those delimiters). Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Loop in list.
Jim Someone on this list (SteveB) helped me quite a bit with a list comprehension on a recent thread. Roy said it can be hard to read, and I agree in part because I always thought they were hard to read, when in actual fact I had just never bothered to learn properly. Here is a mini-tutorial: e.g. 1: The theory '>>> a = [ for i in ] item2 is iterable (like "range()" in your example) item1 is the thing that is going to fill up the resulting list, and item1 is evaluated at each step of the "for" loop. This is the same as '>>> a = [] '>>> for i in : '>>> a.append() e.g. 2: A real example '>>> a = [i*2 for i in range(3)] '>>> a [0, 2, 4] so "i*2" gets evaluated for each step in the "for" loop. The values of "i" at each step are [0,1,2], according to how "range" works, so "i*2" is what you end up with in the resulting list. e.g. 3: They can be nested '>>> a = [i*2*b for i in range(3) for b in range(4)] '>>> a [0, 0, 0, 0, 0, 2, 4, 6, 0, 4, 8, 12] Might take you a while to correlate the answer with the loop, but you should be able to see after a while that this nesting is the same as '>>> a = [] '>>> for b in range(4): '>>> for i in range(3): '>>> a.append(i*2*b) keep well Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Choosing the right parser for parsing C headers
Jean, Paddy I use "pym" to extract bits of pascal out of delphi code for documentation purposes. You have to add some stuff to the delphi code (in your case, C header), but these are added within comment blocks, and the interesting thing is that you add python code(!) as a kind of dynamic markup which pym executes while parsing the file. In other words, you can write python code within a comment block in your C-header to generate unit-tests into other files, and get that code executed with pym. Keep well Caleb On Tue, 08 Feb 2005 19:58:33 GMT, Paddy McCarthy <[EMAIL PROTECTED]> wrote: Jean de Largentaye wrote: Hi, I need to parse a subset of C (a header file), and generate some unit tests for the functions listed in it. I thus need to parse the code, then rewrite function calls with wrong parameters. What I call "shaking the broken tree" :) I chose to make my UT-generator in Python 2.4. However, I am now encountering problems in choosing the right parser for the job. I struggle in choosing between the inappropriate, the out-of-date, the alpha, or the too-big-for-the task... Why not see if the output from a tags file generator such as ctags or etags will do what you want. I often find that some simpler tools do 95% of the work and it is easier to treat the other five percent as broken-input. try http://ctags.sourceforge.net/ - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic file operation questions
Marc I don't know how it is handled, but I expect also that there is an implied close(). thanks Caleb When you read a file with that method, is there an implied close() call on the file? I assume there is, but how is that handled? -- http://mail.python.org/mailman/listinfo/python-list
Re: variable declaration
Alexander PowerOfGenerator=TakeFromSensor() if PowerOfGenerator>xxx: RecalcPower(PowerOfGenerator) PutToTheDatabase(PowerOfGenerator) Here, python will not help you. The worst thing is that in such calculations you often receive plausible results. (I think PyChecker has come up before, but...) If you like, you could make a text-file index of all the variable names allowed in your program, and parse all the python code to ensure that only those variable names are used. I believe this would a) solve your problem b) require less than a morning's work c) not force everyone else to have to deal with variable declarations that will be only an annoyance 95% percent of the time. Is there a specific reason you want this added to the *language* itself? Thanks Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Loop in list.
Stephen You're gonna have to help me here.what is the effective difference? Thanks Caleb '>>> a = [] '>>> for b in range(4): '>>> for i in range(3): '>>> a.append(i*2*b) There is a subtle error in this explanation. The equivilence actually looks like: '> a = [] '> l1 = range(4) '> l2 = range(3) '> for b in l1: '> for i in l2: '> a.append(i*2*b) Stephen -- http://mail.python.org/mailman/listinfo/python-list
Re: variable declaration
Jeff I fully agree. As I stated in a message to alexander, it is quick and easy even to write a simple project-specific tool for checking that only allowed variable names exist in all the project files. Compared to having to work with tons of effectively useless variable declarations forever (perhaps even only in other peoples code who decided to use the "option"), it is not much to ask (I work in pascal a lot - I know all about tons and tons of declarations). thx Caleb You can also get all places where said variable exists by using grep, or your editor's search feature. I don't see how a var declaration gains you anything over 'grep PowerOfGenerator *.py' ... Jeff Shannon Technician/Programmer Credit International -- http://mail.python.org/mailman/listinfo/python-list
Re: Python versus Perl ?
Hi Adam Thanks for your comments. > I think the expression you seek is "comparing virtue among whores." Sure, that's what I was saying, but not quite in as colourfil a manner :) > > > > The problem domains in which I do most of my work (chemical process > > modelling and simulation) really do require speed. That's why I mostly > > use Delphi (i.e. reasonably fast code) at work. I believe I know when > > speed is and is not an issue, and (by far) most of the time, my experience > > is that it is *not*. So I use Delphi for numerical code and python for > > everything else. > > Why don't you use C for the numerical work? Then you can do your number > crunching within a c-based python module. Have your cake and ... As you might imagine, I think about this constantly. However, there are many other issues that make it complicated, such as having to work in a team where the average guy knows pascal well (we're just a bunch of chemical engineers), but has never even heard of python. Plus, were I to go this type of route, I would almost definitely code the binary modules in Delphi or FreePascal, make a DLL and use ctypes to call it. I do not know C and have no desire to learn now :)On the other hand, I know pascal quite well. keep well Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Loop in list.
Hi Fredrik *sigh* I think I will stop writing mini-tutorials :) You are, of course, correct. And I really like your method of explaining how to mentally juggle the LC into explicit loops. I shudder to think how mnay people I confused with my incorrect examples - I really should have tested them first. Thanks again Caleb > (to translate a list comprehension to nested statements, remove > the result expression, insert colons and newlines between the for/if > statement parts, and put the append(result expression) part inside > the innermost statement) > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python versus Perl ?
Joe, thanks Yes, I am on the P4D mailing list :) What you didn't say was that the "python for delphi" extensions are *awesome*. full two-way communication, and you get it all by drag&dropping a little component widget onto your form in the IDE. Amazing. However... Dll's can be used by things other than python, which is the main reason why we would go that route. However, with all the .NET hoopla, maybe IronPython and a .NET dll would be the way to go in the future. I'm still a little uneasy about adopting .NET as a standard just yet... I should give it some more thought anyways. Thanks again Caleb On Wed, 09 Feb 2005 12:38:37 -0500, Joe Francia <[EMAIL PROTECTED]> wrote: Caleb Hattingh wrote: As you might imagine, I think about this constantly. However, there are many other issues that make it complicated, such as having to work in a team where the average guy knows pascal well (we're just a bunch of chemical engineers), but has never even heard of python. Plus, were I to go this type of route, I would almost definitely code the binary modules in Delphi or FreePascal, make a DLL and use ctypes to call it. I do not know C and have no desire to learn now :)On the other hand, I know pascal quite well. keep well Caleb You could always code Python extensions directly in Delphi: http://membres.lycos.fr/marat/delphi/python.htm http://www.atug.com/andypatterns/PythonDelphiLatest.htm Demo09 (look in demodll.dpr & module.pas) in the download tells you how. Peace, Joe -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and version control
Carl What is the ultimate version control tool for Python if you are working in a Windows environment? We use JEDI VCS (open source, free). To be fair, JEDI VCS actually integrates into the Delphi IDE, which is what we use mostly. However, the standard installation also installs a standalone client (as opposed to the IDE client) that you can use for anything. Actually, we use the standalone client for latex documentation, so I know it works well for non-Delphi stuff. The JEDI VCS server download (now) contains an embedded firebird database, which makes setting up the whole server thing a total breeze. I just did it a few days ago, took all of 2 minutes to set up the server and start the service (and send a mail out to everyone asking them to install the new client). Firebird is based on Interbase, if that means anything to you. You get full access controls (check-in/check-out), version history, rollbacks, milestones, integrated diff, check-in requests, per-file check-in/check-out comments, automated database backup, and so on. I cannot recommend it highly enough actually :) Though we use it all the time, we hardly think about it much, which is a really great feature for this type of thing. Of course, I have only used JEDI VCS, so I have nothing to compare it to: ymmv. keep well Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python as capable as Perl for sysadmin work?
Roy How about the Yoda version: do: statement do not do: statement The Yoda version actually goes statement :do statement :not do Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: SWIG or SIP?
Brent Google "python ctypes". ctypes is cool :) keep well Caleb On Wed, 9 Feb 2005 13:44:44 -0700, Brent W. Hughes <[EMAIL PROTECTED]> wrote: I have a third-party DLL and it's associated .h file. The DLL was written in C. I have neither the associated .c files nor the .obj files for the DLL. Can I use SWIG or SIP to build something that will allow me to use the DLL with Python? And what is that something, an .obj file, another DLL or what? Brent -- http://mail.python.org/mailman/listinfo/python-list
Re: some qustions on python
http://www.python.org On Tue, 15 Feb 2005 13:16:53 -0500, samar bazied <[EMAIL PROTECTED]> wrote: Hi.. plz can u help me?? I am very new in python and I have some qustions about it. can u give me design process of python and their related langauges? and I will be very habby if u give me small evaluation of python>> plz.. plz... plz help me.. -- http://mail.python.org/mailman/listinfo/python-list
Re: python open source charting solutions ?
I have had good success with pygnuplot. On Tue, 8 Mar 2005 20:45:22 +0200, ionel <[EMAIL PROTECTED]> wrote: i need some pointers. so far i've tryed matplotlib ... -- http://mail.python.org/mailman/listinfo/python-list
PIL 1.1.4 paste PNG's with transparency problem
Here's hoping effbot is around :) I have a really simple situation where I have 2 png images, and open them so: '>>> iconBallImage = Image.open('sampleTextures/iconBall.png').resize(DimensionSize) '>>> iconShieldImage = Image.open('sampleTextures/iconShield.png').resize(DimensionSize) The 2nd image has an alpha channel with transparency. The first one also has an alpha channel, but is fully opaque. Then I paste the second image into the first image: '>>> iconBallImage.paste(iconShieldImage, (10,10)) Then I save: '>>> iconBallImage.save('sampleTextures/output.png') When I view "output.png" in the Gimp, I see that the transparent bits in the second image appear as a grey-crosshatching pattern. There is an alpha channel in the new image, but I expected to see that bits of the original first image would peer through the transparent bits of the original second image. I fully expect I am doing something wrong here, I just don't know what. Thanks Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: slicing, mapping types, ellipsis etc.
I'm going to assume the following is self-explanatory - type the commands in yourself. '>>> a = 'hello my name is caleb' '>>> b = a.split() '>>> b ['hello', 'my', 'name', 'is', 'caleb'] '>>> b[0] 'hello' '>>> b[1] 'my' '>>> b[0:1] ['hello'] '>>> b[0:2] ['hello', 'my'] '>>> b[-1] 'caleb' '>>> b[:-2] ['hello', 'my', 'name'] '>>> b[2:-2] ['name'] '>>> thx Caleb On 29 Nov 2004 15:49:30 -0500, Jerry Sievers <[EMAIL PROTECTED]> wrote: Slice objects Slice objects are used to represent slices when extended slice syntax is used. This is a slice using two colons, or multiple slices or ellipses separated by commas, e.g., a[i:j:step], a[i:j, k:l], or a[..., i:j]. They are also created by the built-in slice() function. A quick example on how this is used and/or pointer to more reading is greatly appreciated. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: asynchat and threading
I heartily support something like this, but alas I have not the time to help out with it. I like the Enthought python distribution because it installs several packages in one shot. A pity there isn't a similar thing for python addons in Linux (or is there?). Something apt-get-like would be cool. Was there talk of having the python package index support something like this at some stage? If I could simply do: py-get twisted and have all of the dependencies resolved, it would be wonderful. as a prototype, I would suggest wrapping apt-get with a python envelope which automatically invokes apt-get with a python specific configuration file for .pydeb files as well as a private repository and database etc.. Since apt-get exists for almost every version of Linux and should be portable to other platforms, this distribution method should be relatively distribution portable. One can also handle upgrades of the core image of Python and ancillary packages as well by leaving a breadcrumb file indicating which packaging system is native and the package currently installed. <<- idea needs work yea? nay? ---eric -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL 1.1.4 paste PNG's with transparency problem
Wow, that was pretty clueless of me...right there on the *next* page of the manual (I thought "im.paste(image, box)" and "im.paste(image, color)" were the general forms for "paste", apparently didn't look further) thx Caleb On 29 Nov 2004 22:17:36 -0800, Tom Hanks <[EMAIL PROTECTED]> wrote: "Caleb Hattingh" <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>... >>> iconBallImage.paste(iconShieldImage, (10,10)) iconBallImage.paste(iconShieldImage, (10,10), iconShieldImage) ^^^ transparency as 3rd parameter TTFN Tom. -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL interpolation access
Hi I can't help you directly, but I am also finding im.putpixel to be extremely slow - as the docs recommend, can you try using the pixel-placing method of Draw? This is what I am going to try for my application (resampling algorithms). Thx Caleb On 30 Nov 2004 11:18:40 -0800, irond_will <[EMAIL PROTECTED]> wrote: Does anyone know how I might directly access PIL's bicubic interpolator? I have an arbitrary array of points for which I need to find interpolated color values. Unfortunately, I have no clue how to acceess the bicubic filter in the PIL module, and my NumArray solution is very slow and clunky. I've hacked together a very very very slow solution that involves the following steps: 1) import Image 2) translate Image to NumArray object (fairly slow) 3) find interpolated values for pixel array (breathtakingly slow) 4) translate interpolated color values (NumArray) into Image structure (way too slow) If anyone knows any way to perform items 2,3 or 4 with any facility, please please please respond. The code I have now is extremely clunky, largely due to my lack of facility with Python, Numarray and PIL. Some is below: I know I could speed up the algorithm by being smarter with vectors. I don't really want to mess with this, though, if there's already a better extant solution. Thanks, -Wm. def bicub_interp(r,X): from numarray import * import Image #r is the 2d array point in X space; this should be generalized to take in an array of size [2,xspan,yspan] #X is the graphic array. Its specifications are: # dim 1 = x axis # dim 2 = y axis # dim 3 = [RGB] axis # Each pixel of the X array is assumed to exist at the discrete intersection of integer count. # For instance, the bottom left point is X[0,0,:] c_r_x = r.shape[1] c_r_y = r.shape[2] c_X_x = X.shape[0] c_X_y = X.shape[1] Y = zeros((c_r_x, c_r_y, 3)) for n_x in range(c_r_x): for n_y in range(c_r_y): r_x = r[0,n_x,n_y] r_y = r[1,n_x,n_y] r_i = int(r_x) r_j = int(r_y) r_dx = r_x - r_i r_dy = r_y - r_y if ( (0 < r_i < (c_X_x-2)) & (0 < r_j < (c_X_y-2)) ): for n_m in range(-1,3): for n_n in range(-1,3): Y[n_x,n_y,:] += (X[r_i,r_j,:] * Rfunc(n_m - r_dx) * Rfunc(r_dy - n_n)) return Y def Rfunc(X): ##For use in bicub_interp() R = (1.0/6.0)*(1.0 * ((ramp(X+2.0))**3) - 4.0 * ((ramp(X+1.0))**3) + 6.0 * ((ramp(X))**3) - 4.0 * ((ramp(X-1.0))**3)) return R def ramp(X): if (X<0): X = 0.0 return X def image_to_array(im): #This function returns an array of RGB pixel values #The dimensions correspond as follows: #Dim 1 = column or x value #Dim 2 = row or y value #Dim 3 = color value or [R,G,B] for [0, 1, 2] #X.transpose operations can change the order of the axes if desired. X = vect_math.array_flip(transpose(reshape(array(im.getdata()),(im.size[1],im.size[0],3)),(1,0,2)),1) return X def array_to_image(X): #SLOW method of mapping array of spects defined in image_to_array into #an image structure #There is probably a faster way using im.putdata(), but I can't figure out how to get the array structure #oriented in such a fashion as to perform a direct put. im = Image.new('RGB',(X.shape[0], X.shape[1])) X=vect_math.array_flip(X,1) for x in range(0,X.shape[0]): for y in range(0,X.shape[1]): im.putpixel((x,y),tuple(X[x,y,:])) return im -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression Problem...
Obviously, Peter and Jorge are hardcore, but below is what a beginner like me hacked up: My point, I guess, is that it is possible to quickly get a solution to a specific problem like this without being a total expert. The code below was typed out once, and with only one minor correction before it produced the required behaviour. Sure, it is not the general solution, but *this is WHY I use python* - You get a lot of mileage out of the basics. Plus, I can still read and understand the sub-optimal code, and probably will be able to several years from now :) Regular expressions are real powerful, and I am learning through using ViM - but it takes time and practice. (err, I didn't include your example with quotes, but you should get the general idea) *** '>>> stngs = [r'This Is An $EXAMPLE String', r'This Is An $EXAMPLE.String', r'This Is An $EXAMPLE',r'This Is An \$EXAMPLE\String'] '>>> stngs ['This Is An $EXAMPLE String', 'This Is An $EXAMPLE.String', 'This Is An $EXAMPLE', 'This Is An \\$EXAMPLE\\String'] '>>> for i in stngs: wdlist = i.split(' ') for j in wdlist: if j.find(r'$') > -1: dwd = j.split('.')[0] if dwd.find('\\') > -1: dwd = dwd.split('\\')[1] print dwd $EXAMPLE $EXAMPLE $EXAMPLE $EXAMPLE '>>> *** On Wed, 01 Dec 2004 13:40:17 +0100, Peter Otten <[EMAIL PROTECTED]> wrote: [EMAIL PROTECTED] wrote: identifying/extracting a substring from another string. What I have to do is to extract all the strings that begins with a "$" character, but excluding characters like "." (point) and "'" (single quote) and "\" "/" (slashes). For example I have: 1) This Is An $EXAMPLE String 2) This Is An $EXAMPLE.String 3) 'This Is An $EXAMPLE' 4) This Is An \$EXAMPLE\String; I would like to extract only the "keyword" $EXAMPLE and what I'm using at Is that what you want? import re r = re.compile("[$]\w+") r.findall(""" ... 1) This Is An $EXAMPLE String ... 2) This Is An $EXAMPLE.String ... 3) 'This Is An $EXAMPLE' ... 4) This Is An \$EXAMPLE\String; ... """) ['$EXAMPLE', '$EXAMPLE', '$EXAMPLE', '$EXAMPLE'] Peter -- http://mail.python.org/mailman/listinfo/python-list
New experiences with PythonForDelphi
Hi all I hadn't checked PythonForDelphi in a while, and decided to again today. All I can say is *wow*. Those guys are doing a terrific job. For those of you with a pascal background (and a Delphi/Kylix licence), you may want to check it out. In particular, the creation of binary addons/modules (e.g. pyd) is very nearly effortless (I have never used something like SWIG/Pyrex, so I can't compare), and this is where my interest lies. There is also support for Kylix, and I'm gonna try that out as soon as I can get the personal edition down my 56K line :) It is (good) news to me that C is not the only game in town for creating binary python extensions. Just a heads-up is all Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Import a module without executing it?
Hi You could just parse the model file. Off the top of my head *** f = open('ModuleYouWantToExamine.py','r') for i in f: if i.find('def ') > -1: print 'Found a function!: '+i.replace('def ','') f.close() *** You would have to build this up for a more complete examination. Of course, one of the guru's around here should be able to give you guidance regarding actually parsing the file with the interpreter (not executing) and building a dict or something with all the different types of constructs. That's not me :) I want to be able to import this module so I can see "ah ha, this module defines a function called 'test'", but I don't want the code at the bottom executed during the import. Thanks Take care, Jay -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I do this? (eval() on the left hand side)
Hi It's me a = 3 y = "a" print eval(y) To get 'a' to be 4 here, you would say a = 4 I am not sure why you would want to do otherwise? Perhaps you could sketch out a little more about what you are trying to do? That would help a lot. Are you aiming for something like pointer emulation with simple datatypes? Thanks Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Import a module without executing it?
Andy thx for that. I had a file called 'tktest.py' lying around, and I did: '>>> a = compiler.parseFile('tktest.py') And "a" looks something like this: *** Stmt([Import([('Tkinter', None)]), Function(None, 'add_rows', ['w', 'titles', 'rows'], [], 0, None, Stmt([Discard(CallFunc(Getattr(Name('w'), 'configure'), [Keyword('state', Const('normal'))], None, None)), For(AssName('r', 'OP_ASSIGN'), Name('rows'), Stmt([For(AssTuple([AssName('t', 'OP_ASSIGN'), AssName('v', 'OP_ASSIGN')]), CallFunc(Name('zip'), [Name('titles'), Name('r')], None, None), Stmt([Discard(CallFunc(Getattr(Name('w'), 'insert'), [Const('end'), Mod((Const('%s:\t%s\n'), Tuple([Name('t'), Name('v')])))], None, None))]), None), Discard(CallFunc(Getattr(Name('w'), 'insert'), [Const('end'), Const('\n')], None, None))]), None), Discard(CallFunc(Getattr(Name('w'), 'configure'), [Keyword('state', Const('disabled'))], None, None))])), Assign([AssName('app', 'OP_ASSIGN')], CallFunc(Getattr(Name('Tkinter'), 'Tk'), [], None, None)), Assign([AssName('t', 'OP_ASSIGN')], CallFunc(Getattr(Name('Tkinter'), 'Text'), [Name('app'), Keyword('state', Const('disabled'))], None, None)), Discard(CallFunc(Getattr(Name('t'), 'pack'), [], None, None)), Assign([AssName('info', 'OP_ASSIGN')], List([List([Const('Ali'), Const(18)]), List([Const('Zainab'), Const(16)]), List([Const('Khalid'), Const(18)])])), Discard(CallFunc(Name('add_rows'), [Name('t'), List([Const('Name'), Const('Age')]), Name('info')], None, None)), Discard(CallFunc(Getattr(Name('app'), 'mainloop'), [], None, None))]) *** Pretty impressive :) Do you know of more batteries that can process this stuff further, for interest sake (and maybe the OP)? thx again Caleb On Tue, 7 Dec 2004 15:57:16 -0500, Andy Gross <[EMAIL PROTECTED]> wrote: You'll want to use the "compiler" package. compiler.parseFile will return an AST that you can inspect (which is not really 'reflection', btw). /arg -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I do this? (eval() on the left hand side)
Sure, ok, I think I am with you now. You get a (e.g.) variable name as a string, and you KNOW how to evaluate it with "eval", but you also want to be able to assign back to (through) the string representation? One way (if I understand you correctly) is with the globals or locals dicts. Try this in IDLE: '>>> a = 3 '>>> y = 'a' '>>> eval(y) 3 '>>> d = locals() # Get a dictionary of local variables '>>> d['a'] 3 '>>> d[y] 3 '>>> d[y] = 8 # y is a string = 'a' '>>> a # The value of a is changed. 8 '>>> Is this kinda what you mean? I'm still new at this (and don't know REXX from Adam). Thanks Caleb There are many situations where this is useful. For instance, you might be getting an input which is a string representing the name of a variable and you wish to evaluate the expression (like a calculator application, for instance). -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.stdin.read question
Hi You are probably typing this within IDLE. Try it after starting python in a shell like DOS or Bash. Should work then (works for me, and I also get the AttributeError in IDLE. Thanks Caleb On Tue, 07 Dec 2004 21:15:51 GMT, It's me <[EMAIL PROTECTED]> wrote: Why do I get an "AttributeError: read" message when I do: import sys r=sys.stdin.read() ?? I've tried: r=sys.stdin.read(80) r=sys.stdin.read(1) same error message. I couldn't find any reference to this function in my Python book (they have the stdout but not in). Some sample code I saw uses this function in the same manner I am and so I am assuming this is the correct syntax? Or is this a bug in Python 2.4? -- It's me -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.stdin.read question
It runs properly in a shell (bash), but on another matter: '>>> r=sys.stdin.read(1) g '>>> r 'g' '>>> r=sys.stdin.read(5) 1234567890 '>>> r '\n1234' '>>> What exactly happened to my 1234567890? I understand that I am only taking 5 characters, but where does the newline (\n) come from? Is that a remnant from when I terminated the previous 'g' input? Thanks Caleb On Tue, 07 Dec 2004 23:36:56 -0500, Caleb Hattingh <[EMAIL PROTECTED]> wrote: Hi You are probably typing this within IDLE. Try it after starting python in a shell like DOS or Bash. Should work then (works for me, and I also get the AttributeError in IDLE. Thanks Caleb On Tue, 07 Dec 2004 21:15:51 GMT, It's me <[EMAIL PROTECTED]> wrote: Why do I get an "AttributeError: read" message when I do: import sys r=sys.stdin.read() ?? I've tried: r=sys.stdin.read(80) r=sys.stdin.read(1) same error message. I couldn't find any reference to this function in my Python book (they have the stdout but not in). Some sample code I saw uses this function in the same manner I am and so I am assuming this is the correct syntax? Or is this a bug in Python 2.4? -- It's me -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.stdin.read question
I don't have much experience with popen3. I do know that IDLE (interactive interpreter) does something to sys.stdin, and that is probably the problem you are seeing. Try your commands through the python interactive interpreter started from a shell (DOS or Bash), see if it still happens. thx Caleb On Tue, 7 Dec 2004 23:16:50 +0100, Lars Tengnagel <[EMAIL PROTECTED]> wrote: Hej Caleb and others I've been strugling with the same problem where i try to use popen3 to run a program. If I use a piped commandline the program can read the file without problems but in the IDLE and with popen it comes with an error. I haven't been able to read the stdin either so the problem so far is unsolved for my point. But the newline command would explain my problems with the program. Can it be a problem under windows since I'm using XP and the winpython Hopefully Lars "Caleb Hattingh" <[EMAIL PROTECTED]> skrev i en meddelelse news:[EMAIL PROTECTED] It runs properly in a shell (bash), but on another matter: '>>> r=sys.stdin.read(1) g '>>> r 'g' '>>> r=sys.stdin.read(5) 1234567890 '>>> r '\n1234' '>>> What exactly happened to my 1234567890? I understand that I am only taking 5 characters, but where does the newline (\n) come from? Is that a remnant from when I terminated the previous 'g' input? Thanks Caleb On Tue, 07 Dec 2004 23:36:56 -0500, Caleb Hattingh <[EMAIL PROTECTED]> wrote: Hi You are probably typing this within IDLE. Try it after starting python in a shell like DOS or Bash. Should work then (works for me, and I also get the AttributeError in IDLE. Thanks Caleb On Tue, 07 Dec 2004 21:15:51 GMT, It's me <[EMAIL PROTECTED]> wrote: Why do I get an "AttributeError: read" message when I do: import sys r=sys.stdin.read() ?? I've tried: r=sys.stdin.read(80) r=sys.stdin.read(1) same error message. I couldn't find any reference to this function in my Python book (they have the stdout but not in). Some sample code I saw uses this function in the same manner I am and so I am assuming this is the correct syntax? Or is this a bug in Python 2.4? -- It's me -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I do this? (eval() on the left hand side)
Peter, I second that. Nick In what way is it unreliable? I can't seem to create a situation where the update through globals and locals doesn't work. Are you referring perhaps to the possibility of variables being garbage collected and then not being around later when one tries to access them through a string name? I don't know very much about the garbage collector, so I can't say for sure. thx Caleb On Wed, 08 Dec 2004 10:38:30 -0500, Peter Hansen <[EMAIL PROTECTED]> wrote: Nick Coghlan wrote: Generally, altering the contents of the dicts returned by locals() and globals() is unreliable at best. Nick, could you please comment on why you say this about globals()? I've never heard of any possibility of "unreliability" in updating globals() and, as far as I know, a large body of code exists which does in fact rely on this -- much of mine included. ;-) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: updating locals() and globals() (WAS: How do I do this? (eval() on the left hand side))
Steve, I don't think I understand. Here is what I just tried: '>>> def f(): x = 3 d = locals() print x print d['x'] d['x'] = 5 print x '>>> f() 3 3 3 '>>> In your example, x had not yet been initialised, maybe. What I am seeing is that "x" does not seem to update when being assigned to - I guess this is what you are referring to by being unreliable. But "unreliable" sounds kinda vague and intermittent, and I assume that is not the case here - What is the Rule(tm)? Thanks Caleb On Wed, 08 Dec 2004 16:59:23 GMT, Steven Bethard <[EMAIL PROTECTED]> wrote: Peter Hansen wrote: Nick Coghlan wrote: Generally, altering the contents of the dicts returned by locals() and globals() is unreliable at best. Nick, could you please comment on why you say this about globals()? I've never heard of any possibility of "unreliability" in updating globals() and, as far as I know, a large body of code exists which does in fact rely on this -- much of mine included. ;-) Updating locals() is unreliable. Updating globals() is fine, AFAIK. http://docs.python.org/lib/built-in-funcs.html I believe that the only time that locals() is updatable is when locals() is globals(): >>> locals() is globals() True >>> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined >>> locals()['x'] = 3 >>> x 3 >>> def f(): ... print locals() is globals() ... locals()['x'] = 3 ... print x ... >>> f() False Traceback (most recent call last): File "", line 1, in ? File "", line 4, in f NameError: global name 'x' is not defined Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I do this? (eval() on the left hand side)
Thx Peter I verified this situation myself with a post from Steven Bethard earlier (trying to use "locals" within a function definition). I am convinced now that locals() doesn't work as (I) expected. Steven says there was some or other reason why locals() as used in this context is not writable - Do you know why this is? I really do not like guidelines like "may not work", "is unreliable" and so on. Perhaps this is a character flaw, but I really do like to know what works, when it works, and when it doesn't work. In this scenario, we can see it doesn't work. To my eyes, it doesn't work *in the way I expect* (which is highly subjective, no argument there). Would this be a situation where it would be nice to have an exception thrown if locals() is assigned to in a scope where it is not writable? It would also be nice if globals and locals behaved the same, differing only in scope (which is what I expected originally anyway). But we can't have everything, I guess :) Caleb On Wed, 08 Dec 2004 20:49:53 +0100, Peter Otten <[EMAIL PROTECTED]> wrote: Caleb Hattingh wrote: In what way is it unreliable?ÃÂÃÂIÃÂcan'tÃÂseemÃÂtoÃÂcreateÃÂaÃÂsituationÃÂwhere the update through globals and locals doesn't work.ÃÂÃÂÃÂAreÃÂyouÃÂreferring Updates to a locals() dictionary may not be reflected by the variables in the local scope, e. g.: def f(): ... locals()["a"] = 1 ... print a ... f() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in f NameError: global name 'a' is not defined def f(): ... a = 42 ... locals()["a"] = 1 ... print a ... f() 42 Updating globals() should be safe. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I do this? (eval() on the left hand side)
Both Peters :) Sure, I must concede that the problem here was my expectation of how things should work. Thanks for the explanations. I still don't really know whether this behaviour of locals() is the result of a design decision, or an implementation artifact of CPython, but at least I have a clear idea of how to play nice with locals(). thx Caleb Peter Otten wrote: > Caleb Hattingh wrote: > > > I am convinced now that locals() doesn't work as (I) expected. Steven > > says there was some or other reason why locals() as used in this context > > is not writable - Do you know why this is? I really do not like > > guidelines like "may not work", "is unreliable" and so on. Perhaps this > > is a character flaw, but I really do like to know what works, when it > > works, and when it doesn't work. > > I think Peter Hansen has answered that. Your expectations were just wrong. > > > In this scenario, we can see it doesn't work. To my eyes, it doesn't work > > *in the way I expect* (which is highly subjective, no argument there). > > Would this be a situation where it would be nice to have an exception > > thrown if locals() is assigned to in a scope where it is not writable? > > If python were to throw an exception, it should always be thrown. But I'm > the wrong one to worry about that as I didn't even find a single > > globals()[name] = value > > assignment in my scripts. I want to know a variable's name, or I put it in a > dictionary. > > > It would also be nice if globals and locals behaved the same, differing > > only in scope (which is what I expected originally anyway). But we can't > > have everything, I guess :) > > That would mean that both would become read-only, I guess, but I don't see > that happen. > > Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary initialization
Hi Dan I must confess that upon rereading my words, there is some irony there (but not really sarcasm, is there?). However, I *really* tried to keep my tone, well, professional. I realise I didn't do a good job and apologise. I hope that's ok. Keep well Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Pictograms and Python
Diez Ya got me there! """ I have a sript that downloads a webpage. According to the picture on this webpage I need to pass a parameter to this , running script a few lines later. """ Err, ya, I guess I would be suspicious too.Sorry about that! Keep well Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Ideas for projects
Here is something I would try but don't have the guts for: If you could write an extension to idle (yes, idle, not Boa, not Eric, etc) that pops up a small list of possible completions in a listbox when you type a '.' (period) after any object name or module name (including builtins), that would be *awesome*. I have been very spoilt by Delphi in this regard. Some kind of code that does partial compiles in the background to analyse code for members would be sweet. On Thu, 09 Dec 2004 03:29:51 GMT, Phillip Bowden <[EMAIL PROTECTED]> wrote: I feel that I've learned the language pretty well, but I'm having trouble thinking of a medium to large project to start. What are some projects that you have written in the past with Python? -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I do this? (eval() on the left hand side)
Jeff I do the same thing in Delphi -> prepend "Self" before all the members in class methods even though its not required. I do it partially for the same reason as you - so I can grok which variables are local and which are global (well, global within the class, anyway). The other reason is because of the magical little menu that pops up when I type the period after "Self", and lets me pick a class member by typing the first few letters... Keep well Caleb On Thu, 09 Dec 2004 09:39:58 -0800, Jeff Shannon <[EMAIL PROTECTED]> wrote: -- heck, even before I knew Python existed, I typically used this->name to reference C++ members despite the fact that 'this' was not required, just because I wanted to be able to *see* which variables were members and which weren't...) Jeff Shannon Technician/Programmer Credit International -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling a C program from a Python Script
Hi Brad Not that I'm an expert but note: 1. If you already know C, fair enough. You should know what you are getting into then. I sure as heck don't know it very well at all and I'm not gonna make that time investment now. MAYBE if I really really needed the extra speed (but this seems to arise more infrequently than one would imagine) for something where I couldn't interface with some existing binary library. 2. The PythonForDelphi crowd makes the creation of native binary extensions with Delphi pathetically easy (which is about equivalent to the degree of complexity I can handle). As I said in a previous post, C is not the only game in town for binary extensions. Of course, I happen to already know ObjectPascal (Delphi) quite well, so for me it is a good fit - maybe not so much for you if pascal would be new for you. If both pascal AND C are new for you, I suspect you will find Delphi a fair bit easier (& faster) to learn. btw, Works with Kylix also. I don't know about FPC. 3. As someone said previously, some of the 'builtin' python functionality is compiled C anyway. This point alone often makes it very difficult to qualify statements like 'python is slow'. You could even start with the Cpython source for something like file access and see how you go with optimization, if *that* performance was not enough for you. 4. Nobody mentioned Pyrex yet, I think it kinda allows you to write C within your python scripts, and then handles that all intellligently, compiles the necessary bits, and so on - try a google search for the facts rather than my broken memory of features. 5. If all you are is curious about interfacing a C extension with Python - that's cool too. I would be interested in hearing what to look out for in the learning stage of developing C-extensions, for when I am overcome by curiosity and feel the need to try it out. Keep well Caleb I just want to know the basics of using C and Python together when the need arises, that's all, I don't want to write a book about what exactly it is that I'm involved in. I'm going to take It's Me's advice and have a look at SWIG. Thank you, Brad -- http://mail.python.org/mailman/listinfo/python-list
Re: large dictionary creation takes a LOT of time.
In fact, as one of the Peter's (either Otten or Hansen) explained to me, for line in open(file): is actually both faster (being buffered) and generally better for very large files because it doesn't read the whole file into memory, like readlines does (if you have a memory limitation). On Fri, 29 Apr 2005 12:00:37 -0400, Kent Johnson <[EMAIL PROTECTED]> wrote: Maksim Kasimov wrote: Kent Johnson wrote: > for line in open(path): the line of your example raise another question: opened file will be read at once time, as method readlines() do, or it will be read line by line as method readline() do. It will be read line by line as readline() does. as far i know, it is depends on implementation of method "__iter__" of the object that "open()" returns, so another question: where i can find such an information (about how does such a functions works)? http://docs.python.org/lib/built-in-funcs.html http://docs.python.org/lib/bltin-file-objects.html Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: looking for a simple way to load a program from another python program..
Hi Eric Check that ".py" and ".pyw" are in your PATHEXT environment variable (are you using Windows?). Then, if the folder that cabel is in is in your PATH environment variable, and the correct association for .py files is set up (i.e. they get run by python.exe), either os.system('cabel') or os.system('cabel.py') should work. Alternatively, you could not do any of those things, and run os.system('python cabel.py') with 'cabel.py' in the same folder as the parent script, and that should work too, assuming that the path to your python executable is on the PATH environment variable. If you run other commands from python quite frequently, it is probably a good idea to look into the "os.popen" set of commands, for more flexibilty. Caleb -- http://mail.python.org/mailman/listinfo/python-list
And now for something completely different...
I spent way too much time reading the recent massive ">500-messages" thread, and then spent even more time (perhaps better spent) reading wider on some aspects of the debate. This recently-found link sets out (from one possibly-biased POV, I guess) how the rift between GNU Emacs and XEmacs occurred: http://www.jwz.org/doc/lemacs.html After reading the page, and in light of much of the "your-syntax-is-obscure/mine-is-clear/easy-to-read/hard-to-read" discussion on said ">500-messages" thread, I found the last line on the above lemacs.html page very funny, and wanted to share it. Not saying that such a thing couldn't ever be said about some given implementation of something complex in python (or any language, for that matter), but I still had a good chuckle. Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: automatically grading small programming assignments
Hi Brian You could make great use of XML-RPC here. XML-RPC is /really/ easy to use. Here is a simple example: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81549 You put procedures on the server that will check the args against a the required result, and report back to the student whether it passes or fails. Here is another example using xml-rpc over https, for security: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496786 So, the idea is that the student calls a procedure on the xml-rpc server (which you set up), and passes his results as an argument, and your server procedure can return True or False. One benefit is that if you change the input to the tests, you need only update the server.Actually, you could let the procedures on the server accept test input and student results, and return True or False. This would be cool :) Caleb On Dec 14, 6:27 pm, Brian Blais <[EMAIL PROTECTED]> wrote: > Hello, > > I have a couple of classes where I teach introductory programming using > Python. What > I would love to have is for the students to go through a lot of very small > programs, > to learn the basic programming structure. Things like, return the maximum in > a list, > making lists with certain patterns, very simple string parsing, etc. > Unfortunately, > it takes a lot of time to grade such things by hand, so I would like to > automate it > as much as possible. > > I envision a number of possible solutions. In one solution, I provide a > function > template with a docstring, and they have to fill it in to past a doctest. Is > there a > good (and safe) way to do that online? Something like having a student post > code, > and the doctest returns. I'd love to allow them to submit until they get it, > logging > each attempt. > > Or perhaps there is a better way to do this sort of thing. How do others who > teach > Python handle this? > > thanks, > > Brian Blais > > -- > - > > [EMAIL PROTECTED] > http://web.bryant.edu/~bblais -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing and reading variables to/from flat file
Hi Kevin The other posters helped you with configParser, which is what you wanted, i.e. text file access. However, you can also get persistance really cheaply with pickling, if you don't need the saved data to be text-editable: (from memory) verboseSettings = {} verboseSettings['Detailed'] = '-vv' verboseSettings['Basic'] = '-q' import cPickle # Save the data - Just give the dict! cPickle.dump(verboseSettings, file('prefs','w+')) # Load the data back - get the dict back verboseSettings = cPickle.load(file('prefs','r')) I recently did a ton of scientific data analysis looking for trends in 10 years of data for a petrochemical plant, and I learned just how convenient dicts and pickles can be to manage one's sanity :) Caleb On Dec 14, 4:31 pm, Kevin Walzer <[EMAIL PROTECTED]> wrote: > I want to write some variables (user preferences, specifically) to a > text file and then read the values from that file. > > Here is my code to write the data: > > verbosemodes= """ > Detailed = "-vv" > Basic = "-q" > """ > > file = open('prefs', 'w') > > file.writelines(verbosemodes) > > file.close() > > And here is my code, in a separate module, to read the file and display > the variable values: > > readfile = open('prefs').readlines() > > for line in readfile: > print line > > print Basic > > Running the second module yields this error: > > Detailed = "-vv" > > Basic = "-q" > > Traceback (most recent call last): > File "readprefs.py", line 6, in > print Basic > NameError: name 'Basic' is not defined > > Clearly the data is getting read (the lines are being printed), but the > variable itself ("Basic") is not being initialized properly. I'm not > sure what I'm doing wrong here--can anyone point me in the right > direction? Thanks. > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: concatenating strings
Hi Erich If you're going to be doing a lot of string substitution, you should look at the Templating support in the library: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304005 and (a little bit fancier): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335308 Regards Caleb On Dec 15, 12:18 pm, "Erich Pul" <[EMAIL PROTECTED]> wrote: > thank you, i just plainly overlooked it ; ) > > now it works -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to push data into Microsoft Excel & Word from Python ?
The Night Blogger wrote: > Is there a way to push data to Microsoft Excel & Word from a Python > Application On Windows, it's easy after you install the win32 extensions. For example, for python: import win32com.client xl = win32com.client.Dispatch('Excel.Application') after which you can operate on "xl" (almost) as if you were coding in VBA. I have driven Excel from python a /lot/, and it works well. Paul Boddie has written a great tutorial---which includes some Outlook examples, btw---over here: http://thor.prohosting.com/~pboddie/Python/COM.html > Is this a cross platform feature ? I'll need to push data on MS Windows & > Mac OS X I have zero OSX experience, but 30s of googling brings up this: http://appscript.sourceforge.net/ Kevin Walzer mentions on this mailing list entry: http://mail.python.org/pipermail/python-list/2006-August/400255.html that Excel provides reasonably good support for applescript, but again, I have no idea whether these things work; I'm just doing your googling for you. Assuming applescript works, you may want to write a thin wrapper over the combination of the win32 COM interface and the applescript interface that at least lets your business logic sit in one place. The wrapper can use the right API depending on the platform it finds itself on at runtime. Regards Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary, iterate & update objects
jansenh wrote: > hi comp.lang.python. > > I need some newbe advice on idiomatic use of Python dictionaries. > > I have service with a dictionary which holds a bunch of objects as > values, and an ID as key to each object. Then I want to change an > objects state based on its key. The way I am doing this now is by using > 'fromkeys' and copying my object over in a temporary dictionary, then > manipulating the object, and then I do an 'update' back to the main > dictionary.. :-0 It would be easier to help if you post a short snippet of code that demonstrates the essence of the issue, but I made an attempt at coding what you describe: >>> d = {} >>> class o(object): ... def __init__(self): ... self.x = 0 ... >>> i = o() >>> d[12345]=i >>> temp=d[12345] >>> temp.x = 5 >>> d[12345].x 5 >>> i.x 5 >>> After I assign the object to the dict with ID=12345, I can easily get the object by its key and manipulate its state. The last 4 lines show that the state changed for all the active references to the created object. Is this what you wanted? If you are this Henning Jansen: http://www.henning-jansen.com/ you may get a lot much more accurate help from others in this group by mentioning that you have some Ruby experience. That way, the guys in here who also know Ruby (not me :) can quickly point out the differences in behaviour for your specific question. Regards Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to push data into Microsoft Excel & Word from Python ?
Hi Paul > Thanks for the kind words! No, thank _you_ for taking the time to write such a useful document. regards Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: rsync for python?
> I want to build rsync server that can run in linux and windows, and > configure by python. So I'm looking for something like rsync for python. > I find rsync.py and pysync. But rsync.py looks like a client mode, > it can't be a rsync server, is it? Can pysync be a rsync server? Hi nienfeng As file synchronizers go, I have had very good experience with Unison: http://www.cis.upenn.edu/~bcpierce/unison/ which supports unix and windows, but does not run as a server and is not directly python-enabled. You can set it up to run automatically using cron (linux) or Scheduled Tasks (windows), if that was the functionality you wanted in a server implementation of such a tool. regards Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: No speedup on multi-processor machine?
On Apr 21, 11:02 pm, [EMAIL PROTECTED] wrote: > Hi, > I am using Python Thread library for my parallel processing course > project. I am doing matrix convolution on a multi-processor machine > running Solaris. I just found out that no speed-up is obtained with > threading. It is probably because of something called GIL in Python. > How can I get around > that GIL and get speed-up? > Thanks in advance. > Daniel Perhaps try http://www.parallelpython.com/ or http://www.its.caltech.edu/~astraw/seppo.html Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: I need suggests
Pat wrote: > I have to do a big programm. Could someone give me some suggests about > IDE (on Linux) and books to learn. http://groups.google.com/groups/search?q=python+ide&qt_s=Search Lots and lots to read :) Caleb -- http://mail.python.org/mailman/listinfo/python-list
Can one query full name (or version) of selected packages at pypi?
Hi everyone I suspect this has come up before, but google and group searches for "python package index query" or "pypi query" and the like haven't turned anything up. I want to monitor the versions of the list of packages I like having around, and I expect that the python package index might be a good place to do this. Typically, such packages would include, say, Pyrex and PyParsing, for example. So: I would like to query the package index with a short name (perhaps wildcarded), and retrieve either the full name (from which to strip the ver.) or version number, and compare it with what I have on disk. At this stage, just reporting the differences is fine. I could do these steps myself with normal http access and screen-scraping, but is there already such a system/script somewhere? Alternatively, how do you all keep versions of python addons up-to-date? Manually? regards Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Can one query full name (or version) of selected packages at pypi?
Hi Martin Pretty much exactly what I wanted :) How up-to-date does Debian keep its package list for python addons, or are you running Unstable? My big problem, being in South Africa, is that I have to get any distros on cover CDs or order from distro-resellers, and they never have Testing or Unstable. Broadband hasn't exactly hit the local market, although things might be looking up in a few years or so. keep well Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: ConfigParser and multiple option names
I have had this same problem before, and what I ended up doing was writing my own far more limited config parser that would create lists for repeated named assignments. Who is the maintainer of ConfigParser? Perhaps a keyword option can be added so that this kind of behaviour can be added at creation. Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Lambda alternative?
On Wed, 15 Apr 2009 15:47:05 +0200, wrote: But, lambda functions can't be pickled. I would like to pickle my objects, and i would really like to use parallel python (which requires pickling). If you are fixated on using lambda, you could probably use Recipe 7.6: Pickling Code Objects in the Python Cookbook, 2nd Edition, or here: http://www.ubookcase.com/book/Oreilly/Python.Cookbook.2nd.edition/0596007973/pythoncook2-chp-7-sect-6.html However, it is better to use named functions as all the other posters have already mentioned. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this possible in Python?
Hi I don't think this is what you want (a string representation of the argument passed to a function as that argument is at runtime is way beyond my abilities), but this can retrieve the literal text in the function call as it appears in the .py file, assuming you have the .py file available and not just the .pyc: ### Call this file "pyfunargtest.py" def fun(i): pass fun(8+7) def test(): fname = 'pyfunargtest.py' testfunname = 'f' flines = open(fname,'r').readlines() for i in flines: if i.find(testfunname)>-1 and i.find('def '+testfunname)==-1: s = i break leftbracketposition = s.find('(') rightbracketposition = s.find(')') arg = s[leftbracketposition+1:rightbracketposition] return arg print test() ### Output: # 8+7 [EMAIL PROTECTED] wrote: > Hi > > I wonder if Python is capable of the following: define a function which > returns its argument. > I mean: > def magic_function(arg): > .. some magic code ... > > that behaves the following way: > > assert magic_function(3+4)=="3+4" > assert magic_function([i for i in range(10)])=="i for i in range(10)]" > > It is not trivial at all and might require some bytecode hacking that i > am unable to do myself BUT you are the experts ;-) > > Alain > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python IDE: great headache....
Hi Being a Delphi user at work, I know what you mean :) The best python IDE I have found is Stani's Python Editor (SPE), and I think Stani himself replied to your message as well. It integrates wxGlade, which is nice for form-building, although I don't really do much of that with the python code I write. My only gripe with SPE is that the memory usage, while SPE is running, slowly climbs and climbs, and after several hours that python thread running SPE is using several hundred megabytes of RAM. I usually just restart it. It seems as if the effect is pronouced when running code in the IDE. Other than that, I now use SPE instead of Vim for python editing, which is a big step for me. SPE is quite slick; some ways to go, but certainly on the right track. The built-in code-completion is a godsend. Hope this helps Caleb Sullivan WxPyQtKinter wrote: > IDLE is no longer satisfactory for me. Other IDEs make me very > confused. Really do not know which one to use. > > I use WinXP sp2 for current development. > > So far as I know, Eclipse + PyDev + PyDev Extension is perfect for > source code editing. Since I am really not sure how to use the debugger > module, I really do not know how to add watch to variables etc. Anyone > knows if this platform is a good one? > > I hope that an IDE should be featured with: > 1. Grammar Colored highlights. > 2. Manage project in a tree view or something alike, ie, a project file > navigator. > 3. Code collapse and folding. > 4. Code auto-completion: especially prompting function parameters when > I am typing a function previously defined by myself. Like the one in > Visual Studio series. > 5. Debugging: Breakpoints, conditional pause. watch for variables.step > into, over and out of a function. > What about other IDEs? Since I do not need GUI development. More over, > the free-of-charge IDE is highly preferred. > 6.Indentation management like in IDLE: press ctrl+[/] to modify the > identation of a line or a block. > > In addition, I have seen quite a few editors, which are definitely not > what I want. > > Thank you so much for suggestions. > -- http://mail.python.org/mailman/listinfo/python-list
Binary python extensions with Free Pascal Compiler
Hi all I want to write python extensions with FPC (Free Pascal Compiler, http://www.freepascal.org). In Delphi, this is trivially easy due to the great work of the P4D (Python-for-Delphi, http://mmm-experts.com/) guys; however, when aiming for cross-platform binary extensions, that strategy naturally doesn't work. FPC has great cross-platform support, and to date I have written library units that compile to .dlls (on win32) and .so's (on posix), and then used these via ctypes. This has worked very well, but for certain applications I would prefer to create a new python type via binary extension, rather than a python class with method wrappers around library calls. I could just use C, I guess, but I have a large amount of pascal code that I would like to use, and I would prefer not to fiddle with a C-binary extension intermediate. I have explored the python.h header, and as expected, there appears to be much use of the C standard library. Using a tool that converts a C header into an object pascal unit (intended to be the interface to python.dll) gets me some of the way, but of course, calls to the C stdlib don't get automatically translated into equivalent pascal-coded functionality. I'm afraid I am answering my own question here: is the only way of getting this working to change all the stdlib calls in my newly created pascal unit (created from python.h) to matching functionality in pascal? If there is another, simpler way I'm just not seeing, I would be glad to hear it. Regards Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Counting nested loop iterations
Hi Derek I went for an embarrassingly long time without knowing about "enumerate()". It doesn't directly answer your question about counting *within* nests, but I am going to tell you this on the off chance you don't know yet (and apologies if you do): This: count = 0 for animal in zoo: a = animal anum = count count = count + 1 IS a kludge, when you have this available to you: for count, animal in enumerate(zoo): a = animal anum = count I won't say how long it took me to start using list comprehensions :) regards Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Binary python extensions with Free Pascal Compiler
Well, there it is: * Added support for Free Pascal Compiler (http://www.freepascal.org/) and Lazarus Project (http://www.lazarus.freepascal.org/) Thanks to Michiel du Toit ([EMAIL PROTECTED]) That was easy. I just saw the new support for D2k6 recently. thx Ravi Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs. Java gzip performance
I tried this: from timeit import * #Try readlines print Timer('import gzip;lines=gzip.GzipFile("gztest.txt.gz").readlines();[i+"1" for i in lines]').timeit(200) # This is one line # Try file object - uses buffering? print Timer('import gzip;[i+"1" for i in gzip.GzipFile("gztest.txt.gz")]').timeit(200) # This is one line Produces: 3.90938591957 3.98982691765 Doesn't seem much difference, probably because the test file easily gets into memory, and so disk buffering has no effect. The file "gztest.txt.gz" is a gzipped file with 1000 lines, each being "This is a test file". -- http://mail.python.org/mailman/listinfo/python-list
Re: Use of Python with GDAL. How to speed up ?
Hi The documentation for the python profiler in the python library reference is extremely readable (well done James Roskin!?). Profile your code, and when you find where the speed problem occurs, try pitching just that section of code in comp.lang.python. You will likely get much feedback. Everyone loves small optimization exercises, and there be bots here who get the optimal solution on the first try. Though I would like to (seems an interesting application), I don't have time available to go through all your code now. Thanks Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs. Java gzip performance
Hi Peter Clearly I misunderstood what Martin was saying :)I was comparing operations on lines via the file generator against first loading the file's lines into memory, and then performing the concatenation. What does ".readlines()" do differently that makes it so much slower than ".read().splitlines(True)"? To me, the "one obvious way to do it" is ".readlines()". Caleb -- http://mail.python.org/mailman/listinfo/python-list
Simple py script to calc folder sizes
Hi everyone [Short version: I put a some code below: what changes can make it run faster?] Unless you have a nice tool handy, calculating many folder sizes for clearing disk space can be a click-fest nightmare. Looking around, I found Baobab (gui tool); the "du" linux/unix command-line tool; the extremely impressive tkdu: http://unpythonic.net/jeff/tkdu/ ; a python script I didn't really understand at http://vsbabu.org/webdev/zopedev/foldersize.html (are these "folder objects" zope thingies?); there are also tools that can add a "foldersize" column into Explorer on Windows (foldersize.sourceforge.net, for example); the superb freeCommander file-manager (win32) has the functionality built in, and so on. "du" is closest to what I was looking for, but is not immediately cross-platform: I know I can probably get it through Cygwin, and there is probably a win32 binary or clone around somewhere, but I thought a simple python solution would be great. Maybe there already is one, but I couldn't find it with a modest amount of searching. Anyway, I made one that will produce a list of only the folders in the current folder, along with their sizes. I am posting it for two reasons: it might be useful for someone else, and I want to know if it can be made faster (but in a cross-platform way); maybe you spot something in the code that is obviously sub-optimal. # Python script to list sizes of folders in current folder import os, os.path rootfolders = os.listdir('.') rootfolders = [i for i in rootfolders if os.path.isdir(i)] class counter: def __init__(self,rootfolder): self.count = 0 self.rootfolder = rootfolder def inc(self,num): self.count = self.count + num def __str__(self): if self.count<1024.: unit = ' bytes' scaler = 1. elif self.count<1024.*1024.: unit = ' KB' scaler = 1/1024. elif self.count<1024.*1024.*1024.: unit = ' MB' scaler = 1/1024./1024. else: unit = ' GB' scaler = 1/1024./1024./1024. return '%-20s - %8.2f%s'%(self.rootfolder,self.count*scaler,unit) def visitfun(cntObj,dirname,names): for i in names: fullname = os.path.join(dirname,i) if os.path.isfile(fullname): cntObj.inc( os.path.getsize(fullname) ) return None foldersizeobjects = [] for i in rootfolders: cntObj = counter(i) os.path.walk(i,visitfun,cntObj) foldersizeobjects.append(cntObj) def cmpfunc(a,b): if a.count > b.count: return 1 elif a.count == b.count: return 0 else: return -1 foldersizeobjects.sort(cmpfunc) tot=0 for foldersize in foldersizeobjects: tot=tot+foldersize.count print foldersize print 'Total: %.2f MB'%(tot/1024./1024.) # End regards Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: New development windows, IronPython or PythonWin
Hi Dan Pythonwin just adds support for specifically MS Windows features, most prominently COM; writing Excel scripts in python is so cool. The standard python distribution for windows runs perfectly on windows. I'm not sure whether this was clear to you or not. Also, Thomas ctypes and comtypes (by Thomas(?) Heller) also allow COM integration, though I don't think it is as complete as the pythonwin support. Also, I think IronPython is also supported by only one guy - Jim Hugunin. The fact that IronPython development is effectively being sponsored by Microsoft doesn't fill me with great expectations either, although it would be a good thing if they really supported it well. rgds Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiplying sequences with floats
Hi Christoph On my linux py-2.4.1: >>> 4.0//2 # Integer division, but still returns a float. 2.0 >>> 4.0//2 == 2 True >>> 4.0//2 doesn't return an integer, but the equality against an integer still holds. I agree that integer division should return an integer, because using the operator at all means you expect one.Having to cast it after integer division seems unnecessary. Unfortunately, I have zero say on the matter :) This issue was probably discussed at length when the integer division operator (//) was introduced. It is possible there is a good reason behind this, but I don't know it. regards Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple py script to calc folder sizes
Thanks John I will use your code :) 30% improvement is not insignificant, and that's what I was looking for. I find the log function a little harder to read, but I guess that is a limitation of me, not your code. Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiplying sequences with floats
Hi Fredrik Fair enough; I wasn't precise. Upon further reflection, I actually meant floor division, via the // operator. In the following snippet: >>> 4/2 2 >>> 4//2 2 >>> 4.0/2.0 2.0 >>> 4.0//2 2.0 >>> 4.0//2.0 2.0 We know the last two operations can only return what are effectively integer numbers (or raise an error), but the type that gets returned for a valid operation is a float. Now, I'm not pretending to know much about this stuff, just pointing out that that behaviour is interesting.Just like how MvL pointed out to me in a recent thread that in certain cases .read().splitlines(True) is significantly faster than .readlines() on some file objects: that's interesting. I am sure there are good reasons for this, and I can't imagine that the issue of return type didn't come up when discussions about the floor division operator was discussed; in fact, thinking about it a little more, I suspect this operator is probably more likely to be used in a sequence of floating-point operations anyway, for which the current implementation saves a type conversion that might have been necessary had it been made to return int to start with. So regarding my previous statement: >> I agree that integer division should return an integer, >> because using the operator at all means you expect one. I am not so sure now :) By the way (regarding PIL), have you seen this site: http://www.greyc.unicaen.fr/~dtschump/greycstoration/index.html It is an open-source project implementing fancy methods for cleaning up images and (my interest) resizing images with better clarity on enlargements. I had been working on a python implementation for this kind of thing with heavy leaning on the PIL, but I saw this project on the daily freshmeat newsletter, and so will probably use that code instead. regards Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiplying sequences with floats
Christoph I understand the explanation regarding the underlying math.floor() call. Were I using this functionality in my code, int(a//b)* some_list would not be something I consider a big deal. However, I see what you're saying: The multiplcation by list can only work with an int, and you have an integer number, but unfortunatly with type float. Well, I guess that's life :) Again, a small cast like that is not a problem for me, so I can't really comment on this. Keep well Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiplying sequences with floats
Hi Dennis Sure, I get it. I do most of my work in Delphi, which is, shall we say, not lax about floating-point types. Thinking about this more, I realise my initial interest was in looking at the // operator as something new, whereas I now see it probably just wraps math.floor(); obviously then, you're going to get whatever the underlying C math library returns. As an aside, I also realised that the OP could just subclass list to make one that works with multiplications against floats: he could either floor and cast the float to int in the overloaded operator, or make a fancy system of using the fractional part of the float to duplicate the list int(floor()) times, then add just the fraction of the list that approximates most closely the decimal part of the float; this is assuming the outcome is actually meaningful for any particular problem. As I remarked to Christoph, this whole issue is actually a non-issue to me, and I don't want to give the impression I think there is a problem here; just interested in the // operator is all :) regards Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: operation complexities of lists and dictionaries
Hi Use the "timeit" module, like so: >>> from timeit import Timer >>> t = Timer('[i for i in range(1)]') # The string is code to execute >>> (for timing) >>> print t.timeit(100) # execute it 100 times and print the result 0.222389936447 I would appreciate it if you could present your results in this thread. I have also been wondering about timings for simple operations. Thanks Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: Free Python IDE ?
Hi Ernesto SPE, or Stani's python editor is actually a decent IDE that can lauch the winpdb debugger to step through code, with side windows for locals, and watches and so on. It's not exactly integrated debugging a la Delphi, but in general my need for debugging is much less with python; the few times I have needed debugging, SPE did the job well. I also like that SPE automatically checks my code with tabnanny and pychecker. That way I don't have to do anything extra to use these tools. Oh, and SPE is free. Keep well Caleb -- http://mail.python.org/mailman/listinfo/python-list