Re: Python arrays and sting formatting options
On Tue, 30 Sep 2008 00:04:18 +0200, Ivan Reborin wrote: > 1. Multi dimensional arrays - how do you load them in python For > example, if I had: > --- > 1 2 3 > 4 5 6 > 7 8 9 > > 10 11 12 > 13 14 15 > 16 17 18 > --- > with "i" being the row number, "j" the column number, and "k" the .. > uhmm, well, the "group" number, how would you load this ? > > If fortran90 you would just do: > > do 10 k=1,2 > do 20 i=1,3 > > read(*,*)(a(i,j,k),j=1,3) > > 20 continue > 10 continue > > How would the python equivalent go ? Well, I don't know if this qualifies as equivalent: = from __future__ import with_statement from functools import partial from itertools import islice from pprint import pprint def read_group(lines, count): return [map(int, s.split()) for s in islice(lines, count)] def main(): result = list() with open('test.txt') as lines: # # Filter empty lines. # lines = (line for line in lines if line.strip()) # # Read groups until end of file. # result = list(iter(partial(read_group, lines, 3), list())) pprint(result, width=30) if __name__ == '__main__': main() = The output is: [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]]] `k` is the first index here, not the last and the code doesn't use fixed values for the ranges of `i`, `j`, and `k`, in fact it doesn't use index variables at all but simply reads what's in the file. Only the group length is hard coded in the source code. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: str() should convert ANY object to a string without EXCEPTIONS !
En Sun, 28 Sep 2008 07:01:12 -0300, Olivier Lauzanne <[EMAIL PROTECTED]> escribió: On Sep 28, 11:21 am, est <[EMAIL PROTECTED]> wrote: Can anyone tell me how to customize a default encoding, let's say 'ansi' which handles range(256) ? I assume you are using python2.5 Edit the file /usr/lib/python2.5/site.py There is a method called def setencoding(): [...] encoding = "ascii" [...] Change "encoding = "ascii" to encoding = "utf-8" On windows you may have to use "mbsc" or something like that. I have no idea what windows use at its encoding. *Not* a good idea at all. You're just masking errors, and making your programs incompatible with all other Pythons installed around the world. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
I built a nice html templater!
Ok - so it's not really an awesome achievement and only handles basic templating needs (no loops and other programming constructs) but maybe someone will find it useful. It replaces any xml block where the id attribute is specified with contents provided - a description is provided in the comments. http://pastebin.com/m76f57ae2 My knowledge of python is limited and I would like someone to help me with wrapping a command line interface around this function. I need switches to specify input file, output file, key/value pairs for variable substitution and key/value pairs for substituting blocks with file contents (there is some clarification in the comments) Any help would be appreciated. Of course - feel free to use the code as you wish when you wish if you wish :) -d- -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib2 and exceptions
En Sun, 28 Sep 2008 22:44:20 -0300, robean <[EMAIL PROTECTED]> escribió: Many thanks for your reply. I was simply under the impression that 'import urllib2' would take care of the namespace issue and simply import everything in urlib2, making it unnecessary to have to reference HTTPError and URLError. Sorry for being dense about this (I'm very new to Python).. Again, thanks for your help. That's a common misconception - see this article: http://effbot.org/zone/import-confusion.htm -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Using the 'with' statement with cStringIO objects
En Sat, 27 Sep 2008 19:28:49 -0300, peppergrower <[EMAIL PROTECTED]> escribió: When I got that particular error, I suspected that it had something to do with the relative newness of the 'with' statement. If this is something that should be considered for addition in the future, is there somewhere specific I should suggest that? Yes: http://bugs.python.org/ (setting type="feature request", I think) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Python arrays and sting formatting options
Ivan Reborin wrote: Hello everyone, I was wondering if anyone here has a moment of time to help me with 2 things that have been bugging me. 1. Multi dimensional arrays - how do you load them in python For example, if I had: --- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 --- with "i" being the row number, "j" the column number, and "k" the .. uhmm, well, the "group" number, how would you load this ? If fortran90 you would just do: do 10 k=1,2 do 20 i=1,3 read(*,*)(a(i,j,k),j=1,3) 20 continue 10 continue How would the python equivalent go ? 2. I've read the help on the next one but I just find it difficult understanding it. I have; a=2.01 b=123456.789 c=1234.0001 How do you print them with the same number of decimals ? (eg. 2.000, 123456.789, 1234.000) and how do you print them with the same number of significant decimals? (eg. 2.01, 123456.7, 1234.000 - always 8 decimals) ? Is something like this possible (built-in) in python ? Really grateful for all the help and time you can spare. -- Ivan I'm not sure if this is applicable to your multi-dimensional list problem... but it sounded a bit sudoku like (with row, columns and groups) so I thought I'd share a bit of code of developed in regards to solving sudoku puzzles... Given a list of 9 list elements, each with nine elements (lets call it sudoku_grid), the following list comprehensions produce lists of indexes into sudoku grid vgroups = [[(x,y) for y in xrange(9)] for x in xrange(9)] hgroups = [[(x,y) for x in xrange(9)] for y in xrange(9)] lgroups = [[(x,y) for x in xrange(a,a+3) for y in xrange(b,b+3)] for a in xrange(0,9,3) for b in xrange(0,9,3)] where sudoku_grid[y][x] yields the value at position (x,y), assuming the top left corner is indexed as (0,0) HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: What is not objects in Python?
En Tue, 30 Sep 2008 01:03:07 -0300, namekuseijin <[EMAIL PROTECTED]> escribió: On 28 set, 15:29, process <[EMAIL PROTECTED]> wrote: Why isn't len implemented as a str.len and list.len method instead of a len(list) function? Because postfix notation sucks. The natural way of spelling is adjective+noun and verb+predicate. That's one of the reasons I like Lisp better than Python. Well, "natural" for English-speaking people... Noun+adjective is usually more "natural" In Spanish than the English word ordering. Back to the original question, len(x) allows for a fast response without paying the overhead of a name lookup and then a method call. len(some_list) doesn't invoke some_list.__len__(), it just returns the value stored somewhere in the list object; same for other built-in objects. __len__ is searched as a last resort only. The optimization could not be done if it were spelled x.len() -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
Lawrence D'Oliveiro wrote: > In message <[EMAIL PROTECTED]>, r0g wrote: > >> You can only distribute modifications to gnuplot itself as >> patches, but you can distribute it freely ... > > This must be some new definition of "freely" of which I'm unaware. As in beer. -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing float and decimal
Gabriel Genellina wrote: En Thu, 25 Sep 2008 08:02:49 -0300, Mark Dickinson <[EMAIL PROTECTED]> escribió: On Sep 23, 1:58 pm, Robert Lehmann <[EMAIL PROTECTED]> wrote: I don't see why transitivity should apply to Python objects in general. Hmmm. Lack of transitivity does produce some, um, interesting results when playing with sets and dicts. Here are sets s and t such that the unions s | t and t | s have different sizes: from decimal import Decimal s = set([Decimal(2), 2.0]) t = set([2]) len(s | t) 2 len(t | s) 1 Ouch! This opens up some wonderful possibilities for hard-to-find bugs... And I was thinking all this thread was just a theoretical question without practical consequences... To explain this anomaly more clearly, here is a recursive definition of set union. if b: a|b = a.add(x)|(b-x) where x is arbitrary member of b else: a|b = a Since Python only defines set-set and not set-ob, we would have to subtract {x} to directly implement the above. But b.pop() subtracts an arbitrary members and returns it so we can add it. So here is a Python implementation of the definition. def union(a,b): a = set(a) # copy to preserve original b = set(b) # ditto while b: a.add(b.pop()) return a from decimal import Decimal d1 = Decimal(1) fd = set((1.0, d1)) i = set((1,)) print(union(fd,i)) print(union(i,fd)) # prints {1.0, Decimal('1')} {1} This is a bug in relation to the manual: "union(other, ...) set | other | ... Return a new set with elements from both sets." Transitivity is basic to logical deduction: equations: a == b == c ... == z implies a == z implications: (a implies b) and (b implies c)implies (a implies c) The latter covers syllogism and other deduction rules. The induction part of an induction proof of set union commutivity is a typical equality chain: if b: a | b = a.add(x)| b-x for x in b # definition for non-empty b = b-x | a.add(x) # induction hypothesis = (b-x).add(x) | a.add(x)-x # definition for non-empty a = b | a.add(x)-x # definitions of - and .add if x not in a: = b | a # .add and - if x in a: = b | a-x# .add and - = b.add(x) | a-x # definition of .add for x in b = b | a # definition for non-empty a = b | a # in either case, by case analysis By transitivity of =, a | b = b | a ! So where does this go wrong for our example? This shows the problems. >>> fd - i set() This pretty much says that 2-1=0, or that 2=1. Not good. The fundamental idea of a set is that it only contains something once. This definition assumes that equality is defined sanely, with the usual properties. So, while fd having two members implies d1 != 1.0, the fact that f1 == 1 and 1.0 == 1 implies that they are really the same thing, so that d1 == 1.0, a contradiction. To put this another way: The rule of substitution is that if E, F, and G are expressions and E == F and E is a subexpression of G and we substitute F for E in G to get H, then G == H. Again, this rule, which is a premise of all formal expressional systems I know of, assumes the normal definition of =. When we apply this, fd == {f1, 1.0} == {1,1.0} == {1} == i But Python says >>> fd == i False Conclusion: fd is not a mathematical set. Yet another anomaly: >>> f = set((1.0,)) >>> i == f True >>> i.add(d1) >>> f.add(d1) >>> i == f False So much for "adding the same thing to equals yields equals", which is a special case of "doing the same thing to equals, where the thing done only depends on the properties that make the things equal, yields equals." And another >>> d1 in i True >>> 1.0 in i True >>> fd <= i False Manual: "set <= other Test whether every element in the set is in other" I bet Python first tests the sizes because the implementer *assumed* that every member of a larger set could not be in a smaller set. I presume the same assumption is used for equality testing. Or Manual: "symmetric_difference(other) set ^ other Return a new set with elements in either the set or other but not both." >>> d1 in fd True >>> d1 in i True >>> d1 Decimal('1') >>> fd ^ i {Decimal('1')} If no one beats me to it, I will probably file a bug report or two, but I am still thinking about what to say and to suggest. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
In message <[EMAIL PROTECTED]>, r0g wrote: > Lawrence D'Oliveiro wrote: > >> In message <[EMAIL PROTECTED]>, r0g wrote: >> >>> You can only distribute modifications to gnuplot itself as >>> patches, but you can distribute it freely ... >> >> This must be some new definition of "freely" of which I'm unaware. > > As in beer. You get free beer? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python script for tracert
cindy jones wrote: Hello.. I'm trying to do a scripting for tracert in windows using python... I'm using popen(), but it displays only after the tracert is completed. i want the results to be displayed for every route. I believe "tracert" is a really ugly 8.3 abbrevivation of traceroute ;) Well, maybe an implementation in python itself could be of interest? http://mail.python.org/pipermail/python-list/2003-March/196063.html maybe there are more attempts - this one was just the first thing which popped up with g**gle. (The script is in the attachment). Regards Tino smime.p7s Description: S/MIME Cryptographic Signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Tue, 30 Sep 2008 14:50:26 +1300, Lawrence D'Oliveiro wrote: > In message <[EMAIL PROTECTED]>, r0g wrote: > >> You can only distribute modifications to gnuplot itself as patches, but >> you can distribute it freely ... > > This must be some new definition of "freely" of which I'm unaware. You're free to distribute the official release of gnuplot. You're free to distribute patches to gnuplot. You're even free to provide people with a script or program to apply those patches to gnuplot. Where's the non-free bit? Personally, I don't get the whole "only distribute patches" requirement. It's a bit like saying "You're free to distribute this software, but only as a tarball". It seems silly to me. But I don't see it as non-free, except in the sense that "only licences approved by the FSF are free". -- Steven -- http://mail.python.org/mailman/listinfo/python-list
How best to pass arbitrary parameters from one function to another
Hi Pythonistas, I'm looking for the best way to pass an arbitrary number and type of variables created by one function to another. They can't be global because they may have different values each time they are used in the second function. So far I'm trying to do something like this: def process_args( [list, of, command-line, arguments] ): do stuff return {dictionary : of, local : variables } def main_function( **kwargs ): do stuff return result kw1 = process_args( [some, list] ) kw2 = process_args( [a, different, list] ) for i in main_function( **kw1 ): kw2[ var1 ] = i kw2[ var2 ] = len( i ) for j in main_function(**kw2): print j This only seems to work if I specify a default value for every possible parameter of main_function and also for any others which may be passed to it, which is a bit tedious because there are very many of them but only a few are used in any given execution of the program. Is there a better way to do it? Or have I simply made an error? Regards and thanks, John O'Hagan -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
Steven D'Aprano <[EMAIL PROTECTED]> writes: > On Tue, 30 Sep 2008 14:50:26 +1300, Lawrence D'Oliveiro wrote: > > > In message <[EMAIL PROTECTED]>, r0g wrote: > > > >> You can only distribute modifications to gnuplot itself as > >> patches, but you can distribute it freely ... […] > Where's the non-free bit? You're not free to modify gnuplot and redistribute the result. That you're free to distribute patches is nice, but it's not enough to make the work free. The freedom to help people by giving them an *already-modified* gnuplot is restricted by the copyright holder. It's an artificial restriction on redistribution of derived works, making them second-class for the prupose of getting them into people's hands. > Personally, I don't get the whole "only distribute patches" > requirement. It's a bit like saying "You're free to distribute this > software, but only as a tarball". It seems silly to me. That, too, would be a non-free requirement. > But I don't see it as non-free, except in the sense that "only > licences approved by the FSF are free". I try to judge freedom of a software work by the freedoms granted to all recipients of the work, not by the approval of some organisation. -- \ “When I turned two I was really anxious, because I'd doubled my | `\ age in a year. I thought, if this keeps up, by the time I'm six | _o__) I'll be ninety.” —Steven Wright | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Python-URL! - weekly Python news and links (Sep 30)
QOTW: "AFAICT, _everybody_ is bad at programming C++. One begins to suspect it's not the fault of the programmers." - Grant Edwards Mixing integer, float, Decimal and Fraction objects when comparing may yield unexpected results: http://groups.google.com/group/comp.lang.python/browse_thread/thread/eebc7ee9d9f2ffb0/ Usually class attributes don't have a docstring attached - how to define one? http://groups.google.com/group/comp.lang.python/browse_thread/thread/18a8c3f09ac02f85/ How do people manage their development and production environments (apt, .deb/.rpm, virtualenv, eggs...)? http://groups.google.com/group/comp.lang.python/browse_thread/thread/5d14be5d870f1600/ A real counterexample to the "Python is slow" usual claim (C++ and Python versions of the same CPU intensive task have similar performance): http://groups.google.com/group/comp.lang.python/browse_thread/thread/a63979a6f18bf37/ Implementing (some kind of) "proxy" object to multiple delegates (step by step, and with changing requirements!) http://groups.google.com/group/comp.lang.python/browse_thread/thread/a917e13bf0ea261f/ Should a library terminate program execution when it encounters an error? http://groups.google.com/group/comp.lang.python/browse_thread/thread/f01d514fbe3183ad/ An attempt to explain how closures and dynamic scope work: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c6463402371857dc/ Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It alrea
Welcome to US Computer Jobs
Welcome to US Computer Jobs Windows System Engineer Phone and Inperson Interview http://geocities.com/anandrisks/ http://friendfinder.com/go/g959922 http://amigos.com/go/g959922 -- http://mail.python.org/mailman/listinfo/python-list
Welcome to US Computer Jobs
Welcome to US Computer Jobs Windows System Engineer Phone and Inperson Interview http://geocities.com/anandrisks/ http://friendfinder.com/go/g959922 http://amigos.com/go/g959922 -- http://mail.python.org/mailman/listinfo/python-list
can someone explain why this happens- newbie question
Hi can someone tell me why it prints the high score table multiple times? #high scores program scores =[] choice = None while choice != 0: print """high Score Table 0 - exit 1 - show Scores 2 - add a score 3 - delete a score 4 - sort scores """ choice = input("what would you like to do?") if choice == 0: print "goodbye" elif choice == 1: for score in scores: print scores elif choice == 2: score = input("add a score") scores.append(score) elif choice == 3: score = input("what score would you like to delete ?") if score in scores: scores.remove(score) else: print "that score is not listed" elif choice == 4: scores.sort() scores.reverse() print scores, "highest score first" -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems compiling on CentOS Python 2.5
On Sep 23, 10:37 am, "F." <[EMAIL PROTECTED]> wrote: > Hello, > I have problems makingpythonon CentOS 5. > Seems that can not find something. I can not find the problem. > Where is the problem? > > > case $MAKEFLAGS in \ > > *-s*) CC='gcc -pthread' LDSHARED='gcc -pthread -shared' > > OPT='-DNDEBUG -fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe > > -fomit-frame-pointer -Wall -Wstrict-prototypes' ./python-E ./setup.py -q > > build;; \ > > *) CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG > > -fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe > > -fomit-frame-pointer -Wall -Wstrict-prototypes' ./python-E ./setup.py > > build;; \ > > esac > > running build > > running build_ext > > db.h: found (4, 3) in /usr/include > > db lib: using (4, 3) db-4.3 > > INFO: Can't locate Tcl/Tklibs and/or headers > > building '_ssl' extension > > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -fwrapv -march=i686 -mmmx > > -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall > > -Wstrict-prototypes -I. > > -I/home/unStable/progC/exLibs/Python-2.5.2/Python-2.5.2/./Include -I. > > -IInclude -I./Include -I/usr/local/include > > -I/directory/Python-2.5.2/Python-2.5.2/Include > > -I/directory/Python-2.5.2/Python-2.5.2 -c > > /directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.c -o > > build/temp.linux-i686-2.5/directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.o > > gcc -pthread -shared -fno-strict-aliasing -DNDEBUG -fwrapv -march=i686 > > -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall > > -Wstrict-prototypes > > build/temp.linux-i686-2.5/directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.o > > -L/usr/local/lib -lssl -lcrypto -o build/lib.linux-i686-2.5/_ssl.so > > *** WARNING: renaming "_ssl" since importing it failed: > > build/lib.linux-i686-2.5/_ssl.so: undefined symbol: krb5_auth_con_getrcache > > running build_scripts > > -- > > -- > Publicidadhttp://www.pas-world.com I also spent a couple hours googling for this same problem! It's not tough to figure it out but would have saved time and stress if i hit the answer on my first search. I am also using CentOS 4.4, 4.5 and python 2.4.4. I debugged the Python installation script to find that the tk.h/tcl.h headers are missing. Installing the tk-devel package (using yum) installs the headers. Then re-install Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: How best to pass arbitrary parameters from one function to another
John O'Hagan a écrit : Hi Pythonistas, I'm looking for the best way to pass an arbitrary number and type of variables created by one function to another. > They can't be global because they may have different values each time they are used in the second function. So far I'm trying to do something like this: def process_args( [list, of, command-line, arguments] ): do stuff return {dictionary : of, local : variables } def main_function( **kwargs ): do stuff return result kw1 = process_args( [some, list] ) kw2 = process_args( [a, different, list] ) for i in main_function( **kw1 ): kw2[ var1 ] = i kw2[ var2 ] = len( i ) for j in main_function(**kw2): print j This only seems to work if I specify a default value for every possible parameter of main_function and also for any others which may be passed to it, which is a bit tedious because there are very many of them but only a few are used in any given execution of the program. If this is about commmand line arguments parsing and defaults, you may want to have a look at the optparse package in the stdlib. Also, kwargs work fine with default arguments too, ie: def func(arg1=1, arg2='yadda', arg3=None): print arg1, arg2, arg3 for kw in ({}, {'arg1':42}, {'arg2':'yop', 'arg3' : range(5)}): func(**kw) HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: How best to pass arbitrary parameters from one function to another
On Tue, 30 Sep 2008 08:58:15 +, John O'Hagan wrote: > Hi Pythonistas, > > I'm looking for the best way to pass an arbitrary number and type of > variables created by one function to another. They can't be global > because they may have different values each time they are used in the > second function. > > So far I'm trying to do something like this: > > > def process_args( [list, of, command-line, arguments] ): If you are trying to process commandline args, I suggest you don't re- invent the wheel. Have a look at the two standard modules, optparse and getopt. Of the two, getopt is probably simpler to get started with, but optparse is more powerful. To answer your more general question, see below. > do stuff > return {dictionary : of, local : variables } > > def main_function( **kwargs ): > > do stuff > return result > > kw1 = process_args( [some, list] ) > kw2 = process_args( [a, different, list] ) > > for i in main_function( **kw1 ): > > kw2[ var1 ] = i > kw2[ var2 ] = len( i ) > > for j in main_function(**kw2): > > print j > > This only seems to work if I specify a default value for every possible > parameter of main_function and also for any others which may be passed > to it, which is a bit tedious because there are very many of them but > only a few are used in any given execution of the program. Er, yes. Presumably main_function actually does something. So it expects some arguments, and if the arguments aren't given, then it will fail. To prevent it failing when arguments aren't given, they must have default values. So define them, once, and be done with it: def main_function(a=1, b=2, c=3, d=4): dostuff return result Now this will work fine: result = main_function( **{'a': 22, 'd': 33} ) and b and c will take their default values and everything works well. Default values are a feature, not a problem to be solved. As for your nested for-loops (see above), I'm guessing that you're trying to copy items from one dictionary kw1 to another kw2, before processing kw2. You should check out the update method on dictionaries. Either of: kw2.update(kw1) kw1.update(kw2) will probably do the right thing, depending on which values you want to take priority in the case of clashes. If you need something even more flexible, write a small function to merge the two dicts in whatever way you want. Here's one example: def merge(kw1, kw2): """Merge dict kw1 to kw2 and return a new dict.""" new = kw2.copy() for key, value in kw1.items(): if key in kw2: # clash, keep the biggest value new[key] = max(value, kw2[key]) else: new[key] = value return new -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: can someone explain why this happens- newbie question
change: for score in scores: print scores to: for score in scores: print score that should do the trick :) Almar 2008/9/30 garywood <[EMAIL PROTECTED]> > Hi > can someone tell me why it prints the high score table multiple times? > > #high scores program > scores =[] > choice = None > > while choice != 0: > print """high Score Table > 0 - exit > 1 - show Scores > 2 - add a score > 3 - delete a score > 4 - sort scores > """ > choice = input("what would you like to do?") > if choice == 0: > print "goodbye" > elif choice == 1: > for score in scores: > print scores > elif choice == 2: > score = input("add a score") > scores.append(score) > elif choice == 3: > score = input("what score would you like to delete ?") > if score in scores: > scores.remove(score) > else: > print "that score is not listed" > > > elif choice == 4: > scores.sort() > scores.reverse() > print scores, "highest score first" > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: python & sms
Hi! You can manage Skype from Python('s scripts), for use the functionalities of Skype to send SMS. @-salutations -- Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Not fully OO ?
Lawrence D'Oliveiro a écrit : In message <[EMAIL PROTECTED]>, James Mills wrote: On Fri, Sep 26, 2008 at 8:20 AM, Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote: Object orientation IS procedural. Correction: OOP is Imperative. No, "procedural". Nope, "imperative" !-) The functional unit is called an "expression", the encapsulation of which is called a "function". Hence "functional". Similarly, the procedural unit is commonly called a "statement", the encapsulation of which is a "procedure", not an "imperator". Hence "procedural". "imperative" means that the computation is done through statements that modify the program's state. "procedural" means that these statements are organized in "procedures", that group a serie of statements. OO is based on objects (that carry and manage internal state) and messages. A message can happen to trigger a serie of statements that modifies a program state, so you could say (and this wouldn't be totally false) that an OO method can be seen as a procedure (or at least some methods...), but the whole program's organization is still not the same as one seen in procedural programming. IOW, it's more a matter of how you design / organize your (otherwise imperative) program than anything else. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Tue, 30 Sep 2008 19:04:41 +1000, Ben Finney wrote: > Steven D'Aprano <[EMAIL PROTECTED]> writes: > >> On Tue, 30 Sep 2008 14:50:26 +1300, Lawrence D'Oliveiro wrote: >> >> > In message <[EMAIL PROTECTED]>, r0g wrote: >> > >> >> You can only distribute modifications to gnuplot itself as patches, >> >> but you can distribute it freely ... > […] > >> Where's the non-free bit? > > You're not free to modify gnuplot and redistribute the result. > > That you're free to distribute patches is nice, but it's not enough to > make the work free. The freedom to help people by giving them an > *already-modified* gnuplot is restricted by the copyright holder. > > It's an artificial restriction on redistribution of derived works, > making them second-class for the prupose of getting them into people's > hands. Yes it is. It seems a strange, unnecessary restriction. But is it sufficient to make it non-free? I don't think so. In case you are thinking that gnuplot allows people to *only* distribute the diffs, not the original source to apply the diffs onto, that is not the case. I quote from gnuplot > help copyright "Permission to distribute the released version of the source code along with corresponding source modifications in the form of a patch file is granted with same provisions 2 through 4 for binary distributions." Those provisions aren't terribly onerous, although #3 may be considered a privacy issue: 2. add special version identification to distinguish your version in addition to the base release version number, 3. provide your name and address as the primary contact for the support of your modified version, and 4. retain our contact information in regard to use of the base software. >> Personally, I don't get the whole "only distribute patches" >> requirement. It's a bit like saying "You're free to distribute this >> software, but only as a tarball". It seems silly to me. > > That, too, would be a non-free requirement. > >> But I don't see it as non-free, except in the sense that "only licences >> approved by the FSF are free". > > I try to judge freedom of a software work by the freedoms granted to all > recipients of the work, not by the approval of some organisation. Yes, but you accept some restrictions as legitimate. For example, you accept the restriction that the GPL makes that says you may not redistribute a modified work without making the source code available. That's a restriction, but it's not enough to disqualify it from being a free software licence. In fact, that restriction is *necessary* to make it a free software licence in the sense we're talking about. So "free" does not mean "no restrictions", it merely means "none of some sorts of restrictions, but other restrictions are okay". Likewise the restriction that GPL software must be distributed with a copy of the appropriate licence. It is useful to compare the "diffs only" licence to two different GPL- related scenarios. Scenario one is clearly against the spirit of the GPL, and possibly (hopefully!) the letter as well. Scenario two is not. (1) I distribute the modified source code encrypted and charge $1,000,000 for a NON-TRANSFERABLE licence to the encryption key. If you don't have the encryption key, that's your bad luck. (2) I distribute the modified source code archived in a tar file, and refuse to offer it in any other format. If you don't have an untar application, that's your bad luck. It's my contention that the restriction of supplying diffs is closer to Scenario 2 than to Scenario 1. The modified source is supplied, but it is split into two pieces: the official source, plus a set of diffs. Reversing that to get the modified source is not much more difficult than untarring a tarball. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Shed Skin (restricted) Python-to-C++ compiler 0.0.29
Hi all, I have just released Shed Skin 0.0.29, with the following changes. Thanks to those mentioned for helping out! - datetime implementation (Karel Heyse, Pavel Vinogradov, FFAO, David Marek) - ConfigParser implementation (suggested by Albert Hofkamp) - staticmethod and property decorator support (Seo Sanghyeon) - GCC 4.3 fixes (Seo Sanghyeon, Winterknight) - FreeBSD, OpenSolaris and 64-bit support - support for mapping keys('%(key)x' % some_dict) - improvements to the import mechanism for nested modules (e.g. os.path) - __init__ is now less of a special case - many fixes for calling ancestor methods (e.g. __init__) - all example programs now compile to extension modules - avoid stack overflows for highly recursive/dynamic types - re.sub now accepts a replacement function - remove tuple hash caching (as CPython does not do this) - many, many bugfixes This has been a significant release, with many important improvements. Please see my latest blog entry with more details: http://shed-skin.blogspot.com/ I would really like to receive more bug reports. Please try out the new release, and file issues at the project homepage: http://shedskin.googlecode.com More coding help is also always welcome. One important feature I'd really like to have for a 0.1 release is custom class support in extension modules.. Thanks! Mark. -- "One of my most productive days was throwing away 1000 lines of code" - Ken Thompson -- http://mail.python.org/mailman/listinfo/python-list
Weirdness comparing strings
Hi, I have this piece of code: class Note(): ... ... def has_the_same_name(self, note): return self == note def __str__(self): return self.note_name + accidentals[self.accidentals] __repr__ = __str__ if __name__ == '__main__': n = Note('B') n2 = Note('B') print n print n2 print n.has_the_same_name(n2) I'd expect to get "True", because their string representation is actually the same, instead the output is: B B False I think I'm missing something stupid. Where am I wrong? -- http://mail.python.org/mailman/listinfo/python-list
Re: Weirdness comparing strings
Hi, Better post complete code. I don't see where self.note_name is defined, and what are these accidentals? you write: def has_the_same_name(self, note): return self == note but this does not implicitly convert self to a string. You'll have to do in explicitly: use "return str(self) == note" instead. Hope this helps, Almar 2008/9/30 Mr. SpOOn <[EMAIL PROTECTED]> > Hi, > I have this piece of code: > > class Note(): > ... > ... > def has_the_same_name(self, note): > return self == note > > def __str__(self): > return self.note_name + accidentals[self.accidentals] > > __repr__ = __str__ > > if __name__ == '__main__': > n = Note('B') > n2 = Note('B') > print n > print n2 > print n.has_the_same_name(n2) > > I'd expect to get "True", because their string representation is > actually the same, instead the output is: > > B > B > False > > I think I'm missing something stupid. Where am I wrong? > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Weirdness comparing strings
Instance comparison is not necessarily the same as string comparison. Neither __str__ nor __repr__ are implicitly used at all for comparison. In fact, by default a pair of instances are not equal unless they are the same object. To define comparison to mean something, you need to define __cmp__ or __eq__. Trivial example of default comparison: >>> class C: ... pass ... >>> c = C() >>> d = C() >>> c==d False >>> c==c True See http://docs.python.org/ref/customization.html for more details. Ken Mr.SpOOn wrote: Hi, I have this piece of code: class Note(): ... ... def has_the_same_name(self, note): return self == note def __str__(self): return self.note_name + accidentals[self.accidentals] __repr__ = __str__ if __name__ == '__main__': n = Note('B') n2 = Note('B') print n print n2 print n.has_the_same_name(n2) I'd expect to get "True", because their string representation is actually the same, instead the output is: B B False I think I'm missing something stupid. Where am I wrong? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Tix Combo box problem - remains in editable mode only
Hi I'm facing a problem with the tix combo box in a way that my combo box is always in an editable mode after I have cleared subwidgets Entry and Listbox from it. My setup is like this : CheckButton1 : If this is unset, the combo box should get disabled, the entries in it should get cleared ( entries are listbox and entry subwidgets) which in my case they get cleared. When this check box is set again, the combo box should get enabled, with no entries in listbox and entry subwidgets ( which are reallly cleared in my case.) But the combox box having being enabled is in editable mode despite of setting it to un-editable mode. The code is as follows: #Combo Box self.cbAnalysisLibVersion = Tix.ComboBox(self.frame1, \ dropdown = True, \ command=self.__cllbkAnalysisLibVer, \ editable=0, \ variable=verSelection, options='listbox.height 8\ listbox.width 25 \ entry.width 30 \ entry.anchor w \ entry.padx 30', \ history = False) #Check Button box self.chBtResultsComparison = Checkbutton(self.frame2, \ text = "Results Comparison", \ variable = varResultsComparison, \ command = self.__cllbkResultsComparison) def __cllbkResultsComparison(self, Event = None): subLB = self.cbAnalysisLibVersion.subwidget("listbox") subEntry = self.cbAnalysisLibVersion.subwidget("entry") if varResultsComparison.get() != 1: #Disable Tolerance Text Box self.txtTolerance.delete(1.0, END) self.txtTolerance.config(state = DISABLED, \ bg = "grey") #Delete all entries (entry & subwidget's entries) #in Reference Analysis Results Version Combo Box #and disable this combo box. #First Delete the Listbox sub-widget entries subLB.delete(0, END) subLB.config(state = DISABLED) #Then delete Entry sub-widget entries #subEntry = self.cbAnalysisLibVersion.subwidget("entry") subEntry.config(state = NORMAL) subEntry.delete(0, END) subEntry.config(state = DISABLED) self.cbAnalysisLibVersion.config(state = DISABLED) #Diable Result Comparison Button self.btViewComparisonResults.config(state = DISABLED) else: #Check box is ticked #Enable the Tolerance text box self.txtTolerance.config(state = NORMAL, \ bg = "white") #Enable the Reference Analysis Combo box #self.cbAnalysisLibVersion.config(state = NORMAL, editable=0) self.cbAnalysisLibVersion.configure(state = NORMAL, editable = 0) subLB.config(state = NORMAL) subEntry.config(state = NORMAL) self.btViewComparisonResults.config(state = NORMAL) Please suggest what is that I am missing Regards, Rajat -- http://mail.python.org/mailman/listinfo/python-list
Re: Weirdness comparing strings
On Tue, Sep 30, 2008 at 12:55 PM, Ken Seehart <[EMAIL PROTECTED]> wrote: > Instance comparison is not necessarily the same as string comparison. > Neither __str__ nor __repr__ are implicitly used at all for comparison. Ok, I see. > In fact, by default a pair of instances are not equal unless they are the > same object. To define comparison to mean something, you need to define > __cmp__ or __eq__. > > Trivial example of default comparison: > class C: > ... pass > ... c = C() d = C() c==d > False c==c > True Thanks. Almar Klein: >but this does not implicitly convert self to a string. You'll have to >do in explicitly: >use "return str(self) == note" instead. Yes, this works. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: what does "python -i" use as input stream (stdin)?
Wow, it's that easy... thanks! 2008/9/29 Gabriel Genellina <[EMAIL PROTECTED]> > En Fri, 26 Sep 2008 04:29:42 -0300, Almar Klein <[EMAIL PROTECTED]> > escribió: > > I would still like to hear if anyone knows how I can change the input >> stream >> that >> is used when running "python -i", but I would not be surprised if it is >> impossible... >> > > Sure you can. You have to replace the file descriptor 0, that is, "standard > input"; sys.stdin reads from there. The standard way is to use os.dup2: > > c:\temp>type foo.txt > This line read from foo.txt > > > c:\temp>type redirect.py > import os > > inp = open("foo.txt","r") > os.dup2(inp.fileno(), 0) > print "raw_input->", raw_input() > > c:\temp>python redirect.py > raw_input-> This line read from foo.txt > > This is not > > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: What is not objects in Python?
Terry Reedy wrote: > Steven D'Aprano wrote: >> On Mon, 29 Sep 2008 05:41:02 -0700, George Sakkis wrote: >> >>> For example I would be much less >>> opposed to len() being defined as, say, |x| if "|...|" was a valid >>> operator. >> >> Arghh! No!!! |x| should be abs(x), not len(x). Just ask mathematicians >> and physicists. > > It should be both, just as + is addition for numbers and concatenation > for sequences. Or we could have just one built-in -- size() instead of > abs() and len(). For non-sequence collections, size() would be better > than len() anyway. > And how are these "non-sequence collections" to be distinguished? And how does size() differ from len() in that case? regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing float and decimal
On Sep 30, 9:21 am, Terry Reedy <[EMAIL PROTECTED]> wrote: > If no one beats me to it, I will probably file a bug report or two, but > I am still thinking about what to say and to suggest. I can't see many good options here. Some possibilities: (0) Do nothing besides documenting the problem somewhere (perhaps in a manual section entitled 'Infrequently Asked Questions', or 'Uncommon Python Pitfalls'). I guess the rule is simply that Decimals don't mix well with other numeric types besides integers: if you put both floats and Decimals into a set, or compare a Decimal with a Fraction, you're asking for trouble. I suppose the obvious place for such a note would be in the decimal documentation, since non-users of decimal are unlikely to encounter these problems. (1) 'Fix' the Decimal type to do numerical comparisons with other numeric types correctly, and fix up the Decimal hash appropriately. (2) I wonder whether there's a way to make Decimals and floats incomparable, so that an (in)equality check between them always raises an exception, and any attempt to have both Decimals and floats in the same set (or as keys in the same dict) also gives an error. (Decimals and integers should still be allowed to mix happily, of course.) But I can't see how this could be done without adversely affecting set performance. Option (1) is certainly technically feasible, but I don't like it much: it means adding a whole load of code to the Decimal module that benefits few users but slows down hash computations for everyone. And then any new numeric type that wants to fit in with Python's rules had better worry about hashing equal to ints, floats, Fractions, complexes, *and* Decimals... Option (2) appeals to me, but I can't see how to implement it. So I guess that just leaves updating the docs. Other thoughts? Mark -- http://mail.python.org/mailman/listinfo/python-list
Advice for a replacement for plone.
I want a new python based CMS. ... One that won't keep me up all night I've been fooling around with zope and plone, and I like plone for some things, such as a repository for online project documentation. However for general-purpose web development it is too monolithic. Is there anything out there with the following properties? 0. Web page being developed is a typical small business home page (i.e. not a newspaper or a blog). 1. Page owner can edit pages on line with no expertise (plone does great here). 2. Main page does not look plone-like. For an example of a main page that does not look plone-like, see http://www.arbitrary.com/ Note the lack of CMS style navigation widgets. 3. Item 2 should be reachable with nearly no effort (plone fails utterly here). 4. Target viewer (not the owner), should /not/ see something that looks at all like a CMS system, but rather see exactly what the page owner wants the page to look like. 5. Page owner should be able to view and navigate the tree of contents, and select pages to edit with a wysiwyg editor (plone does great here)... 6. ... But the target viewer should not see this tree. See items 2 and 4. 7. Potential to add python scripted pages of various kinds. There are a couple different design approaches to making a development environment. You can let the developer start with nothing, and provide the developer with tools to create something (e.g. zope, most plain text editors), or you can start with a finished result and let the developer rip out and discard what is not desired (e.g. plone). I often prefer to start with nothing. It's a natural starting point. Note that systems that are based on starting with nothing can provide the benefits of starting with something by providing templates and such. I would love to see a system that would give me an editable Hello World page in under 5 minutes. Hello World would be a page consisting of nothing but the words "hello world" (no tools, no navigation bar, and certainly no CMS navigation stuff) in a url such as www.myhelloworldwebsite.com/hello and a different url to edit the page, such as www.myhelloworldwebsite.com/hello/edit or www.mywebsite.com/edit/hello If you are a plone fanatic and still think I should use plone, fine, but please let me know where I can find a "Hello World" kind of example that demonstrates items 2, 4, and 6. In addition, I would like the ability to design the layout of the page independent of the content. Plone has some nice features that would be very helpful, but again, getting to hello world seems difficult. Just plain Zope does a pretty good job at some of this, but I haven't found a good online wysiwyg editor for the page owner to modify content. Thanks for any ideas. Ken -- http://mail.python.org/mailman/listinfo/python-list
Re: Tix Combo box problem - remains in editable mode only
On Tue, Sep 30, 2008 at 11:57 AM, <[EMAIL PROTECTED]> wrote: > Hi > > I'm facing a problem with the tix combo box in a way that my combo box is > always in an editable mode after I have cleared subwidgets Entry and Listbox > from it. > > > My setup is like this : > > CheckButton1 : > > If this is unset, the combo box should get disabled, the entries in it > should get cleared ( entries are listbox and entry subwidgets) which in my > case they get cleared. > > When this check box is set again, the combo box should get enabled, with no > entries in listbox and entry subwidgets ( which are reallly cleared in my > case.) But the combox box having being enabled is in editable mode despite > of setting it to un-editable mode. > > > The code is as follows: > #Combo Box > self.cbAnalysisLibVersion = Tix.ComboBox(self.frame1, \ > dropdown = True, \ > > command=self.__cllbkAnalysisLibVer, \ > editable=0, \ > variable=verSelection, > options='listbox.height 8\ > listbox.width 25 \ > entry.width 30 \ > entry.anchor w \ > entry.padx 30', \ > history = False) > > > #Check Button box > self.chBtResultsComparison = Checkbutton(self.frame2, \ >text = "Results Comparison", > \ >variable = > varResultsComparison, \ >command = > self.__cllbkResultsComparison) > > def __cllbkResultsComparison(self, Event = None): > > subLB = self.cbAnalysisLibVersion.subwidget("listbox") > subEntry = self.cbAnalysisLibVersion.subwidget("entry") > > if varResultsComparison.get() != 1: > #Disable Tolerance Text Box > > self.txtTolerance.delete(1.0, END) > self.txtTolerance.config(state = DISABLED, \ > bg = "grey") > #Delete all entries (entry & subwidget's entries) > #in Reference Analysis Results Version Combo Box > #and disable this combo box. > > #First Delete the Listbox sub-widget entries > subLB.delete(0, END) > subLB.config(state = DISABLED) > > #Then delete Entry sub-widget entries > #subEntry = self.cbAnalysisLibVersion.subwidget("entry") > subEntry.config(state = NORMAL) > subEntry.delete(0, END) > subEntry.config(state = DISABLED) > > self.cbAnalysisLibVersion.config(state = DISABLED) > #Diable Result Comparison Button > self.btViewComparisonResults.config(state = DISABLED) > > else: > #Check box is ticked > #Enable the Tolerance text box > self.txtTolerance.config(state = NORMAL, \ > bg = "white") > #Enable the Reference Analysis Combo box > #self.cbAnalysisLibVersion.config(state = NORMAL, editable=0) > self.cbAnalysisLibVersion.configure(state = NORMAL, editable = 0) > subLB.config(state = NORMAL) > subEntry.config(state = NORMAL) > > self.btViewComparisonResults.config(state = NORMAL) > > > Please suggest what is that I am missing > > Regards, > Rajat > Any help guys? -- Regrads, Rajat -- http://mail.python.org/mailman/listinfo/python-list
Re: What is not objects in Python?
On Mon, 2008-09-29 at 21:03 -0700, namekuseijin wrote: > On 28 set, 15:29, process <[EMAIL PROTECTED]> wrote: > > I have heard some criticism about Python, that it is not fully object- > > oriented. > > So what? > > > Why isn't len implemented as a str.len and list.len method instead of > > a len(list) function? > > Because postfix notation sucks. The natural way of spelling is > adjective+noun and verb+predicate. That's one of the reasons I like > Lisp better than Python. > -- > http://mail.python.org/mailman/listinfo/python-list > Actually str.len and len(str) is just like saying "the string's length" and "the length of the string". There is no difference between the two except for personal preference. (I am no linguist-- not even a native speaker of English --but I think there is a subtle difference on emphasis, "the string's length" emphasizes on the length being string's property, while "the length of the string" emphasizes on the length itself, am I correct?) -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question...
Ken D'Ambrosio wrote: First, apologies for such a newbie question; if there's a better forum (I've poked around, some) feel free to point it out to me. Anyway, a mere 25-odd years after first hearing about OOP, I've finally decided to go to it, by way of Python. But this puzzles me: import commands free = commands.getoutput("free") for line in free: print line, Gives: t o t a l u s e d f r e e s h a r e d b u f f e r s c a c h e d M e m : 5 1 5 9 9 2 4 6 0 4 5 2 5 5 5 4 0 0 7 7 5 1 6 9 1 8 8 4 - / + b u f f e r s / c a c h e : 2 9 1 0 5 2 2 2 4 9 4 0 Why are there spaces between everything? And how do I keep it from happening? *confused* Thanks much, -Ken ** Posted from http://www.teranews.com ** -- http://mail.python.org/mailman/listinfo/python-list The variable 'free' is a string containing all of the output, not a file object or a sequence of strings. Therefore, when you iterate free you iterate a sequence of characters. This is different than the case of iterating an open file, which would give you a sequence of lines as you expect. So ... print line, ... prints each character followed by a space and no newline. You can do this instead: import commands free = commands.getoutput("free") print free - Ken (that's my name too) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
Steven D'Aprano <[EMAIL PROTECTED]> writes: > On Tue, 30 Sep 2008 19:04:41 +1000, Ben Finney wrote: > > You're not free to modify gnuplot and redistribute the result. > > > > That you're free to distribute patches is nice, but it's not > > enough to make the work free. The freedom to help people by giving > > them an *already-modified* gnuplot is restricted by the copyright > > holder. > > > > It's an artificial restriction on redistribution of derived works, > > making them second-class for the prupose of getting them into > > people's hands. > > Yes it is. It seems a strange, unnecessary restriction. But is it > sufficient to make it non-free? I don't think so. I do, because a natural, beneficial act (modify the work and redistribute it) that has no technical reason to restrict, is artifically restricted. > In case you are thinking that gnuplot allows people to *only* > distribute the diffs, not the original source to apply the diffs > onto, that is not the case. I quote from gnuplot > help copyright > > "Permission to distribute the released version of the source code > along with corresponding source modifications in the form of a patch > file is granted with same provisions 2 through 4 for binary > distributions." That's what I refer to when I say that it artifically makes derived works into second-class for the purpose of doing the beneficial act of distributing them: the redistributor is artificially restricted from making the work as useful as the original they received. They have only the options to redistribute a work that is more cumbersome for the recipient of that work, or not to redistribute at all. That's not free redistribution. > > I try to judge freedom of a software work by the freedoms granted > > to all recipients of the work, not by the approval of some > > organisation. > > Yes, but you accept some restrictions as legitimate. For example, you > accept the restriction that the GPL makes that says you may not > redistribute a modified work without making the source code available. Yes, which is why I was careful to say "the freedoms granted to all recipients of the work". The power to restrict a recipient of one's work (by choosing not to grant them the freedoms you yourself had when you received the work) reduces the freedoms available to all recipients of the work, even though one party's power may be increased. This is where the useful "your freedom to swing your fist ends at the tip of the other man's nose" applies: As soon as the act you wish to perform is restricting the freedom of another, you're not contemplating an act of freedom, but an act of power over another. Freedoms should be protected, but only within the limits imposed by the freedoms of others. > That's a restriction, but it's not enough to disqualify it from > being a free software licence. Specifically because it upholds the freedom of the recipient of a derived work from having power exerted over them. > In fact, that restriction is *necessary* to make it a free software > licence in the sense we're talking about. Not really; it's necessary to make it a copyleft license, which is a way of preserving freedom as the work gets passed along. Works can still be free software without being copyleft-licensed, though. A license allowing free redistribution and requiring only attribution be preserved is less restrictive than a copyleft; yet, because it allows any free act (even as it also allows acts of power over others), the work is free software. > So "free" does not mean "no restrictions", it merely means "none of > some sorts of restrictions, but other restrictions are okay". > Likewise the restriction that GPL software must be distributed with > a copy of the appropriate licence. That's right, and I've explained above what restrictions I consider justified, and why, and how to tell the difference. -- \ “Reichel's Law: A body on vacation tends to remain on vacation | `\unless acted upon by an outside force.” —Carol Reichel | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: writing dll in python?
Terry Reedy wrote: Start with the Python tutorial, perhaps parts of the reference manual, and definitely peruse the first chapters in the library manual on built-in functions and classes. Check out http://wiki.python.org/moin/BeginnersGuide to see a range of ways to learn Python, most very good (what works for you vaires by student). You will almost certainly want to use numpy (numpy.org) for numerical calculation and possibly existing modules in scipy (scipy.org) or elsewhere. Although it is likely someyhing like numpy will be necessary, don't make the mistake of thinking Python cannot handle calculation itself easily. Where you'll need to leave python is in array and matrix calculations, there the numpy code will get you near custom C/fortran code speeds. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On 30 Sep, 14:19, Ben Finney <[EMAIL PROTECTED]> wrote: > > This is where the useful "your freedom to swing your fist ends at the > tip of the other man's nose" applies: As soon as the act you wish to > perform is restricting the freedom of another, you're not > contemplating an act of freedom, but an act of power over another. > Freedoms should be protected, but only within the limits imposed by > the freedoms of others. This is a very good explanation of what copyleft is all about. I suppose one could regard copyleft as a means to preserve the "maximal common freedom" in a system - if anyone else were to acquire more power or privilege to do something, that would diminish the freedoms of others. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: What is not objects in Python?
Steven D'Aprano wrote: > On Mon, 29 Sep 2008 21:03:07 -0700, namekuseijin wrote: > >>> Why isn't len implemented as a str.len and list.len method instead of a >>> len(list) function? >> Because postfix notation sucks. The natural way of spelling is >> adjective+noun and verb+predicate. > > "Natural"? > > You mean phrases like "heir apparent" and "worst choice imaginable" are > unnatural? They are certainly far from normal usage, as my dog yellow would be certain to agree. > To say nothing of languages like Spanish, Albanian, Italian, > Cornish, Vietnamese, Hebrew... It's long been a convention in the Western programming world to pretend no other language than English and no other codes than ASCII exist. The fact that Python is beginning to come to terms with Unicode is a tribute to certain developers' persistence. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How best to pass arbitrary parameters from one function to another
On Tue Sep 30 11:32:41 CEST 2008, Steven D'Aprano >On Tue, 30 Sep 2008 08:58:15 +, John O'Hagan wrote: > >> Hi Pythonistas, >> >> I'm looking for the best way to pass an arbitrary number and type of >> variables created by one function to another. They can't be global >> because they may have different values each time they are used in the >> second function. >> >> So far I'm trying to do something like this: >> >> >> def process_args( [list, of, command-line, arguments] ): > > >If you are trying to process commandline args, I suggest you don't re- >invent the wheel. Have a look at the two standard modules, optparse and >getopt. Of the two, getopt is probably simpler to get started with, but >optparse is more powerful. > Thanks, both to you and Bruno for pointing this out, I'll certainly be using it in future. >To answer your more general question, see below. > > >> do stuff >> return {dictionary : of, local : variables } >> >> def main_function( **kwargs ): >> >> do stuff >> return result >> >> kw1 = process_args( [some, list] ) >> kw2 = process_args( [a, different, list] ) >> >> for i in main_function( **kw1 ): >> >> kw2[ var1 ] = i >> kw2[ var2 ] = len( i ) >> >> for j in main_function(**kw2): >> >> print j >> >> This only seems to work if I specify a default value for every possible >> parameter of main_function and also for any others which may be passed >> to it, which is a bit tedious because there are very many of them but >> only a few are used in any given execution of the program. >> >Er, yes. Presumably main_function actually does something. So it expects >some arguments, and if the arguments aren't given, then it will fail. To >prevent it failing when arguments aren't given, they must have default >values. So define them, once, and be done with it: [...snip code example...] >Default values are a feature, not a problem to be solved. I take your point, but in this case all necessary parameters are present in the keyword dictionary, so I guess I was surprised that default values still need to specified. Also, the function body tests for the presence of each parameter and only acts on those that are there, so it does not fail because of a missing argument. However, I'm sure there's a good reason that it works this way. >As for your nested for-loops (see above), I'm guessing that you're trying >to copy items from one dictionary kw1 to another kw2, before processing >kw2. You should check out the update method on dictionaries. [...] That's also of great use, thank you. What I'm actually trying to do, though, is add some of the output of one call of main_function to the arguments of another call of the same function (with different arguments). It's a long story, but I have a number-crunching function which produces lists of numbers representing musical notes, either rhythmic or melodic, to be printed out as a score using Lilypond and/or played by samples or synthesizers using sox. The melodic and rhythmic parts work by themselves, but I'm trying to get the function to feed itself rhythms for its melodies, and vice-versa. I guess that's already too much information Thanks for your help. John -- http://mail.python.org/mailman/listinfo/python-list
Re: Weirdness comparing strings
Mr.SpOOn wrote: Hi, I have this piece of code: class Note(): Unless you _need_ old-style, use new style. ... def has_the_same_name(self, note): return self == note Define equality (__eq__) if you want to compare for equality. def __str__(self): return self.note_name + accidentals[self.accidentals] __repr__ = __str__ If str and repr are to be equal, just define repr. class Note(object): def __init__(self, note, accidentals): self.note_name = note self.accidentals = accidentals def has_the_same_name(self, note): return self == note def __eq__(self, other): return isinstance(other, Note) and ( self.note_name == other.note_name and self.accidentals == other.accidentals) def __repr__(self): return self.note_name + accidentals[self.accidentals] --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python style: exceptions vs. sys.exit()
Steven D'Aprano a écrit : On Mon, 29 Sep 2008 18:27:22 +0200, Bruno Desthuilliers wrote: Lawrence D'Oliveiro a écrit : In message <[EMAIL PROTECTED]>, Ross Ridge wrote: You need either use trial and error to find out, or look at the source. So what's wrong with using the source as documentation? :) Don't know... Ok, having higher-level documentation (the big picture, and quick description of what and how for classes and functions) really helps. But when it comes to nitty-gritty details, source code is the best documentation ever, since it's always accurate and up to date. FWIW, I'm often surprised by people asking questions about some implementation detail of some open-source library or framework that are very easily answered just looking at the source code. Reading the source is 1/ the best way to really know how something is implemented and 2/ usually very instructive. Reading the source code is good, but it's not a panacea. Not what I implied. There are at least four things wrong with the advice to read the source code: My "advice to read the source code" was not meant as a *replacement* for documentation, but as a *complement* to it. What I meant is that you just can't document each and every detail of implementation. (1) It's not always available. (2) Even when the source is available, it is sometimes a legal trap to read it with respect to patents and copyright. E.g. some Microsoft so- called "open" licences (but not all) allow you to read the source, but if you do then everything you program in a related field from that point is legally contaminated and could be considered a derivative work of Microsoft's software. I obviously implied that source was freely available and you had the right to read it. Else it just makes no sense. (3) Source code not always understandable without significant effort. That's why reading the source can have a great educational value, isn't it ?-) Code can be obfuscated, either to hide the algorithm, same problem as closed-source software - not concerned by this advice. as an optimization, or simply because the coder is cleverer than you are. It might be in a language you don't understand (e.g. Python built-ins are written in C, not Python. I have to learn C to find out what exceptions sorted() can raise?). Every developer should have at least basic knowledge of C. MHO of course. That's why accurate documentation should be preferred in the first place. Indeed. Did I say otherwise ? Now not all code has accurate documentation, and then you're happy to be able to access and possibly understand the source code. I'm not talking about an ideal world here. (snip) Yes, documentation can fall behind the source code, but once the code is stable and the documentation has caught up and is accurate, there's no reason to re-invent the wheel by slugging through the source just to find out something already documented. Once again, that's not what I said. (4) Even when the source code is available, legally unencumbered, in a language you understand and not too complicated for you to grasp, there's the combinatorial explosion: you may need to read and understand an arbitrarily large and complex chain of software merely to know what a single function can do. Yes, this happens when hi-level documentation is lacking. At least you have a chance to gain some insight !-) E.g. you want to know what exceptions function spam() can raise: def spam(x): a = 1 b = 2 c = ham(x) return fried_eggs(a, b, c) Now you need to understand ham() and fried_eggs(), but they aren't documented either. So you turn to their source code, and each of them call two functions, each of which call another two functions, each of which call *another* two functions... And still you're a lucky guy if there's no callback, conditional import and / or polymorphic dispatch involved. Steve, I may not have been clear, but I didn't meant that code shouldn't be documented. I was : 1/ answering to the question "So what's wrong with using the source as documentation?", my own personal answer being that it's something I often do, whether because I want to find out some detail not covered by the available documentation, whatever this available documention is worth 2/ digressing about the fact that, to my suprise, few developpers seem to *first* have a look at the source code when either documentation is lacking or they'd like to know more about some implementation detail. But FWIW, it seems that few developpers even bother reading the documentation at all :( -- http://mail.python.org/mailman/listinfo/python-list
ElementTree Help With DTD
Afternoon All, I have used elementtree for a little while now parsing simple XML documents and found it pretty intuitive. Today is the first time I've used the library to create an XML file though. I have a simple script which looks like this: # Save the configuration to the XML file. # Create the root element, top = etree.Element("top") # Create the other elements in the tree. sub1 = etree.SubElement(top, "sub1") sub1.text = "other text" # Create the core element tree object. tree = etree.ElementTree(top) # Write the XML to the file system. tree.write("/path/to/my.xml") This works just fine, in as much that I get an XML file with the correct XML content within it, like so: other text However, I really need to validate this built XML against a DTD schema that I have, and also add the DTD reference to the top of the generated file, so other applications parsing it in can validate it properly, like so: other text As you can see, this also includes the proper XML definition for the file. Can anyone offer any pointers on how to have ElementTree add these additional definitions to the file it generates? And also validate itself against the DTD before writing to the FS? Many thanks guys, I really appreciate it. Heston -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Tue, 30 Sep 2008 22:19:57 +1000, Ben Finney wrote: > Steven D'Aprano <[EMAIL PROTECTED]> writes: > >> On Tue, 30 Sep 2008 19:04:41 +1000, Ben Finney wrote: >> > You're not free to modify gnuplot and redistribute the result. >> > >> > That you're free to distribute patches is nice, but it's not enough >> > to make the work free. The freedom to help people by giving them an >> > *already-modified* gnuplot is restricted by the copyright holder. >> > >> > It's an artificial restriction on redistribution of derived works, >> > making them second-class for the prupose of getting them into >> > people's hands. >> >> Yes it is. It seems a strange, unnecessary restriction. But is it >> sufficient to make it non-free? I don't think so. > > I do, because a natural, beneficial act (modify the work and > redistribute it) that has no technical reason to restrict, is > artifically restricted. We agree that the restriction is artificial, and I think irrational (although I'd be interested in hearing the gnuplot developers' reasoning before making a final judgment). But I just don't see the requirement that modified software be distributed in form X (original source + diffs) versus form Y (modified source in a tar ball) or form Z (an rpm) to be that big a deal. Not enough to make it "non-free software". I simply don't think that having to run some variation on patch -i patchfile.patch is a requirement so onerous that it makes the gnuplot licence non-free. Perhaps I'm just more tolerant of eccentricities than you :) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Python arrays and sting formatting options
On 30 Sep 2008 07:07:52 GMT, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: Hello Marc, thanks for answering (on both subjects). I understand now the logic which lays behind what you were explaining in the other one. It cleared things quite a bit. >Well, I don't know if this qualifies as equivalent: > >= >from __future__ import with_statement >from functools import partial >from itertools import islice >from pprint import pprint > > >def read_group(lines, count): >return [map(int, s.split()) for s in islice(lines, count)] > >def main(): >result = list() >with open('test.txt') as lines: >lines = (line for line in lines if line.strip()) >result = list(iter(partial(read_group, lines, 3), list())) >pprint(result, width=30) >if __name__ == '__main__': >main() >= I'm afraid I must admit I find the code above totally uncomprehesible (I can't even see where the array here is mentioned - "result"?) and inpractical for any kind of engineering practice I had in mind. Does python, perchance, have some wrapper functions or something, which would allow one to load an array in a more natural "technical" way ? Like something mentioned above in my post (now deleted) ? Also, is there a way to change counter for arrays to go from 0 to 1 ? (first element being with the index 1) ? (probably not since that seems like a language implementation thing, but it doesn't hurt to ask) -- Ivan -- http://mail.python.org/mailman/listinfo/python-list
How to add CC and BCC while sending mails using python
Hello all, Can someone tel me how to add cc's and bcc's while sending mails using python Thank you all -- http://mail.python.org/mailman/listinfo/python-list
Replacing cmd.exe with custom .py application
Instead of going to the command line all the time, I want to create a small customized cmd.exe of my own, how can I get the return value from os.system() because I was thinking I can do soothing with os.system(), In case my question is not clear, just like an IDE that plugged in another .exe application. Sorry for any mistake in my question. Just help me if you can -- http://mail.python.org/mailman/listinfo/python-list
Re: Python arrays and sting formatting options
On Tue, 30 Sep 2008 15:42:58 +0200, Ivan Reborin wrote: > On 30 Sep 2008 07:07:52 GMT, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> > wrote: >>= >>from __future__ import with_statement from functools import partial >>from itertools import islice >>from pprint import pprint >> >> >>def read_group(lines, count): >>return [map(int, s.split()) for s in islice(lines, count)] >> >>def main(): >>with open('test.txt') as lines: >>lines = (line for line in lines if line.strip()) >>result = list(iter(partial(read_group, lines, 3), list())) >>pprint(result, width=30) >> >>if __name__ == '__main__': >>main() >>= > > I'm afraid I must admit I find the code above totally uncomprehesible (I > can't even see where the array here is mentioned - "result"?) and > inpractical for any kind of engineering practice I had in mind. Learn Python then to understand that code. ;-) There is no array. The data type is called "list" in Python, so `result` is a nested list. And in Python it quite unusual to build lists by creating them with the final size filled with place holder objects and then fill the real values in. Instead lists are typically created by appending values to existing lists, using list comprehension or the `list()` function with some iterable object. Typical Python code tries to minimize the use of index variables. Python is not Fortran (or C, or Pascal, …). > Does python, perchance, have some wrapper functions or something, which > would allow one to load an array in a more natural "technical" way ? > Like something mentioned above in my post (now deleted) ? > > Also, is there a way to change counter for arrays to go from 0 to 1 ? You can write your own sequence type but that would be odd because the rest of the language expects zero as the first index, so you will be constantly fighting the language by adding or subtracting 1 all the time at the "border" between your custom sequence type and the the rest of Python. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 30, 9:43 am, Steven D'Aprano <[EMAIL PROTECTED] cybersource.com.au> wrote: > On Tue, 30 Sep 2008 22:19:57 +1000, Ben Finney wrote: > > Steven D'Aprano <[EMAIL PROTECTED]> writes: > > >> On Tue, 30 Sep 2008 19:04:41 +1000, Ben Finney wrote: > >> > You're not free to modify gnuplot and redistribute the result. > > >> > That you're free to distribute patches is nice, but it's not enough > >> > to make the work free. The freedom to help people by giving them an > >> > *already-modified* gnuplot is restricted by the copyright holder. > > >> > It's an artificial restriction on redistribution of derived works, > >> > making them second-class for the prupose of getting them into > >> > people's hands. > > >> Yes it is. It seems a strange, unnecessary restriction. But is it > >> sufficient to make it non-free? I don't think so. > > > I do, because a natural, beneficial act (modify the work and > > redistribute it) that has no technical reason to restrict, is > > artifically restricted. > > We agree that the restriction is artificial, and I think irrational > (although I'd be interested in hearing the gnuplot developers' reasoning > before making a final judgment). > > But I just don't see the requirement that modified software be > distributed in form X (original source + diffs) versus form Y (modified > source in a tar ball) or form Z (an rpm) to be that big a deal. Not > enough to make it "non-free software". > > I simply don't think that having to run some variation on > > patch -i patchfile.patch > > is a requirement so onerous that it makes the gnuplot licence non-free. > Perhaps I'm just more tolerant of eccentricities than you :) What you're missing is that for Free Software (TM) zealots it's a matter of philosophical principle, totally unrelated to how easy is to overcome the restriction. There is not a "practicality beats purity" clause in the FSF Bible. George -- http://mail.python.org/mailman/listinfo/python-list
XMLRPC - C Client / Python Server
I have implemented a simple Python XMLRPC server and need to call it from a C/C++ client. What is the simplest way to do this? I need to pass numerical arrays from C/C++ to Python. Yours, Carl -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding subsets for a robust regression
Thank you everyone, for your input. The help is much appreciated. Thomas Philips -- http://mail.python.org/mailman/listinfo/python-list
Re: Shed Skin (restricted) Python-to-C++ compiler 0.0.29
On Sep 30, 6:19 am, "Mark Dufour" <[EMAIL PROTECTED]> wrote: > Hi all, > > I have just released Shed Skin 0.0.29, with the following changes. Not to sound negative, but what's with the 0.0.x version numbers ? Maybe it's just me, but seeing a zero major/minor version give me the impression of experimental/pre-alpha project, which (from my very limited knowledge) doesn't do justice to shedskin's current state. Regardless, congrats for this great effort, hope it gains more prominence in the future! George -- http://mail.python.org/mailman/listinfo/python-list
Re: Python arrays and sting formatting options
On Tue, 30 Sep 2008 00:04:18 +0200, Ivan Rebori wrote: > > 1. Multi dimensional arrays - how do you load them in python > For example, if I had: > --- > 1 2 3 > 4 5 6 > 7 8 9 > > 10 11 12 > 13 14 15 > 16 17 18 > --- > with "i" being the row number, "j" the column number, and "k" the .. > uhmm, well, the "group" number, how would you load this ? > > If fortran90 you would just do: > > do 10 k=1,2 > do 20 i=1,3 > > read(*,*)(a(i,j,k),j=1,3) > > 20 continue > 10 continue > > How would the python equivalent go ? Since you're coming from the FORTRAN world (thank you for that stroll down Memory Lane), you might be doing scientific computations, and so might be interested in the SciPy package (Google scipy), which gives you arrays and matrices. Don't expect to be able to use it without learning some Python, though. -- To email me, substitute nowhere->spamcop, invalid->net. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python arrays and sting formatting options
On 2008-09-30, Peter Pearson <[EMAIL PROTECTED]> wrote: > On Tue, 30 Sep 2008 00:04:18 +0200, Ivan Rebori wrote: >> >> 1. Multi dimensional arrays - how do you load them in python >> For example, if I had: >> --- >> 1 2 3 >> 4 5 6 >> 7 8 9 >> >> 10 11 12 >> 13 14 15 >> 16 17 18 >> --- >> with "i" being the row number, "j" the column number, and "k" the .. >> uhmm, well, the "group" number, how would you load this ? >> >> If fortran90 you would just do: >> >> do 10 k=1,2 >> do 20 i=1,3 >> >> read(*,*)(a(i,j,k),j=1,3) >> >> 20 continue >> 10 continue >> >> How would the python equivalent go ? You would drag yourself out of the 1960s, install numpy, and then do something like this: a = read_array(open("filename.dat","r")) > Since you're coming from the FORTRAN world (thank you for that > stroll down Memory Lane), you might be doing scientific > computations, and so might be interested in the SciPy package > (Google scipy), which gives you arrays and matrices. Don't > expect to be able to use it without learning some Python, > though. If not full-up scipy (which provides all sorts of scientific and numerical-analysis stuff), then at least numpy (which provides the basic array/matrix operations: http://numpy.scipy.org/ Though the software is free, the documentation isn't. You've got to buy the book if you want something to read. IMO, it's definitely worth it, and a good way to support the project even if you don't really need something to keep your bookends apart. Scientific Python is something else the OP might be interested in. Yes, Scientific Python is different than SciPy: http://dirac.cnrs-orleans.fr/plone/software/scientificpython/overview/ If you're a Windows user, I can recommend the Enthough Python distribution. It has all sorts of numerical and scientific "batteries included". http://www.enthought.com/products/epd.php It includes both scipy and scientific python as well as several options for data visualization (e.g. matplotlib, VTK). There's also an Enthought Python distro for Linux, but I've never tried it. I run Gentoo Linux, and there are standard ebuilds for pretty much all of the stuff in EPD. -- Grant Edwards grante Yow! I've read SEVEN at MILLION books!! visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to add CC and BCC while sending mails using python
Hi, * cindy jones [2008-09-30 19:57]: > > Can someone tel me how to add cc's and bcc's while sending mails using > python Following (tested) snippet should help: -- 8< -- from smtplib import SMTP from email.mime.image import MIMEImage from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart to = '[EMAIL PROTECTED]' cc = '[EMAIL PROTECTED]' bcc = '[EMAIL PROTECTED]' msg = MIMEMultipart() msg['To'] = to msg['Cc'] = cc msg['From'] = '[EMAIL PROTECTED]' msg['Subject'] = 'Test' text = MIMEText('Das ist ein Test') text.add_header("Content-Disposition", "inline") msg.attach(text) s = SMTP('test.smtp.relay') s.sendmail(msg['From'], [to, cc, bcc], msg.as_string()) s.quit() -- >8 -- Regards, Bernhard -- http://mail.python.org/mailman/listinfo/python-list
Re: Python arrays and sting formatting options
On Tue, 30 Sep 2008 10:57:19 -0500, Grant Edwards wrote: > On 2008-09-30, Peter Pearson <[EMAIL PROTECTED]> wrote: >> On Tue, 30 Sep 2008 00:04:18 +0200, Ivan Rebori wrote: >>> >>> 1. Multi dimensional arrays - how do you load them in python For >>> example, if I had: >>> --- >>> 1 2 3 >>> 4 5 6 >>> 7 8 9 >>> >>> 10 11 12 >>> 13 14 15 >>> 16 17 18 >>> --- >>> with "i" being the row number, "j" the column number, and "k" the .. >>> uhmm, well, the "group" number, how would you load this ? >>> >>> If fortran90 you would just do: >>> >>> do 10 k=1,2 >>> do 20 i=1,3 >>> >>> read(*,*)(a(i,j,k),j=1,3) >>> >>> 20 continue >>> 10 continue >>> >>> How would the python equivalent go ? > > You would drag yourself out of the 1960s, install numpy, and then do > something like this: > >a = read_array(open("filename.dat","r")) In [64]: a = numpy.fromfile('test.txt', dtype=int, sep=' ') In [65]: a Out[65]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]) In [66]: a.reshape(2, 3, 3) Out[66]: array([[[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]]]) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python arrays and sting formatting options
On 30 Sep 2008 15:31:59 GMT, Peter Pearson <[EMAIL PROTECTED]> wrote: > >Since you're coming from the FORTRAN world (thank you for >that stroll down Memory Lane), you might be doing scientific >computations, and so might be interested in the SciPy >package (Google scipy), which gives you arrays and matrices. >Don't expect to be able to use it without learning some Python, >though. Actually, no (regarding memory lane :-). I'm helping a friend to translate some of my old routines to python so he can use them in his programs. I'm still using fortran84, and mean to continue doing so as long as something better doesn't come along. But as I said, got a job that't got to be done, so I'm trying to figure out how to do array operations as easily as possible in python, which are necessary for all my calculations. Best regards Ivan -- http://mail.python.org/mailman/listinfo/python-list
how to find out the version of a certain installed package
Hi, In a projecet I'm making using pycrypto, I need to find out the current installed version of pycrypto. After looking around, I found out that "pkg_resources.requires("pycrypto") will give me a string containing the version number, but is this the only way to do it or are there other ways? thanks, Christophe -- http://mail.python.org/mailman/listinfo/python-list
Re: how to find out the version of a certain installed package
On 2008-09-30 18:17, Christophe wrote: > Hi, > > In a projecet I'm making using pycrypto, I need to find out the > current installed version of pycrypto. After looking around, I found > out that "pkg_resources.requires("pycrypto") will give me a string > containing the version number, but is this the only way to do it or > are there other ways? Most packages have a .__version__ attribute in their top-level package dir which you can query. You do have to import the base package, though, in order to find out. Thanks, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 30 2008) >>> Python/Zope Consulting and Support ...http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 -- http://mail.python.org/mailman/listinfo/python-list
Re: XMLRPC - C Client / Python Server
On Tue, Sep 30, 2008 at 8:05 AM, <[EMAIL PROTECTED]> wrote: > I have implemented a simple Python XMLRPC server and need to call it > from a C/C++ client. What is the simplest way to do this? I need to > pass numerical arrays from C/C++ to Python. If you just googled for "xmlrpc c", you would've found http://xmlrpc-c.sourceforge.net/ , which appears to be the best (and possibly only) option for this. Also, this isn't really Python-related if you think about it. Regards, Chris -- Follow the path of the Iguana... http://rebertia.com > > Yours, Carl > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python arrays and sting formatting options
On 2008-09-30, Ivan Reborin <[EMAIL PROTECTED]> wrote: > But as I said, got a job that't got to be done, so I'm trying > to figure out how to do array operations as easily as possible > in python, which are necessary for all my calculations. numpy -- Grant Edwards grante Yow! TONY RANDALL! Is YOUR at life a PATIO of FUN?? visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: how to find out the version of a certain installed package
great! thanks for you fast response. Christophe On Tue, Sep 30, 2008 at 6:30 PM, M.-A. Lemburg <[EMAIL PROTECTED]> wrote: > On 2008-09-30 18:17, Christophe wrote: > > Hi, > > > > In a projecet I'm making using pycrypto, I need to find out the > > current installed version of pycrypto. After looking around, I found > > out that "pkg_resources.requires("pycrypto") will give me a string > > containing the version number, but is this the only way to do it or > > are there other ways? > > Most packages have a .__version__ attribute in their top-level > package dir which you can query. > > You do have to import the base package, though, in order to find > out. > > Thanks, > -- > Marc-Andre Lemburg > eGenix.com > > Professional Python Services directly from the Source (#1, Sep 30 2008) > >>> Python/Zope Consulting and Support ...http://www.egenix.com/ > >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ > >>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ > > > Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! > > > eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 >D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg > Registered at Amtsgericht Duesseldorf: HRB 46611 > -- http://mail.python.org/mailman/listinfo/python-list
r""
Is there a way to use the 'r' in front of a variable instead of directly in front of a string? Or do I need to use a function to get all of the slashes automatically fixed? /thanks -Kyle -- http://mail.python.org/mailman/listinfo/python-list
OS.SYSTEM ERROR !!!
To All, I have been attempting to execute the following program within the Python environment: Myprogram.exe, which means this is an executable file!! I would usually execute this program (with the appropriate arguments) by going to following directory within MS-DOS (Windows XP): C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 The executable would execute perfectly. However, when I would try to execute the following lines of source code within a python script file: import os os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") The executable file would start to execute until it would print an error stating that it cannot use a (.dat) file, which is located under the following directory: C:\myprogramfolder\run\inputs\io\control.dat I believe I may be missing something here that prevents the executable file working within python from utilizing this (.dat). The printed final error is the following: ERROR opening inputs/io/control.dat Does anyone know what that could be ?? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: r""
Kyle Hayes wrote: > Is there a way to use the 'r' in front of a variable instead of > directly in front of a string? Or do I need to use a function to get > all of the slashes automatically fixed? Please describe the actual problem you're trying to solve. In what way do slashes need to be "fixed," and why? -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: OS.SYSTEM ERROR !!!
Blubaugh, David A. wrote: > To All, > > > I have been attempting to execute the following program within the > Python environment: > > Myprogram.exe, which means this is an executable file!! > > I would usually execute this program (with the appropriate arguments) by > going to following directory within MS-DOS (Windows XP): > > C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 > > > The executable would execute perfectly. > > > However, when I would try to execute the following lines of source code > within a python script file: > > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") > > > The executable file would start to execute until it would print an error > stating that it cannot use a (.dat) file, which is located under the > following directory: > > > C:\myprogramfolder\run\inputs\io\control.dat > > > I believe I may be missing something here that prevents the executable > file working within python from utilizing this (.dat). The printed > final error is the following: > > ERROR opening inputs/io/control.dat > > Does anyone know what that could be ?? The program (myprogram.exe) is not looking for C:\myprogramfolder\run\inputs\io\control.dat, it's looking for inputs/io/control.dat relative to its current working directory. That will only work if the current working directory of the program is C:\myprogramfolder\run. Is it? -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: OS.SYSTEM ERROR !!!
On Sep 30, 1:21 pm, "Blubaugh, David A." <[EMAIL PROTECTED]> wrote: > I would usually execute this program (with the appropriate arguments) by > going to following directory within MS-DOS (Windows XP): > > C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 [snip] > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") [snip] > ERROR opening inputs/io/control.dat [snip] I would add the following line right before your call to os.system: os.chdir(r'C:\myprogramfolder\run') If you have to change directories to run it properly in the Windows shell, then you need to do it in Python, too. HTH, Geoff G-T -- http://mail.python.org/mailman/listinfo/python-list
Re: r""
> Please describe the actual problem you're trying to solve. In what way > do slashes need to be "fixed," and why? Well, I have decided to build a tool to help us sync files in UNC paths. I am just building the modules and classes right now so I haven't developed the frontend yet. I am assuming when the user provides a path (either by typing it in, or pulling it in from a config file), the UNC slashes are going to escape stuff in the string, so I want to double them up. I understand if the best way is to convert all the slashes to double- slashes. But the 'r' function seemed so handy and convenient. I am very new to Python, but not at all to programming. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: r""
On Sep 30, 1:17 pm, Kyle Hayes <[EMAIL PROTECTED]> wrote: > Is there a way to use the 'r' in front of a variable instead of > directly in front of a string? Or do I need to use a function to get > all of the slashes automatically fixed? Is this what you're talking about? str = "foo/bar" re = Regexp.new(str) => /foo\/bar/ -- Mark. -- http://mail.python.org/mailman/listinfo/python-list
Problems with encoding/decoding locales
Hi there, I'm using a python script in conjunction with a JPype, to run java classes. So, here's the code: from jpype import * import os import random import math import sys input = open('foo.img','rb').read().decode('ISO-8859-1') square = java.encoding(input) output = java.decoding() fd = open('foo_decode.img','wb') fd.write(output.encode('ISO-8859-1')) fd.close() sys.exit(0) First of all, java.encoding and java.decoding are two methods that respectively take a java string as an argument and return a java String. JPype is the bridge between Java and Python, and converts automatically a str or unicode pythonstring into a Java String. So, input and output are two unicode strings. I were forced to use decode() and encode() methods by python, otherwise it refuses to read foo.img file. Here's the strange behaviour: when I write the output in the 'foo_decode.img', I don't reassemble the original file; I already tested the java encoding/decoding libraries with the same input file, and what the decoding process returns is the original file. I suspect that the discrepancy is due to encoding/decoding of ISO-8859-1: is that required? What do you think about? Thank you -- http://mail.python.org/mailman/listinfo/python-list
Would this be called a bug in inspect ?
hello, I'm not familiar with inspect, but I get an error (see below) in getmembers ( wx ) Of course this is bug in wx . But would you also call this a bug in inspect ? (inspect crashes and doesn't continue with th rest of the code, nor it returns the already gathered data) thanks, Stef >>> import wx >>> wx.version() '2.8.7.1 (msw-unicode)' >>> from inspect import * >>> getmembers(wx) Traceback (most recent call last): File "", line 1, in File ")>)>>", line 517, in pphook File "P:\Python\Lib\pprint.py", line 55, in pprint printer.pprint(object) File "P:\Python\Lib\pprint.py", line 106, in pprint self._format(object, self._stream, 0, 0, {}, 0) File "P:\Python\Lib\pprint.py", line 129, in _format rep = self._repr(object, context, level - 1) File "P:\Python\Lib\pprint.py", line 195, in _repr self._depth, level) File "P:\Python\Lib\pprint.py", line 207, in format return _safe_repr(object, context, maxlevels, level) File "P:\Python\Lib\pprint.py", line 283, in _safe_repr orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level) File "P:\Python\Lib\pprint.py", line 283, in _safe_repr orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level) File "P:\Python\Lib\pprint.py", line 292, in _safe_repr rep = repr(object) File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 242, in __repr__ def __repr__(self): return 'wx.Colour' + str(self.Get(True)) File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 230, in Get return _gdi_.Colour_Get(*args, **kwargs) TypeError: in method 'Colour_Get', expected argument 1 of type 'wxColour *' -- http://mail.python.org/mailman/listinfo/python-list
Re: r""
Kyle Hayes wrote: >> Please describe the actual problem you're trying to solve. In what way >> do slashes need to be "fixed," and why? > > Well, I have decided to build a tool to help us sync files in UNC > paths. I am just building the modules and classes right now so I > haven't developed the frontend yet. I am assuming when the user > provides a path (either by typing it in, or pulling it in from a > config file), the UNC slashes are going to escape stuff in the string, > so I want to double them up. That assumption is incorrect. While backslashes in string literals are escape characters that must be doubled up to convey literal backslashes, no such interpretation is made for backslashes that are read from a GUI text box or from a file. See for yourself: >>> some_string = raw_input("Enter a string: ") Enter a string: blah\blah\blah >>> print some_string blah\blah\blah Carry on and come back when you actually have a problem ;) -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
IDLE doesn't run on OSX 10.3.9
Just installed Python 2.5.2 on a PowerPC G4 running OSX 10.3.9 and when clicking on the IDLE icon in the MacPython 2.5 folder nothing happens, program doesn't execute... I've uninstalled, reinstalled over again... I friend of mine just installed the same 2.5.2 download from the Python.org website on OSX 10.4.11 and all went fine...but shouldn't it install on 10.3.9 as well? Anyone have any ideas? Thanks. -Tom -- http://mail.python.org/mailman/listinfo/python-list
Re: OS.SYSTEM ERROR !!!
Blubaugh, David A. wrote: To All, I have been attempting to execute the following program within the Python environment: Myprogram.exe, which means this is an executable file!! I would usually execute this program (with the appropriate arguments) by going to following directory within MS-DOS (Windows XP): C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 The executable would execute perfectly. However, when I would try to execute the following lines of source code within a python script file: import os os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") Try this: import subprocess retval = subprocess.call( ['Myprogram.exe', '1', '1', 'acc', '0'], cwd='C:\myprogramfolder\run') Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: OS.SYSTEM ERROR !!!
Blubaugh, David A. wrote: > To All, > > I have been attempting to execute the following program within the > Python environment: > > However, when I would try to execute the following lines of source code > within a python script file: > > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") > > > I believe I may be missing something here that prevents the executable > file working within python from utilizing this (.dat). The printed > final error is the following: > > ERROR opening inputs/io/control.dat > > Does anyone know what that could be ?? Based on your description, it seems pretty obvious (and easy to confirm) that Myprogram.exe needs to be run from its containing directory ("C:\myprogramfolder\run"). Try something like this... import os pwd = os.getcwd() os.chdir('c:/myprogramfolder/run') os.system("Myprogram.exe 1 1 acc 0") os.chdir(pwd) HTH, Marty -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] Replacing cmd.exe with custom .py application
Joseph: Check out subprocess. The subprocess module is on python 2.4. Also, use subprocess.call("your command",shell=True) On Linux/Unix, the process is below import subprocess ret = subprocess.call("dir",shell=True,stdout=open('/dev/null','w'),stderr=subprocess.STDOUT) print ret You should get a return value of 0. Which means that it was successful. I'm still learning this myself, so some of these other guys might have more input. On Tue, Sep 30, 2008 at 10:32 AM, A. Joseph <[EMAIL PROTECTED]> wrote: > > > Instead of going to the command line all the time, I want to create a small > customized cmd.exe of my own, how can I get the return value from > os.system() because I was thinking I can do soothing with os.system(), In > case my question is not clear, just like an IDE that plugged in another > .exe application. > > > > Sorry for any mistake in my question. Just help me if you can > > ___ > Tutor maillist - [EMAIL PROTECTED] > http://mail.python.org/mailman/listinfo/tutor > > -- Ezra Taylor -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Tuesday 30 September 2008 16:04:35 George Sakkis wrote: > What you're missing is that for Free Software (TM) zealots it's a > matter of philosophical principle, totally unrelated to how easy is to > overcome the restriction. There is not a "practicality beats purity" > clause in the FSF Bible. The gnuplot license is a free software according to FSF, what is the problem here after all? > George -- José Abílio -- http://mail.python.org/mailman/listinfo/python-list
Re: OS.SYSTEM ERROR !!!
[EMAIL PROTECTED] wrote: I would add the following line right before your call to os.system: os.chdir(r'C:\myprogramfolder\run') I wouldn't. os.chdir() tends to introduce all sorts of trouble. It's a quick n'dirty hack for a small script but no solution for a large program or library. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
Steven D'Aprano wrote: On Tue, 30 Sep 2008 22:19:57 +1000, Ben Finney wrote: I do, because a natural, beneficial act (modify the work and redistribute it) that has no technical reason to restrict, is artifically restricted. We agree that the restriction is artificial, and I think irrational (although I'd be interested in hearing the gnuplot developers' reasoning before making a final judgment). I believe it is a matter of preserving clarity of authorship, just as is the quoting mechanism we take for granted in posts like this. If I removed the quote marks above and silently edited what Ben and you wrote, I might upset someone and certainly could confuse readers. tjr -- http://mail.python.org/mailman/listinfo/python-list
RE: OS.SYSTEM ERROR !!!
Thank You!! I am still new to Python!! David Blubaugh -Original Message- From: Christian Heimes [mailto:[EMAIL PROTECTED] Sent: Tuesday, September 30, 2008 2:08 PM To: python-list@python.org Subject: Re: OS.SYSTEM ERROR !!! Blubaugh, David A. wrote: > To All, > > > I have been attempting to execute the following program within the > Python environment: > > Myprogram.exe, which means this is an executable file!! > > I would usually execute this program (with the appropriate arguments) > by going to following directory within MS-DOS (Windows XP): > > C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 > > > The executable would execute perfectly. > > > However, when I would try to execute the following lines of source > code within a python script file: > > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") Try this: import subprocess retval = subprocess.call( ['Myprogram.exe', '1', '1', 'acc', '0'], cwd='C:\myprogramfolder\run') Christian This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -- http://mail.python.org/mailman/listinfo/python-list
RE: OS.SYSTEM ERROR !!!
Yes, I new it was a directory issue. I am new to Python. Thank You David Blubaugh -Original Message- From: Martin Walsh [mailto:[EMAIL PROTECTED] Sent: Tuesday, September 30, 2008 1:42 PM To: python-list@python.org Subject: Re: OS.SYSTEM ERROR !!! Blubaugh, David A. wrote: > To All, > > I have been attempting to execute the following program within the > Python environment: > > However, when I would try to execute the following lines of source > code within a python script file: > > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") > > > I believe I may be missing something here that prevents the executable > file working within python from utilizing this (.dat). The printed > final error is the following: > > ERROR opening inputs/io/control.dat > > Does anyone know what that could be ?? Based on your description, it seems pretty obvious (and easy to confirm) that Myprogram.exe needs to be run from its containing directory ("C:\myprogramfolder\run"). Try something like this... import os pwd = os.getcwd() os.chdir('c:/myprogramfolder/run') os.system("Myprogram.exe 1 1 acc 0") os.chdir(pwd) HTH, Marty This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE doesn't run on OSX 10.3.9
[EMAIL PROTECTED] wrote: Just installed Python 2.5.2 on a PowerPC G4 running OSX 10.3.9 and when clicking on the IDLE icon in the MacPython 2.5 folder nothing happens, program doesn't execute... I've uninstalled, reinstalled over again... I friend of mine just installed the same 2.5.2 download from the Python.org website on OSX 10.4.11 and all went fine...but shouldn't it install on 10.3.9 as well? Anyone have any ideas? Thanks. -Tom Do you have Tcl/Tk installed? It doesn't come on 10.3.9 by default. -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: r""
On Tue, 30 Sep 2008 10:50:01 -0700, Kyle Hayes wrote: >> Please describe the actual problem you're trying to solve. In what way >> do slashes need to be "fixed," and why? > > Well, I have decided to build a tool to help us sync files in UNC paths. > I am just building the modules and classes right now so I haven't > developed the frontend yet. I am assuming when the user provides a path > (either by typing it in, or pulling it in from a config file), the UNC > slashes are going to escape stuff in the string, so I want to double > them up. > > I understand if the best way is to convert all the slashes to double- > slashes. But the 'r' function seemed so handy and convenient. You don't need to. Python's string is never escaped in-memory, it is only escaped when repr(s) is called (the interpreter's implicit print uses repr () instead of str()). And that means all string coming and going to/from IO (file, GUI, etc) is stored as-is. However, strings that comes from source code or interpreter prompt (a.k.a. literal string) needs to be escaped. Analogy: When you're writing a string in the source code, you add double quotes (""), right? But do you think the quotes are stored in memory? No, it's just an escape character to differentiate a string from its surrounding. -- http://mail.python.org/mailman/listinfo/python-list
pylab without X11
I want to use pylab (matplotlib) on a machine without X11. I'm trying to generate onthefly graphics for an apache2 web service, so they do not have to be displayed on this machine ! When i do pylab.figure() I get the error TclError: couldn't connect to display ":0.0" I tried setting the DISPLAY environment variable to "", ":0.0" but I got the same error message. Any help is very much appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: rlcompleter and wxPython, problems ...
Gabriel Genellina wrote: En Sun, 28 Sep 2008 19:25:30 -0300, Stef Mientki <[EMAIL PROTECTED]> escribió: I'm trying to implement autocompletion into my editor. But I find some weird behavior, or at least I don't have the faintest idea why this behavior occures, and even more important how to solve it In the example below I try to autocomplete " wx.s" , which in my humble opinion should at least produce "wx.stc" (and some others ). wx is a package. Modules within the package are not, by default, attributes of the package - unless they're imported in __init__.py or your code imports them. So the autocompleter is doing the right thing in what perspective ? the autocompleter is only meant to assist the program writer ;-) - wx.stc does not exist until it is explicitely imported. I guess I've to study the package. For the moment I'll implement a user editable list of additions. But with your remarks I tried __all__ And now I wonder why rlcompleter is not simply using "wx.__all__", it than does gets all the items ? cheers, Stef -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing float and decimal
Mark Dickinson wrote: On Sep 30, 9:21 am, Terry Reedy <[EMAIL PROTECTED]> wrote: If no one beats me to it, I will probably file a bug report or two, but I am still thinking about what to say and to suggest. I can't see many good options here. Some possibilities: Thanks for responding. Agreeing on a fix would make it more likely to happen sooner ;-) (0) Do nothing besides documenting the problem somewhere (perhaps in a manual section entitled 'Infrequently Asked Questions', or 'Uncommon Python Pitfalls'). I guess the rule is simply that Decimals don't mix well with other numeric types besides integers: if you put both floats and Decimals into a set, or compare a Decimal with a Fraction, you're asking for trouble. I suppose the obvious place for such a note would be in the decimal documentation, since non-users of decimal are unlikely to encounter these problems. Documenting the problem properly would mean changing the set documentation to change at least the definitions of union (|), issubset (<=), issuperset (>=), and symmetric_difference (^) from their current math set based definitions to implementation based definitions that describe what they actually do instead of what they intend to do. I do not like this option. (1) 'Fix' the Decimal type to do numerical comparisons with other numeric types correctly, and fix up the Decimal hash appropriately. (1A) All that is needed for fix equality transitivity corruption and the consequent set/dictview problems is to correctly compare integral values. For this, Decimal hash seems fine already. For the int i I tried, hash(i) == hash(float(i)) == hash(Decimal(i)) == hash(Fraction(i)) == i. It is fine for transitivity that all fractional decimals are unequal to all fractional floats (and all fractions) since there is no integer (or fraction) that either is equal to, let alone both. This is what I would choose unless there is some 'hidden' problem. But it seem to me this should work: when a float and decimal are both integral (easy to determine) convert either to an int and use the current int-whichever comparison. (2) I wonder whether there's a way to make Decimals and floats incomparable, so that an (in)equality check between them always raises an exception, and any attempt to have both Decimals and floats in the same set (or as keys in the same dict) also gives an error. (Decimals and integers should still be allowed to mix happily, of course.) But I can't see how this could be done without adversely affecting set performance. I pretty strongly believe that equality checks should always work (at least in Python as delivered) just as boolean checks should (and do). Option (1) is certainly technically feasible, but I don't like it much: it means adding a whole load of code to the Decimal module that benefits few users but slows down hash computations for everyone. And then any new numeric type that wants to fit in with Python's rules had better worry about hashing equal to ints, floats, Fractions, complexes, *and* Decimals... I believe (1A) would be much easier both to implement and for new numeric types. Option (2) appeals to me, but I can't see how to implement it. So I guess that just leaves updating the docs. Other thoughts? (3) Further isolate decimals by making decimals also unequal to all ints. Like (1A), this would easily fix transitivity breakage, but I would consider the result less desirable. My ranking: 1A > 3 > 0 > 2. I might put 1 between 1A and 3, but I am not sure. Mark Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Change environment after setreuid
I have a program (which normally runs as root) which can start child processes as different users. Effectively, my program is a modified version of popen2's Popen3 class where the child process (after the fork) does: os.setregid (gid, gid) os.setreuid (uid, uid) session_pid = os.setsid () This all seems to work. However, I am running into a problem where the environment of the new process still carries values that were set before the setreuid() call. What would be the best way to go about modifying the environment without having to re-implement all the functionality of the 'su' command? I could use it (the 'su' command) to start the new process but I'd like to avoid external dependencies like that. Thank you -- Mitko Haralanov == The program isn't debugged until the last user is dead. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] Replacing cmd.exe with custom .py application
Is there something similar to /dev/null on Windows? On Tue, Sep 30, 2008 at 2:13 PM, Ezra Taylor <[EMAIL PROTECTED]> wrote: > Joseph: > Check out subprocess. The subprocess module is on python > 2.4. Also, use subprocess.call("your command",shell=True) > > On Linux/Unix, the process is below > > import subprocess > > ret = > subprocess.call("dir",shell=True,stdout=open('/dev/null','w'),stderr=subprocess.STDOUT) > > print ret > > You should get a return value of 0. Which means that it was > successful. I'm still learning this myself, so some of these other > guys might have more input. > > > > > > On Tue, Sep 30, 2008 at 10:32 AM, A. Joseph <[EMAIL PROTECTED]> wrote: >> >> >> Instead of going to the command line all the time, I want to create a small >> customized cmd.exe of my own, how can I get the return value from >> os.system() because I was thinking I can do soothing with os.system(), In >> case my question is not clear, just like an IDE that plugged in another >> .exe application. >> >> >> >> Sorry for any mistake in my question. Just help me if you can >> >> ___ >> Tutor maillist - [EMAIL PROTECTED] >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > > -- > Ezra Taylor > -- Ezra Taylor -- http://mail.python.org/mailman/listinfo/python-list
Re: What is not objects in Python?
En Tue, 30 Sep 2008 08:07:18 -0300, Steve Holden <[EMAIL PROTECTED]> escribió: Terry Reedy wrote: Steven D'Aprano wrote: Arghh! No!!! |x| should be abs(x), not len(x). Just ask mathematicians and physicists. It should be both, just as + is addition for numbers and concatenation for sequences. Or we could have just one built-in -- size() instead of abs() and len(). For non-sequence collections, size() would be better than len() anyway. And how are these "non-sequence collections" to be distinguished? And how does size() differ from len() in that case? Consider a tree, or a graph. The number of elements they have is not naturally described as their "length", the usual term is "size" instead. "Length" is adequate for one-dimensional structures only; even len(dict) is a bit controversial. Had Python used the more generic size and __size__ from the beginning, we'd be all happy now :) But it's too late to change things. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: OS.SYSTEM ERROR !!!
Blubaugh, David A. wrote: To All, I have been attempting to execute the following program within the Python environment: Myprogram.exe, which means this is an executable file!! I would usually execute this program (with the appropriate arguments) by going to following directory within MS-DOS (Windows XP): C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 The executable would execute perfectly. Because you execute it in the necessary directory. However, when I would try to execute the following lines of source code within a python script file: import os os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") This does not execute it in the proper directory. os.getcwd() will tell you where you are -- mostly likely .../Pythonx.y. Try: os.chdir("C:/myprogramfolder/run") # / works fine, and without r prefix os.system("Myprogram.exe 1 1 acc 0") The executable file would start to execute until it would print an error stating that it cannot use a (.dat) file, which is located under the following directory: C:\myprogramfolder\run\inputs\io\control.dat I believe I may be missing something here that prevents the executable file working within python from utilizing this (.dat). The printed final error is the following: ERROR opening inputs/io/control.dat Does anyone know what that could be ?? That file does not exist in the Pythonx.y directory where the program starts ;-). tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Would this be called a bug in inspect ?
En Tue, 30 Sep 2008 14:57:55 -0300, Stef Mientki <[EMAIL PROTECTED]> escribió: I'm not familiar with inspect, but I get an error (see below) in getmembers ( wx ) Of course this is bug in wx . Yes. But would you also call this a bug in inspect ? (inspect crashes and doesn't continue with th rest of the code, nor it returns the already gathered data) getmembers works fine; try m=getmembers(wx) and see. It fails when you attemp to print (or pprint) the returned list. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] Replacing cmd.exe with custom .py application
On Tue, 30 Sep 2008 15:09:06 -0400, Ezra Taylor wrote: > Is there something similar to /dev/null on Windows? I think it's called nul REM This is a batch file (.bat) echo "This won't show" > NUL I'm not sure how to use it in python though. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] Replacing cmd.exe with custom .py application
On Tue, 30 Sep 2008 19:30:55 + (UTC), Lie Ryan <[EMAIL PROTECTED]> wrote: On Tue, 30 Sep 2008 15:09:06 -0400, Ezra Taylor wrote: Is there something similar to /dev/null on Windows? I think it's called nul REM This is a batch file (.bat) echo "This won't show" > NUL I'm not sure how to use it in python though. Check out os.devnull. You can open it and write to it. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: OS.SYSTEM ERROR !!!
Blubaugh, David A. wrote: > Thank You!! > > I am still new to Python!! > > David Blubaugh As you've already noticed, plenty of folks here on the list are ready help you out with issues the crop up as you learn python. So keep on asking questions as you need assistance. In the future, please avoid using all-capital letters and superfluous exclamation marks in the subject line as this comes across in the parlance of nntp- and mailing- list etiquette as yelling. If you don't get any replies to your posts, please just be patient and the gurus will get to them eventually. I have found this list to be extremely good that way, and almost all my questions have been politely answered, even if it took a few days. I hope you continue to find your python learning experience to be fun and profitable. -- http://mail.python.org/mailman/listinfo/python-list
Re: XMLRPC - C Client / Python Server
[EMAIL PROTECTED] wrote: > I have implemented a simple Python XMLRPC server and need to call it > from a C/C++ client. What is the simplest way to do this? I need to > pass numerical arrays from C/C++ to Python. Which do you need, C or C++? They are two different languages with different possibilities for libraries. As the other poster mentioned, xmlrpc-c is a good one for C, and also comes with bindings for C++ which I have used. Getting xmlrpc-c compiled can be a real challenge though. I recommend you use binary packages for your distribution of Linux. If you need it on Win32, then you'll have to spend a day or two figuring out how to build it on Windows. I eventually got the both the C and C++ client library built in Mingw with libcurl as the transport. But it was a real pain. -- http://mail.python.org/mailman/listinfo/python-list
Re: Would this be called a bug in inspect ?
Gabriel Genellina wrote: En Tue, 30 Sep 2008 14:57:55 -0300, Stef Mientki <[EMAIL PROTECTED]> escribió: I'm not familiar with inspect, but I get an error (see below) in getmembers ( wx ) Of course this is bug in wx . Yes. But would you also call this a bug in inspect ? (inspect crashes and doesn't continue with th rest of the code, nor it returns the already gathered data) getmembers works fine; try m=getmembers(wx) and see. REALLY GREAT ! It fails when you attemp to print (or pprint) the returned list. But this is fully beyond my understanding: m = getmembers ( wx ) print m runs fine print getmembers ( wx ) crashes but not always: >>> print getmembers (wx) [('ACCEL_ALT', 1), ('ACCEL_CMD', 2), ('ACCEL_CTRL', 2), ('ACCEL_NORMAL', 0), ('ACCEL_SHIFT', 4), ('ADJUST_MINSIZE', 0), ( And to make it even weirder, now I can let your suggestion crash too >>> m=getmembers(wx) >>> print getmembers (wx) Traceback (most recent call last): File "", line 1, in File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 242, in __repr__ def __repr__(self): return 'wx.Colour' + str(self.Get(True)) File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 230, in Get return _gdi_.Colour_Get(*args, **kwargs) TypeError: in method 'Colour_Get', expected argument 1 of type 'wxColour *' >>> print m Traceback (most recent call last): File "", line 1, in File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 242, in __repr__ def __repr__(self): return 'wx.Colour' + str(self.Get(True)) File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 230, in Get return _gdi_.Colour_Get(*args, **kwargs) TypeError: in method 'Colour_Get', expected argument 1 of type 'wxColour *' ?? thanks, Stef -- http://mail.python.org/mailman/listinfo/python-list
Re: rlcompleter and wxPython, problems ...
En Tue, 30 Sep 2008 16:06:07 -0300, Stef Mientki <[EMAIL PROTECTED]> escribió: Gabriel Genellina wrote: En Sun, 28 Sep 2008 19:25:30 -0300, Stef Mientki <[EMAIL PROTECTED]> escribió: I'm trying to implement autocompletion into my editor. But I find some weird behavior, or at least I don't have the faintest idea why this behavior occures, and even more important how to solve it In the example below I try to autocomplete " wx.s" , which in my humble opinion should at least produce "wx.stc" (and some others ). wx is a package. Modules within the package are not, by default, attributes of the package - unless they're imported in __init__.py or your code imports them. So the autocompleter is doing the right thing in what perspective ? the autocompleter is only meant to assist the program writer ;-) It's hard to write an autocompleter that does the right thing in all cases :) For a package, you have several sources for possibly valid attributes: - its dir() (that is, the package object's own attributes) - the __all__ attribute, when it exists - the list of modules inside the package directory or directories (given by its __path__ attribute) Sometimes __init__.py is empty - and enumerating the modules inside the directory is the right thing to do. Sometimes the author explicitely imports things in __init__.py, things that comprise the public interfase to the package. In that case I'd not like to see "private" modules appearing in the list. Combine with __all__, which might be defined or not. Mix all those, choose your own autocomplete algorithm, and see what happens... - wx.stc does not exist until it is explicitely imported. I guess I've to study the package. For the moment I'll implement a user editable list of additions. But with your remarks I tried __all__ And now I wonder why rlcompleter is not simply using "wx.__all__", it than does gets all the items ? __all__ isn't always defined. It's only used when you do "from xxx import *" AFAIK. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list