Re: Difference in Python and Ruby interactive shells
Alex Martelli wrote: > Michele Simionato <[EMAIL PROTECTED]> wrote: > >> You want this recipe from Michael Hudson: >> >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 >> >> "automatically upgrade class instances on reload()" > > Note that the version in the printed Cookbook (2nd edition) was > substantially enhanced (mostly by me and Michael working together), I > don't know if Michael updated his ASPN recipe to reflect that but at any > rate you can download all the code from the printed Cookbook as a > zipfile from O'Reilly's site (sorry, I don't recall the URL). http://examples.oreilly.com/pythoncook2/cb2_examples.zip The files are named cb2_6_21_*.py, but the book has the recipe in chapter 20.15. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib.urlencode wrongly encoding ± character
Ok, I think this code snippet enough to show what i said; === #!/usr/bin/env python # -*- coding: utf-8 -*- #Change utf-8 to latin-1 #Or move variable decleration to another file than import it val='00090±NO:±H±H±H±H±' from urllib import urlencode data={'key':val} print urlencode(data) === -- http://mail.python.org/mailman/listinfo/python-list
subprocess freeze with rsync on windows
Hi, I try to call rsync (with ssh) with subprocess but _some times_ it freeze without traceback, without any reason. My code look like that : def sh(self,cmd): log.debug("S cmd: " + " ".join(cmd)) p = Popen(cmd, stdout = PIPE, stderr = PIPE) stdout, stderr = p.communicate() if stdout: log.debug("S ret: %s" % stdout) if stderr: log.error("S err: %s" % stderr) return p.returncode When it freeze i need to kill the ms-dos console by hand. I've no problem on linux with the same script. thanks the complet script (doing rsync and cp -al on the remote side) is available freely here : http://flibuste.net/libre/snapy (but documentation is in french) -- William Dodé - http://flibuste.net -- http://mail.python.org/mailman/listinfo/python-list
Re: pre-PEP: The create statement
I think looking at the occurrences in the standard library only is unfair. I have a large "Zope +Plone+my stuff" installation and I get 154 occurrences of 'create' but nearly 0 occurrences of 'make' (only a few in Zope/lib/python/BTrees/tests/testSetOps.py). I guess 'make' sounds too Lispy, this is why it is never used in Pythonland. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
ftplib question
hi my purpose is just to connect to an FTP server and delete all files in a directory Is there a way using ftplib module? something like ftp.delete("*") ? another way i can do is using LIST to list out all the files in that directory, grab the filename, append to an array, then do a for loop to delete one by one. using the ftplib retrlines('LIST') , it shows me all the lines with -rw-r--r-- 1 user grp 6302 Apr 7 15:30 some file how can i get only the filename? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib.urlencode wrongly encoding � character
Evren Esat Ozkan wrote: > Ok, I think this code snippet enough to show what i said; > > === > > #!/usr/bin/env python > # -*- coding: utf-8 -*- > #Change utf-8 to latin-1 > #Or move variable decleration to another file than import it > > val='00090±NO:±H±H±H±H±' > > from urllib import urlencode > > data={'key':val} > > print urlencode(data) > > === did you cut and paste this into your mail program? because the file I got was ISO-8859-1 encoded: Content-Type: text/plain; charset="iso-8859-1" and uses a single byte to store each "±", and produces key=00090%B1NO%3A%B1H%B1H%B1H%B1H%B1 when I run it, which is the expected result. I think you're still not getting what's going on here, so let's try again: - the urlencode function doesn't care about encodings; it translates the bytes it gets one by one. if you pass in chr(0xB1), you get %B1 in the output. - it's your editor that decides how that "±" you typed in the original script are stored on disk; it may use one ISO-8859-1 bytes, two UTF-8 bytes, or something else. - the coding directive doesn't affect non-Unicode string literals in Python. in an 8-bit string, Python only sees a number of bytes. - the urlencode function only cares about the bytes. since you know that you want to use ISO-8859-1 encoding for your URL, and you seem to insist on typing the "±" characters in your code, the most portable (and editor-independent) way to write your code is to use Unicode literals when building the string, and explicitly convert to ISO-8859-1 on the way out. # build the URL as a Unicode string val = u'00090±NO:±H±H±H±H±' # encode as 8859-1 (latin-1) val = val.encode("iso-8859-1") from urllib import urlencode data={'key':val} print urlencode(data) key=00090%B1NO%3A%B1H%B1H%B1H%B1H%B1 this will work the same way no matter what character set you use to store the Python source file, as long as the coding directive matches what your editor is actually doing. if you want to make your code 100% robust, forget the idea of putting non-ascii characters in string literals, and use \xB1 instead: val = '00090\xb1NO:\xb1H\xb1H\xb1H\xb1H\xb1' # no need to encode, since the byte string is already iso-8859-1 from urllib import urlencode data={'key':val} print urlencode(data) key=00090%B1NO%3A%B1H%B1H%B1H%B1H%B1 hope this helps! -- http://mail.python.org/mailman/listinfo/python-list
Re: Partially unpacking a sequence
[EMAIL PROTECTED] wrote: > I have a list y > y > > ['20001201', 'ARRO', '04276410', '18.500', '19.500', '18.500', > '19.500', '224'] > > from which I want to extract only the 2nd and 4th item > > by partially > unpacking the list. So I tried > a,b = y[2,4] Mmm, so lovely and meaningful names !-) FWIW, and since nobody seemed to mention it, list indexes are zero-based, so the second element of a list is at index 1 and the fourth at index 3. Also, a GoodPractice(tm) is to use named constants instead of magic numbers. Here we don't have a clue about why these 2 elements are so specials. Looking at the example list (which - semantically - should be a tuple, not a list) I could wild-guess that the 2nd item is a reference and the fourth a price, so: REF_INDEX = 1 # lists are zero-based PRICE_INDEX = 3 ref, price = y[REF_INDEX], y[PRICE_INDEX] And finally, since this list is clearly structured data, wrapping it into an object to hide away implementation details *may* help - depending on the context, of course !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: recursion and linked lists
On 01/04/06, John Salerno <[EMAIL PROTECTED]> wrote: > I V wrote: > > > > Note that print gets called after _each_ time that printBackward > > returns. So, as the different calls to printBackward return, they print > > whatever 'head' was set to in that invocation. Now, logically enough, > > the last call to printBackward is the first to return, so the last > > value of 'head' is printed first, and so in in the reverse order of the > > list. > > Oh, that helps! Now I'm starting to understand when exactly it returns > each time. The way I got my head round this was to think of namespaces (I'm not sure how true this is though). I think of the first head variable as being: printBackward.head When it calls printBackward from within the first printBackward, thye second variable is: printBackward.printBackward.head and so on. It helps to keep it clear that they are entirely different. Ed -- http://mail.python.org/mailman/listinfo/python-list
Re: HTMLParser fragility
[Richie] > But Tidy fails on huge numbers of real-world HTML pages. [...] > Is there a Python HTML tidier which will do as good a job as a browser? [Walter] > You can also use the HTML parser from libxml2 [Paul] > libxml2 will attempt to parse HTML if asked to [...] See how it fixes > up the mismatching tags. Great! Many thanks. -- Richie Hindle [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Quickie: converting r"\x2019" to int
On Thu, 06 Apr 2006 20:00:13 +0200, Just wrote: > In article <[EMAIL PROTECTED]>, > Kent Johnson <[EMAIL PROTECTED]> wrote: > >> Robin Haswell wrote: >> Is this what you mean? >> In [9]: int(r'\x2019'[2:], 16) >> Out[9]: 8217 >> >> or maybe you meant this: >> In [6]: ord(u'\u2019') >> Out[6]: 8217 > > Or even: > > >>> import struct > >>> struct.unpack("q", "\0\0"+ r'\x2019')[0] > 101671307850041L > >>> [EMAIL PROTECTED]:~$ python Python 2.4.2 (#2, Sep 30 2005, 21:19:01) [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> int("\x2019") 19 >>> Something like that. Except with: >>> int(r"\x2019") Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): \x2019 >>> :-) -Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: how to make a generator use the last yielded value when it regains control
just couldn't help taking the bait... def morris(seed) : """ >>> m = morris('3447221') >>> m.next() '1324172211' >>> m.next() '1113121411172221' >>> m.next() '31131112111431173211' """ assert isinstance(seed,basestring) and seed.isdigit(),"bad seed" def itially(z) : feedback.z = z while True : yield feedback.z def feedback(gen) : while True : feedback.z = gen.next() yield feedback.z def morrisify(number) : from itertools import groupby for digit,sequence in groupby(number) : yield str(len(tuple(sequence))) yield digit return feedback(''.join(morrisify(number)) for number in itially(seed)) -- http://mail.python.org/mailman/listinfo/python-list
Re: "The World's Most Maintainable Programming Language"
Michael Yanowitz wrote: > > At-least Pythetic isn't a word (yet). > :))) "now that's quite pythetic !" hmmm, clearly that word could become damaging to python, so I suggest the best course is to preventively focus the meaning in a way that prevents the danger, by providing canonical examples of, hem, pythos, that will direct the contempt away from your beloved programming language. My contribution (2001) : filter(lambda W : W not in "ILLITERATE","BULLSHIT") -- http://mail.python.org/mailman/listinfo/python-list
Re: pre-PEP: The create statement
Serge Orlov wrote: > bruno at modulix wrote: > > Steven Bethard wrote: > > > The PEP below should be mostly self explanatory. I'll try to keep the > > > most updated versions available at: > > [snip] > > > > > Seems mostly clean. +1. > > > > That's what Trojans said when they saw a wooden horse at the gates of > Troy ;) > > Serge. QOTW! -- http://mail.python.org/mailman/listinfo/python-list
Re: Quickie: converting r"\x2019" to int
Robin Haswell wrote: > > [EMAIL PROTECTED]:~$ python > Python 2.4.2 (#2, Sep 30 2005, 21:19:01) > [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> int("\x2019") > 19 > >>> > > Something like that. Except with: > > >>> int(r"\x2019") > Traceback (most recent call last): > File "", line 1, in ? > ValueError: invalid literal for int(): \x2019 > >>> > > > :-) > > -Rob I decided to use this as a learning exercise for myself. This is what I figured out. All quotes are paraphrased from the docs. "\xhh in a string substitutes the character with the hex value hh. Unlike in Standard C, at most two hex digits are accepted." \x20 is equal to a space. Therefore '\x2019' is equal to ' 19'. "int(x) converts a string or number to a plain integer. If the argument is a string, it must contain a possibly signed decimal number representable as a Python integer, possibly embedded in whitespace." Therefore int(' 19') is equal to 19. "When an 'r' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string". Therefore r'\x2019' is left unchanged, and cannot be converted to an int. Rob, this explains *why* you are getting the above error. It does not explain how to achieve your objective, as you have not specified what it is. If you give more information, one of the resident gurus may be able to assist you. Frank Millman -- http://mail.python.org/mailman/listinfo/python-list
OT: job offering in Milan
My current employer is looking for a senior system administrator/programmer with good Python expertise. Notice that the job is in Milan, Italy and that we do not consider remote work. You can mail your CV and/or ask questions to [EMAIL PROTECTED] I can say this is a nice place to work ;) Here is the announcement. - Position Title Senior System Engineer The Company StatPro, a leader Company in the field of portfolio analytics for the global asset management market, is looking for a Senior Systems/Network Engineering Specialist, who is ready for a new challenge. Skills/Experience The ideal candidate should have Bachelor or Master Scientific degree and at least 5 years of experience in Linux and Microsoft Operating Systems as System Administrator. He/She will be able to manage the installation, configuration, tuning and troubleshooting servers (Microsoft, Linux and BSD), both for institutional services and for specific projects. He/She should also have skills in networking and previous experience with cluster environments on unix-like systems. The candidate will be asked to develop scripting procedures for automating common system tasks and for system and application monitoring purpose. Experience with the python programming language and relational databases is a plus. Attitude He/she should be a pro-active, quick-learner individual with strong initiative and good English communication skills. The offer The offered package is in line with the top market levels for the position. The working location is Milan. -- http://mail.python.org/mailman/listinfo/python-list
Re: Quickie: converting r"\x2019" to int
Robin Haswell wrote: > Hey guys. This should just be a quickie: I can't figure out how to convert > r"\x2019" to an int - could someone give me a hand please? >>> int(r'\x2019'.decode('string_escape')) 19 -- http://mail.python.org/mailman/listinfo/python-list
Best way to process table rows from an RDBMS
I can handle making the connections and running queries, but what's the best way to process table rows returned in Python? What about turning a table definition into an object? Just looking for ways to be efficient, since I know I will be hitting the same external RDBMS from Python and regularly processing a fixed set of tables with a certain fixed set of attribute columns. Is there something better than tuples for this? -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I get the text under the cusor ?
Alle 00:20, sabato 08 aprile 2006, Bo Yang ha scritto: > I want to develop an application to record some of the best words and > ideas On linux and KDE desktop is easy as a breathing, by Klipper applet:-) And also no virus prone like windowz. Pls no flame, just a consideration. F -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode, command-line and idle
[EMAIL PROTECTED] wrote: > Martin v. Löwis wrote: >> [EMAIL PROTECTED] wrote: >>> This works if I use the console but gives the following error if I use >>> IDLE: >>> >>> Traceback (most recent call last): >>> File "C:\test.py", line 4, in ? >>> text2 = unicode(raw_input(), sys.stdin.encoding) >>> AttributeError: PyShell instance has no attribute 'encoding' >> What operating system and Python version are you using? This ought to >> work. >> >> Regards, >> Martin > > Python 2.4.3 > IDLE 1.1.3 > Windows XP SP2 ?? Works for me on Win2K Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. IDLE 1.1.3 >>> import sys >>> sys.stdin.encoding 'cp1252' Kent -- http://mail.python.org/mailman/listinfo/python-list
passing argument to script
hi if i have a string like this "ABCE-123456 ABC_DEF_Suggest(abc def ghi).txt" that needs to be passed to a python script and i wanted to get the words inside the brackets after i passed this string. I did a re something like thestring = sys.argv[1:] pat = re.compile(r".*\((.*)\)\.txt$") if pat.search(thestring): words = pat.search(thestring).group(1) but it doesn't return anything for words variable. When i specifically define the string inside the python script , it works thestring = "ABCE-123456 ABC_DEF_Suggest(abc def ghi).txt" I also tried str(thestring) but also did not work what is wrong with the argument passing? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: passing argument to script
> hi > > if i have a string like this > > "ABCE-123456 ABC_DEF_Suggest(abc def ghi).txt" > > that needs to be passed to a python script > and i wanted to get the words inside the brackets after i passed this > string. I did a re > something like > > thestring = sys.argv[1:] > pat = re.compile(r".*\((.*)\)\.txt$") > if pat.search(thestring): >words = pat.search(thestring).group(1) > > but it doesn't return anything for words variable. > When i specifically define the string inside the python script , it > works > > thestring = "ABCE-123456 ABC_DEF_Suggest(abc def ghi).txt" > > I also tried str(thestring) but also did not work > what is wrong with the argument passing? Are you doing this on Linux or Windows? If you execute your script from the command line on Linux you need to enclose it in quotation marks otherwise your shell will interfere. So you need to invoke your program as python yourscript.py "ABCE-123456 ABC_DEF_Suggest(abc def ghi).txt" and need to refer to the argument as sys.argv[1:][0], so yourscript.py should be import sys, re thestring = sys.argv[1:][0] pat = re.compile(r".*\((.*)\)\.txt$") if pat.search(thestring): words = pat.search(thestring).group(1) print words I'm not sure what you need to do on Windows though. -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib.urlencode wrongly encoding ± character
I copied and pasted my code to new file and saved with utf-8 encoding. it produced 00090%C2%B1NO%3A%C2%B1H%C2%B1H%C2%B1H%C2%B1H%C2%B1 Than I added "u" to decleration and encode it with iso-8859-1 as you wrote and finally it produced proper result. Your reply is so helped and clarify some things about unicode string usage on Python. Thank you very much! -- http://mail.python.org/mailman/listinfo/python-list
performance degradation when looping through lists
I need to process large lists (in my real application, this is to parse the content of a file). I noticed that the performance to access the individual list elements degrades over runtime. This can be reproduced easily using this code: import time N=10 p=1 A=[] for i in range(N): A.append(str(i)) j = 0 t = time.clock() for i in range(len(A)): j += int(A[i]) if i % p == 0: t = time.clock() - t print t (the string conversion only servers to increase the duration of each iteration; you can observer the same effect with ints, too). When running this, I get output like this: 0.0 0.37 0.03 0.4 0.06 0.43 0.09 0.46 0.13 0.49 I use Python 2.3.4 (#1, Sep 3 2004, 12:08:45) [GCC 2.96 2731 (Red Hat Linux 7.3 2.96-110)] on linux2 I wonder why 1. The execution times alternate between "fast" and "slow" (I observe the same effect in my much more complex application) 2. The execution times increase steadily, from "0" to 0.13 for the "fast" phases, and from 0.37 to 0.49 for the slow phases. Within my application, the effect is more drastical as the following numbers show (the processing time per line is roughly the same for each line!): at line 1 (32258 lines/s) at line 2 (478 lines/s) at line 3 (21276 lines/s) at line 4 (475 lines/s) at line 5 (15873 lines/s) at line 6 (471 lines/s) at line 7 (12658 lines/s) at line 8 (468 lines/s) at line 9 (10638 lines/s) at line 10 (464 lines/s) at line 11 (9090 lines/s) at line 12 (461 lines/s) at line 13 (7936 lines/s) at line 14 (457 lines/s) at line 15 (7042 lines/s) at line 16 (454 lines/s) at line 17 (6369 lines/s) at line 18 (451 lines/s) at line 19 (5780 lines/s) at line 20 (448 lines/s) at line 21 (4854 lines/s) at line 22 (444 lines/s) at line 23 (4504 lines/s) at line 24 (441 lines/s) at line 25 (4201 lines/s) at line 26 (438 lines/s) at line 27 (3952 lines/s) at line 28 (435 lines/s) at line 29 (3717 lines/s) at line 30 (432 lines/s) at line 31 (3508 lines/s) at line 32 (429 lines/s) at line 33 (3322 lines/s) at line 34 (426 lines/s) at line 35 (3154 lines/s) at line 36 (423 lines/s) at line 37 (3003 lines/s) at line 38 (421 lines/s) at line 39 (2873 lines/s) Any ideas why this is like this, and what I could do about it? It really makes may application non-scalable as the lines/s go down even further. -- Joachim - reply to joachim at domain ccrl-nece dot de Opinion expressed is personal and does not constitute an opinion or statement of NEC Laboratories. -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: job offering in Milan
Michele Simionato wrote: .. > The Company > StatPro, a leader Company in the field of portfolio analytics for the > global asset management market, is looking for a Senior Systems/Network > Engineering Specialist, who is ready for a new challenge. > > real pity, I used to do portfolio analytics for Bita Plus and SBC; minimax risk curves were just my bag etc etc :). My math skills are now so degraded I have difficulty reading about conic programming using Nesterov's barrier functions etc etc. Oh well back to web scraping :( -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: Quickie: converting r"\x2019" to int
> Therefore r'\x2019' is left unchanged, and cannot be converted to an > int. > > Rob, this explains *why* you are getting the above error. It does not > explain how to achieve your objective, as you have not specified what > it is. If you give more information, one of the resident gurus may be > able to assist you. Thanks, I think that helps. Basically I'm decoding HTML character references. "’" is a character reference, equal to a single quote (ish). http://ganesh.bronco.co.uk/example.html is the character in action. I want to get from the string "x2019" to the Unicode character ’. However, your help has lead me to a solution! >>> u"\u2019" u'\u2019' >>> unichr(int("2019", 16)) u'\u2019' >>> That's got it - thanks :-) -Rob > Frank Millman’ -- http://mail.python.org/mailman/listinfo/python-list
Re: performance degradation when looping through lists
Joachim Worringen wrote: > I need to process large lists (in my real application, this is to parse > the content of a file). Then you probably want to use generators instead of lists. The problem with large lists is that they eat a lot of memory - which can result in swapping . > I noticed that the performance to access the > individual list elements degrades over runtime. I leave this point to gurus, but it may have to do with swapping. Also, this is not real-time, so variations may have to do with your OS tasks scheduler. My 2 cents -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to process table rows from an RDBMS
[EMAIL PROTECTED] wrote: > I can handle making the connections and running queries, but what's the > best way to process table rows returned in Python? depends on what you want to do with them. > What about turning a > table definition into an object? Just looking for ways to be efficient, > since I know I will be hitting the same external RDBMS from Python and > regularly processing a fixed set of tables with a certain fixed set of > attribute columns. Before ReinventingTheSquareWheel(tm), you may want to have a look at existing Python ORMs like SQLObjects or SQLAlchemy... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: performance degradation when looping through lists
bruno at modulix wrote: > Joachim Worringen wrote: >> I need to process large lists (in my real application, this is to parse >> the content of a file). > > Then you probably want to use generators instead of lists. The problem > with large lists is that they eat a lot of memory - which can result in > swapping . The effect also shows up in tiny examples (as the one posted) which surely don't swap on a 512MB machine. Also, I only read parts of the file into memory to avoid that memory becomes exhausted. Of course, using less memory is always a good idea - do you have a pointer on how to use generators for this application (basically, buffering file content in memory for faster access)? BTW, the effect also shows up with the linecache module. >> I noticed that the performance to access the >> individual list elements degrades over runtime. > > I leave this point to gurus, but it may have to do with swapping. Also, > this is not real-time, so variations may have to do with your OS tasks > scheduler. See above for the swapping. And the OS scheduler may create variations in runtime, but not monotone degradation. I don't think these two effect come into play here. -- Joachim - reply to joachim at domain ccrl-nece dot de Opinion expressed is personal and does not constitute an opinion or statement of NEC Laboratories. -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: job offering in Milan
Robin Becker wrote: > Michele Simionato wrote: > .. > > The Company > > StatPro, a leader Company in the field of portfolio analytics for the > > global asset management market, is looking for a Senior Systems/Network > > Engineering Specialist, who is ready for a new challenge. > > > > > > real pity, I used to do portfolio analytics for Bita Plus and SBC; minimax > risk > curves were just my bag etc etc :). > > My math skills are now so degraded I have difficulty reading about conic > programming using Nesterov's barrier functions etc etc. > > Oh well back to web scraping :( > -- > Robin Becker This position is for a system administrator (we are going to setup a cluster Linux for risk computations) but very likely we will have opening for other positions, for experts in financial computations/risk analysis. So if there is somebody interested, he can write to [EMAIL PROTECTED] Pretending I am on topic, I will add that most of our sofware is in Python, whereas all the numerical intensive routines are in C++. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: performance degradation when looping through lists
Joachim Worringen wrote: > I need to process large lists (in my real application, this is to parse > the content of a file). I noticed that the performance to access the > individual list elements degrades over runtime. > > This can be reproduced easily using this code: > > import time > > N=10 > p=1 > > A=[] > for i in range(N): > A.append(str(i)) > > j = 0 > t = time.clock() > for i in range(len(A)): > j += int(A[i]) > if i % p == 0: > t = time.clock() - t > print t > > (the string conversion only servers to increase the duration of each > iteration; you can observer the same effect with ints, too). > > When running this, I get output like this: > 0.0 > 0.37 > 0.03 > 0.4 > 0.06 > 0.43 > 0.09 > 0.46 > 0.13 > 0.49 > > I use Python 2.3.4 (#1, Sep 3 2004, 12:08:45) > [GCC 2.96 2731 (Red Hat Linux 7.3 2.96-110)] on linux2 > > I wonder why > 1. The execution times alternate between "fast" and "slow" (I observe the > same effect in my much more complex application) Your timing code is buggy. Change it to import time N=10 p=1 A=[] for i in range(N): A.append(str(i)) j = 0 start = time.clock() for i in range(len(A)): j += int(A[i]) if i % p == 0: end = time.clock() print end - start start = end Does the problem persist? I hope not. Peter -- http://mail.python.org/mailman/listinfo/python-list
ImageDraw line inconsistent ? (repost)
Hi there, Sorry to repost this, but I didn't get any answer one month ago. In essence, it seems that the ImageDraw line function draws lines one pixel shorter in some circumstances. This could be very annoying for some applications where precise geometry does matter. Below I test this function on a 3x3 image and show schematic representations of obtained images (where o means a drawn pixel) import Image, ImageDraw im = Image.new("L", (3,3)) draw = ImageDraw.Draw(im) draw.line((0,0,2,2), fill=255) im.tostring() Gives: o-- -o- --- So the last pixel of the line is not drawn. Similarly, draw.line((0,2,2,0), fill=255) gives: --- -o- o-- And draw.line((1,0,1,2), fill=255) gives: -o- -o- --- But, surprisingly, draw.line((0,1,2,1), fill=255) gives: --- ooo --- Where the last pixel of the line -is- drawn, as I expected it would be for all lines. This seems to be true for various image sizes and line angles: the last pixel is never drawn unless the line is horizontal. Any clues ? Thanks alex -- http://mail.python.org/mailman/listinfo/python-list
how convert "\\xd6\\xd0\\xb9\\xfa" into "\xd6\xd0\xb9\xfa"
in python dd = "\\xd6\\xd0\\xb9\\xfa" d = "\xd6\xd0\xb9\xfa" but how to convert one to other ? thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple string formatting question
Steven D'Aprano wrote: > I have a sinking feeling I'm missing something really, > really simple. > > I'm looking for a format string similar to '%.3f' > except that trailing zeroes are not included. > > To give some examples: > > FloatString > 1.0 1 > 1.1 1.1 > 12.1234 12.123 > 12.0001 12 > > and similar. > > Here is a (quick and dirty) reference implementation: > > def format(f, width=3): > fs = '%%.%df' % width > s = fs % f > return s.rstrip('0').rstrip('.') > > > Is there a way of getting the same result with just a > single string format expression? Does it have to be a string or can you cheat? If so: >>> class Format(str): ... def __new__(cls, width): ... return str.__new__(cls, "%%.%df" % width) ... def __mod__(self, other): ... return str.__mod__(self, other).rstrip("0").rstrip(".") ... >>> format = Format(3) >>> for f in [1.0, 1.1, 12.1234, 12.0001]: ... print f, "-->", format % f ... 1.0 --> 1 1.1 --> 1.1 12.1234 --> 12.123 12.0001 --> 12 For passing around in your app that should be as convenient as a string -- of course it will break if you store the "format" in a file, say. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: ImageDraw line inconsistent ? (repost)
[EMAIL PROTECTED] wrote: > Sorry to repost this, but I didn't get any answer one month ago. In > essence, it seems that the ImageDraw line function draws lines one > pixel shorter in some circumstances. This could be very annoying for > some applications where precise geometry does matter. http://effbot.python-hosting.com/ticket/41 -- http://mail.python.org/mailman/listinfo/python-list
Characters contain themselves?
While testing recursive algoritms dealing with generic lists I stumbled on infinite loops which were triggered by the fact that (at least for my version of Pyton) characters contain themselves.See session: system prompt% python Python 2.3.5 (#2, Feb 9 2005, 00:38:15) [GCC 3.3.5 (Debian 1:3.3.5-8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 'a' is 'a' True >>> 'a' in 'a' True >>> 'a' in ['a'] True >>> Leading to paradoxes and loops objects which contain themselves (and other kinds of monsters) are killed in set theory with the Axiom of Foundation:=) But let's go back to more earthly matters. I couldn't find any clue in a python FAQ after having googled with the following "Python strings FAQ" about why this design choice and how to avoid falling in this trap without having to litter my code everywhere with tests for stringiness each time I process a generic list of items. Any hints would be appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Farther OT: financial analytics (was: OT: job offering in Milan)
In article <[EMAIL PROTECTED]>, Robin Becker <[EMAIL PROTECTED]> wrote: . . . >My math skills are now so degraded I have difficulty reading about conic >programming using Nesterov's barrier functions etc etc. . . . You've got me curious. I haven't yet located an adequate introduction to the topic, so I'll ask *you* about the basics: do these (*semi*definite?) cones arise in financial with time the privileged dimension? Does "cone" here mean necessarily with a quadratic cross-section? If so, why is that more compelling than the simplexes of more traditional LP? -- http://mail.python.org/mailman/listinfo/python-list
Re: how convert "\\xd6\\xd0\\xb9\\xfa" into "\xd6\xd0\xb9\xfa"
ygao wrote: > in python > dd = "\\xd6\\xd0\\xb9\\xfa" > d = "\xd6\xd0\xb9\xfa" > but how to convert one to other ? >>> "\\xd6\\xd0\\xb9\\xfa".decode("string-escape") '\xd6\xd0\xb9\xfa' >>> "\xd6\xd0\xb9\xfa".encode("string-escape") '\\xd6\\xd0\\xb9\\xfa' Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Characters contain themselves?
WENDUM Denis 47.76.11 (agent): >While testing recursive algoritms dealing with generic lists I stumbled >on infinite loops which were triggered by the fact that (at least for my >version of Pyton) characters contain themselves. No, strings contain characters. And 'a' is a string consisting of one character. "The items of a string are characters. There is no separate character type; a character is represented by a string of one item." http://docs.python.org/ref/types.html (One item of what type, one might ask) -- René Pijlman -- http://mail.python.org/mailman/listinfo/python-list
Re: how to make a generator use the last yielded value when it regains control
Lonnie Princehouse wrote: > Here's my take on the thing. It only prints one term, though. > > http://www.magicpeacefarm.com/lonnie/code/morris.py.html > > (a bit too long to post) > yikes, scary! :) there was always the hint that using itertools might be helpful, as you guys are doing, but i could never quite figure out how, but looking at these alternate methods is definitely helpful -- http://mail.python.org/mailman/listinfo/python-list
wxPython Question
I am learning wxPython for one of my projects. I was wondering if there is drag and drop in any Python IDE like there is Visual Basic where you select an object like command_button and put onto the frame. Is there any help to make life easier in Python. Every help is greatly appreciated, -- http://mail.python.org/mailman/listinfo/python-list
Re: Characters contain themselves?
In fact, not just characters, but strings contain themselves: >>> 'abc' in 'abc' True This is a very nice(i.e. clear and concise) shortcut for: >>> 'the rain in spain stays mainly'.find('rain') != -1 True Which I always found contorted and awkward. Could you be a bit more concrete about your complaint? -- George [Thanks, I did enjoy looking up the Axiom of Foundation!] -- http://mail.python.org/mailman/listinfo/python-list
how you know you're a programming nerd
So last night I had a dream that me and two other guys needed to get a simple task done in Java. We were staring at the problem in confusion and I kept saying "First we have to create a class, then instantiate it, then..." etc. etc. They didn't agree with me so we kept arguing back and forth about it. Finally, in frustration, I shout "God, Python is so much easier than any other language!" :) It's not the first time I've had a dream about programming (and the others were much more uncomfortable because they involved math), but it's the first time Python has snuck into my subconscious. And as a sidenote, I don't know Java at all, so I have no idea how it found its way into my brain. Of course, it wasn't real Java syntax I was seeing, I'm sure... -- http://mail.python.org/mailman/listinfo/python-list
Re: Characters contain themselves?
Rene Pijlman <[EMAIL PROTECTED]> writes: > WENDUM Denis 47.76.11 (agent): > >While testing recursive algoritms dealing with generic lists I stumbled > >on infinite loops which were triggered by the fact that (at least for my > >version of Pyton) characters contain themselves. > > No, strings contain characters. And 'a' is a string consisting of one > character. > > "The items of a string are characters. There is no separate character > type; a character is represented by a string of one item." > http://docs.python.org/ref/types.html > > (One item of what type, one might ask) Good point. ". . .represented by a string of length one" would be better. -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson An information system based on theory isolated from reality is bound to fail. - Mitch Kabay -- http://mail.python.org/mailman/listinfo/python-list
Re: shelve and ".bak .dat .dir" files
Michele Petrazzo <[EMAIL PROTECTED]> wrote: >Sion Arrowsmith wrote: >> This is a documented behaviour of shelve: > [ open(filename) may create files with names based on filename + ext ] >(and I fail to understand why >> it is a problem). >Because: >1) I pass a name that, after, I'll pass to another program and if shelve >change the name, the latter can't read it (it doesn't exists!) Hmm, is there any guarantee that the filename you give to shelve.open() to create will correspond to a single file on disk that you can hand to another application for purposes other than opening to read with shelve? Given that it's documented that it may create other files, it seems to me like you'd always want the other program to look for file and file.* anyway. Unless it's just reading: >2) I can't read those files with shelve! If I try... : > shelve.open("test.dat") >Traceback (most recent call last): > [ ... ] >anydbm.error: db type could not be determined Did you try opening using the filename you originally gave, ie shelve.open("test")? Of course plain open("test") will fail, but this is opening a dbm structure based on "test" not a simple file. -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: how you know you're a programming nerd
John Salerno wrote: > So last night I had a dream that me and two other guys needed to get a > simple task done in Java. Then s/dream/nightmare/ -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: passing argument to script
Works for me. I get "abc def ghi" using your script on Windows XP and ActiveState Python 2.4.3 rd -- http://mail.python.org/mailman/listinfo/python-list
Re: passing argument to script
Daniel Nogradi <[EMAIL PROTECTED]> wrote: >If you execute your script from the command line on Linux you need to >enclose it in quotation marks otherwise your shell will interfere. So >you need to invoke your program as > >python yourscript.py "ABCE-123456 ABC_DEF_Suggest(abc def ghi).txt" Same is true on Windows. It's just that some commands magically convert filenames with spaces into a single argument if you don't quote them. (Compare, for instance, cd \Program Files with dir \Program Files .) >and need to refer to the argument as sys.argv[1:][0] That's an interesting way of spelling sys.argv[1] . -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: pre-PEP: The create statement
Michele> I think looking at the occurrences in the standard library only Michele> is unfair. In addition, when considering the standard library you need to search the source repository, not just what's installed on your platform. I noticed in your earlier post that you pointed your count_names script (very handy, btw) at your /usr/lib/pythonN.M directory. Pointing it at the source repository picks up stuff in the platform-dependent sections as well as searching through other less-used code. Michele> I guess 'make' sounds too Lispy, this is why it is never used Michele> in Pythonland. It doesn't seem lispish to me. OTOH, "make" seems more utilitarian than "create". For instance, cooks make things while chefs create things. Perhaps "make" is better anyway. The proposed statement is essentially a namespace factory. I think of object factories as very utilitarian beasts. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython Question
I think you are looking for a drag and drop GUI builder? If so then http://wxglade.sourceforge.net/ -- wxglade is what you need. There are some others but this is what I prefer myself. -- http://mail.python.org/mailman/listinfo/python-list
Re: ftplib question
Well I am not too familiar with ftplib but I have done some minimal work. Example: try: server=FTP() server.connect('ftp.mcafee.com', 21) except: print "Could not connect to server" raw_input("Hit Enter to quit:") sys.exit(0) login = server.login('anonymous', '[EMAIL PROTECTED]') workdir = server.cwd("/pub/datfiles/english") ## Set the current directory server.delete("*.*") End Example: I hope it helps -- http://mail.python.org/mailman/listinfo/python-list
Re: performance degradation when looping through lists
Joachim Worringen on comp.lang.python said: > I use Python 2.3.4 (#1, Sep 3 2004, 12:08:45) > [GCC 2.96 2731 (Red Hat Linux 7.3 2.96-110)] on linux2 Check Peter Otten's answer, and remember as well that GCC 2.96 can lead to highly strange issues whenever used. -- Alan Franzoni <[EMAIL PROTECTED]> - Togli .xyz dalla mia email per contattarmi. Rremove .xyz from my address in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E -- http://mail.python.org/mailman/listinfo/python-list
Re: glob and curly brackets
You just need to literlize them with a forward slash. " globber = '/home/zhomer/test/{dir1*,dir2*}/{subdir1,subdir2}' globlist = glob.glob(globber) " globber = '/home/zhomer/test/\{dir1*,dir2*\}/\{subdir1,subdir2\}' globlist = glob.glob(globber) See if that works for you. -- http://mail.python.org/mailman/listinfo/python-list
Re: performance degradation when looping through lists
Peter Otten wrote: > Your timing code is buggy. Change it to Ooops, you're right. Everything is fine now... Thanks. Joachim -- Joachim - reply to joachim at domain ccrl-nece dot de Opinion expressed is personal and does not constitute an opinion or statement of NEC Laboratories. -- http://mail.python.org/mailman/listinfo/python-list
Re: performance degradation when looping through lists
Hi, I wrote a program some days back and I was using lists heavily for performing operations such as pop, remove, append. My list size was around 1024x3 and there were around 20 different objects like this. What I want to ask you is that my program also degraded over a period of time. I cannot post the code as its lot of code. But I want to ask a question why List degrade. What other alternative for lists is a faster measure. Eveyr help is greatly appreciated, -- http://mail.python.org/mailman/listinfo/python-list
Re: [fcntl]how to lock a file
marcello wrote: > Hello > I need to do this: > 1 opening a file for writing/appending > 2 to lock the file as for writing (i mean: the program > that lock can keep writing, all others programs can't ) > 3 wtite and close/unlock http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 been using it for years and it makes locking really simple. I have no idea why the main Python distribution is missing such an important piece of functionality. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to search HUGE XML with DOM?
Ivan Vinogradov wrote: > I have not much clue about databases, except that they exist, somewhat > complex, and often use proprietary formats for efficiency. Prorietary storage format, but a standardized API... > So any points on whether RDBM-based setup > would be better would be greatly appreciated. The typical use case for RDBMS is that you have a number of record types (classes/relations/tables) with a regular structure, and all data fits into these structures. When you want to search for something, you know exactly in what field of what table to look (but not which item of course). You also typically have multiple users who need to be able to update the same database simultaneously without getting in each others way. > Even trivial aspects, such as whether to produce RDBM during the > simulation, or convert the complete XML log file into one, are not > entirely clear to me. Most databases as suited at writing data in fairly small chunks, although it's typically much faster to write 100 items in a transaction, than to write 100 transactions with one item each. > I gather that RDBM would be much better suited for > analysis, but what about portability ? Is database file a separate > entity that may be passed around? Who says that a database needs to reside in a file? Most databases reside on disk, but it might well be in raw partitions. In general, you should see the database as a persistent representation of data in a system. It's not a transport mechanism. -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython Question
Can we download wxPython doc as an offline folder because if I dont have internet its difficult to have the access to all the docs. -- http://mail.python.org/mailman/listinfo/python-list
Re: A Lambda Logo Tour
Xah Lee wrote: > A Lambda Logo Tour > (and why LISP languages using λ as logo should not be looked upon > kindly) > > Xah Lee, 2002-02 > > Dear lispers, For the love of Java! Where is the Java in this post? Underwear related off topic trivia: At university we worked out that Y-fronts weren't Y-fronts at all - after all, the 'Y' is upside down - they're actually lambda pants. -- http://mail.python.org/mailman/listinfo/python-list
Re: Difference in Python and Ruby interactive shells
Peter Otten <[EMAIL PROTECTED]> wrote: > Alex Martelli wrote: > > > Michele Simionato <[EMAIL PROTECTED]> wrote: > > > >> You want this recipe from Michael Hudson: > >> > >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 > >> > >> "automatically upgrade class instances on reload()" > > > > Note that the version in the printed Cookbook (2nd edition) was > > substantially enhanced (mostly by me and Michael working together), I > > don't know if Michael updated his ASPN recipe to reflect that but at any > > rate you can download all the code from the printed Cookbook as a > > zipfile from O'Reilly's site (sorry, I don't recall the URL). > > http://examples.oreilly.com/pythoncook2/cb2_examples.zip > > The files are named cb2_6_21_*.py, but the book has the recipe in chapter > 20.15. Ah, yes, good point: there's an "off by one" numbering issue there, due to the fact that the O'Reilly Safari online verbatim version of the book numbers the preface as "1" while the printed version doesn't, so chapter 1 in the printed version is 2.something on Safari, etc. Alex -- http://mail.python.org/mailman/listinfo/python-list
FTP
Hello! I want to connecto to a ftp server. There I woult like to read the directiroy and getting the filename, file owner and the file size. How can I do this in python and if possible please post the code for it. Thanks! Arne -- http://mail.python.org/mailman/listinfo/python-list
UnicodeDecodeError help please?
Okay I'm getting really frustrated with Python's Unicode handling, I'm trying everything I can think of an I can't escape Unicode(En|De)codeError no matter what I try. Could someone explain to me what I'm doing wrong here, so I can hope to throw light on the myriad of similar problems I'm having? Thanks :-) Python 2.4.1 (#2, May 6 2005, 11:22:24) [GCC 3.3.6 (Debian 1:3.3.6-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.getdefaultencoding() 'utf-8' >>> import htmlentitydefs >>> char = htmlentitydefs.entitydefs["copy"] # this is an HTML © - a >>> copyright symbol >>> print char © >>> str = u"Apple" >>> print str Apple >>> str + char Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: unexpected code byte >>> a = str+char Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: unexpected code byte >>> Basically my app is a search engine - I'm grabbing content from pages using HTMLParser and storing it in a database but I'm running in to these problems all over the shop (from decoding the entities to calling str.lower()) - I don't know what encoding my pages are coming in as, I'm just happy enough to accept that they're either UTF-8 or latin-1 with entities. Any help would be great, I just hope that I have a brainwave over the weekend because I've lost two days to Unicode errors now. It's even worse that I've written the same app in PHP before with none of these problems - and PHP4 doesn't even support Unicode. Cheers -Rob -- http://mail.python.org/mailman/listinfo/python-list
GUI Treeview
Hello ! I am looking for a widget with the following properties: - showing the tree file structure/ directory structure - next to each file should be a checkbox - the tree should only show certain files (i. e. only for the looked in user) Maybe you can post me a link. Thanks! Arne -- http://mail.python.org/mailman/listinfo/python-list
Re: binding - python
Hi John, It works. Thank you veyr much. Cheers, Q -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeDecodeError help please?
Robin Haswell wrote: > Okay I'm getting really frustrated with Python's Unicode handling, I'm > trying everything I can think of an I can't escape Unicode(En|De)codeError > no matter what I try. Have you read any of the documentation about Python's Unicode support? E.g., http://effbot.org/zone/unicode-objects.htm > Could someone explain to me what I'm doing wrong here, so I can hope to > throw light on the myriad of similar problems I'm having? Thanks :-) > > Python 2.4.1 (#2, May 6 2005, 11:22:24) > [GCC 3.3.6 (Debian 1:3.3.6-2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > import sys sys.getdefaultencoding() > > 'utf-8' How did this happen? It's supposed to be 'ascii' and not user-settable. import htmlentitydefs char = htmlentitydefs.entitydefs["copy"] # this is an HTML © - a copyright symbol print char > > © > str = u"Apple" print str > > Apple > str + char > > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: > unexpected code byte > a = str+char > > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: > unexpected code byte The values in htmlentitydefs.entitydefs are encoded in latin-1 (or are numeric entities which you still have to parse). So decode using the latin-1 codec. -- Robert Kern [EMAIL PROTECTED] "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeDecodeError help please?
Robin Haswell wrote: > Could someone explain to me what I'm doing wrong here, so I can hope to > throw light on the myriad of similar problems I'm having? Thanks :-) > > Python 2.4.1 (#2, May 6 2005, 11:22:24) > [GCC 3.3.6 (Debian 1:3.3.6-2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import sys > >>> sys.getdefaultencoding() > 'utf-8' that's bad. do not hack the default encoding. it'll only make you sorry when you try to port your code to some other python installation, or use a library that relies on the factory settings being what they're supposed to be. do not hack the default encoding. back to your code: > >>> import htmlentitydefs > >>> char = htmlentitydefs.entitydefs["copy"] # this is an HTML © - a > >>> copyright symbol > >>> print char > © that's a standard (8-bit) string: >>> type(char) >>> ord(char) 169 >>> len(char) 1 one byte that contains the value 169. looks like ISO-8859-1 (Latin-1) to me. let's see what the documentation says: entitydefs A dictionary mapping XHTML 1.0 entity definitions to their replacement text in ISO Latin-1. alright, so it's an ISO Latin-1 string. > >>> str = u"Apple" > >>> print str > Apple >>> type(str) >>> len(str) 5 that's a 5-character unicode string. > >>> str + char > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: > unexpected code byte you're trying to combine an 8-bit string with a Unicode string, and you've told Python (by hacking the site module) to treat all 8-bit strings as if they contain UTF-8. UTF-8 != ISO-Latin-1. so, you can of course convert the string you got from the entitydefs dict to a unicode string before you combine the two strings >>> unicode(char, "iso-8859-1") + str u'\xa9Apple' but the htmlentitydefs module offers a better alternative: name2codepoint A dictionary that maps HTML entity names to the Unicode codepoints. New in version 2.3. which allows you to do >>> char = unichr(htmlentitydefs.name2codepoint["copy"]) >>> char u'\xa9' >>> char + str u'\xa9Apple' without having to deal with things like >>> len(htmlentitydefs.entitydefs["copy"]) 1 >>> len(htmlentitydefs.entitydefs["rarr"]) 7 > Basically my app is a search engine - I'm grabbing content from pages > using HTMLParser and storing it in a database but I'm running in to these > problems all over the shop (from decoding the entities to calling > str.lower()) - I don't know what encoding my pages are coming in as, I'm > just happy enough to accept that they're either UTF-8 or latin-1 with > entities. UTF-8 and Latin-1 are two different things, so your (international) users will hate you if you don't do this right. > It's even worse that I've written the same app in PHP before with none of > these problems - and PHP4 doesn't even support Unicode. a PHP4 application without I18N problems? I'm not sure I believe you... ;-) -- http://mail.python.org/mailman/listinfo/python-list
Why did someone write this?
try: exc_type, exc_value, exc_traceback = sys.exc_info() # Do something finally: exc_traceback = None Why the try/finally with setting exc_traceback to None? The python docs didn't give me any clue, and I'm wondering what this person knows that I don't. Thanks, -Sandra -- http://mail.python.org/mailman/listinfo/python-list
Re: FTP
Arne: >I want to connecto to a ftp server. There I woult like to read the >directiroy and getting the filename, file owner and the file size. > >How can I do this in python http://docs.python.org/lib/module-ftplib.html -- René Pijlman -- http://mail.python.org/mailman/listinfo/python-list
Re: FTP
"Arne" <[EMAIL PROTECTED]> wrote: > I want to connecto to a ftp server. There I woult like to read the > directiroy and getting the filename, file owner and the file size. > > How can I do this in python and if possible please post the code for it. there's an example in the library reference that does exactly that: http://www.python.org/doc/lib/module-ftplib.html (it's above the fold, so I'm not sure how you missed it). -- http://mail.python.org/mailman/listinfo/python-list
Jpype on RHEL v3
I have been trying out jpype for python to java work and love it. It works great on my gentoo box with the java 1.4.2 blackdown sdk. I am now trying it on Red Hat Enterprise Linux 3 for access to business intelligence tools (JasperReports, Mondrian, Pentaho, etc) for which we don't have analogous tools in cpython yet. My idea it to use jpype in a cherrypy application server to tie these java BI tools into a website interface without having to delve into the more complex java J2EE application servers and lose all the python libraries that I know and love. Here is my problem. When trying to start the jvm with the sun jre I get this error. [EMAIL PROTECTED] root]# python2.4 Python 2.4.2 (#1, Dec 1 2005, 05:44:04) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-53)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import jpype >>> jpype.startJVM('/usr/lib/jvm/java-1.4.2-sun/jre/lib/i386/client/libjvm.so') Error occurred during initialization of VM Unable to load native library: libjvm.so: cannot open shared object file: No such file or directory and then python dies. When I try to start the jvm with the ibm jre I get this error. [EMAIL PROTECTED] root]# python2.4 Python 2.4.2 (#1, Dec 1 2005, 05:44:04) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-53)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import jpype >>> jpype.startJVM('/usr/lib/jvm/java-1.4.2-ibm-1.4.2.2/jre/bin/classic/libjvm.so') Unable to find UTE, path used libjava.so/libute.so JVMCI170: Please check the path to shared libraries Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/jpype/_core.py", line 25, in startJVM _jpype.startup(jvm, tuple(args), True) RuntimeError: Unable to start JVM at src/native/common/jp_env.cpp:54 but the python interpreter is still running. Can anyone point me in the right direction so I can fix this? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: "The World's Most Maintainable Programming Language"
Peter Hansen wrote: > Mirco Wahab wrote: > >> Hi Ralf >> >>> So we should rename Python into Cottonmouth to get more attention. >> >> >> No, always take some word that relates to >> something more or less 'feminine', its about >> 96% of young males who sit hours on programming >> over their beloved 'languages' ;-) >> >> Pythia? (http://en.wikipedia.org/wiki/Pythia) > > > I guess that would make our motto "Pythia: now you're programming with > ethylene." Who said programming in Python was a r'P[y|i]t(hi)?a' ?-) (oops, sorry --->[]) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
win32com
Hi, Is it possible to create a com server in python and then access that server using VB .NET, for example using the following code. A very basic com server i found in a tutorial about win32com: class HelloWorld: _reg_clsid_ = "{7CC9F362-486D-11D1-BB48-E838A65F}" _reg_desc_ = "Python Test COM Server" _reg_progid_ = "Python.TestServer" # Next line assumes file is "testcomserver.py" _reg_class_spec_ = "testcomserver.HelloWorld" _public_methods_ = ['Hello'] _public_attrs_ = ['softspace', 'noCalls'] _readonly_attrs_ = ['noCalls'] def __init__(self): self.softspace = 1 self.noCalls = 0 def Hello(self, who): self.noCalls = self.noCalls + 1 # insert "softspace" number of spaces return "Hello" + " " * self.softspace + who if __name__=='__main__': import win32com.server.register win32com.server.register.UseCommandLine(HelloWorld) When I run it it says: '>>> Registered: Python.TestServer ' But how can I access that server now from VB .NET (if it's possible). Or do I need to use very different python code? (I wasnt sure where to put this, in vb or python section, sorry if its in the wrong section) Thanks in advance, Floris van Nee -- http://mail.python.org/mailman/listinfo/python-list
Re: Why did someone write this?
Sandra> try: Sandra>exc_type, exc_value, exc_traceback = sys.exc_info() Sandra># Do something Sandra> finally: Sandra>exc_traceback = None Sandra> Why the try/finally with setting exc_traceback to None? The intent is to decrement the reference count to any objects referenced by exc_traceback. Without it, the frame(s) referenced by the traceback remain alive until exc_traceback goes out of scope. Skip -- http://mail.python.org/mailman/listinfo/python-list
Calling Web Services from Python
Hello, My Python application calls web services available on the Internet. The web service being called is defined through application user input. The Python built-in library allows access to web services using HTTP protocol, which is not acceptible - generating SOAP messages for arbitrary web services is something i wish to avoid. I need a package/tool that generates web service proxies that will do all the low-level HTTP work. (Someting like the WSDL.EXE tool in .NET Framework) The ZSI and SOAPy packages [1] that i found (should) have those functionalities but either have a bug (SOAPy) or either do not work for arbitrary web services (ZSI). I tried the ZSI wsdl2py script on a wsdl of one of my services, and the script crashes. I suppose the wsdl was "too hard" for the script to parse. Are there any other packages that utilize generation of web service proxies that are compatible with SOAP & WSDL standards? Thank you, ivan zuzak [1] - http://pywebsvcs.sourceforge.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeDecodeError help please?
Robin Haswell wrote: > Okay I'm getting really frustrated with Python's Unicode handling, I'm > trying everything I can think of an I can't escape Unicode(En|De)codeError > no matter what I try. If you follow a few relatively simple rules, the days of Unicode errors will be over. Let's take a look! > Could someone explain to me what I'm doing wrong here, so I can hope to > throw light on the myriad of similar problems I'm having? Thanks :-) > > Python 2.4.1 (#2, May 6 2005, 11:22:24) > [GCC 3.3.6 (Debian 1:3.3.6-2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import sys > >>> sys.getdefaultencoding() > 'utf-8' Note that this only specifies the encoding assumed to be used in plain strings when such strings are used to create Unicode objects. For some applications this is sufficient, but where you may be dealing with many different character sets (or encodings), having a default encoding will not be sufficient. This has an impact below and in your wider problem. > >>> import htmlentitydefs > >>> char = htmlentitydefs.entitydefs["copy"] # this is an HTML © - a > >>> copyright symbol > >>> print char > © It's better here to use repr(char) to see exactly what kind of object it is (or just give the name of the variable at the prompt). For me, it's a plain string, despite htmlentitydefs defining the each name in terms of its "Unicode codepoint". Moreover, for me the plain string uses the "Latin-1" (or more correctly iso-8859-1) character set, and I imagine that you get the same result. > >>> str = u"Apple" > >>> print str > Apple > >>> str + char > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: > unexpected code byte Here, Python attempts to make a Unicode object from char, using the default encoding (which is utf-8) and finds that char is a plain string containing non-utf-8 character values, specifically a single iso-8859-1 character value. It consequently complains. This is quite unfortunate since you probably expected Python to give you the entity definition either as a Unicode object or a plain string of your chosen encoding. Having never used htmlentitydefs before, I can only imagine that it provides plain strings containing iso-8859-1 values in order to support "legacy" HTML processing (given that semi-modern HTML favours x; entities, and XHTML uses genuine character sequences in the stated encoding), and that getting anything other than such strings might not be particularly useful. Anyway, what you'd do here is this: str + unicode(char, "iso-8859-1) Rule #1: if you have plain strings and you want them as Unicode, you must somewhere state what encoding those strings are in, preferably as you convert them to Unicode objects. Here, we can't rely on the default encoding being correct and must explicitly state a different encoding. Generally, stating the encoding is the right thing to do, rather than assuming some default setting that may differ across environments. Somehow, my default encoding is "ascii" not "utf-8", so your code would fail on my system by relying on the default encoding. [...] > Basically my app is a search engine - I'm grabbing content from pages > using HTMLParser and storing it in a database but I'm running in to these > problems all over the shop (from decoding the entities to calling > str.lower()) - I don't know what encoding my pages are coming in as, I'm > just happy enough to accept that they're either UTF-8 or latin-1 with > entities. Rule #2: get your content as Unicode as soon as possible, then work with it in Unicode. Once you've made your content Unicode, you shouldn't get UnicodeDecodeError all over the place, and the only time you then risk an UnicodeEncodeError is when you convert your content back to plain strings, typically for serialisation purposes. Rule #3: get acquainted with what kind of encodings apply to the incoming data. If you are prepared to assume that the data is either utf-8 or iso-8859-1, first try making Unicode objects from the data stating that utf-8 is the encoding employed, and only if that fails should you consider it as iso-8859-1, since an utf-8 string can quite happily be interpreted (incorrectly) as a bunch of iso-8859-1 characters but not vice versa; thus, you have a primitive means of validation. > Any help would be great, I just hope that I have a brainwave over the > weekend because I've lost two days to Unicode errors now. It's even worse > that I've written the same app in PHP before with none of these problems - > and PHP4 doesn't even support Unicode. Perhaps that's why you never saw any such problems, but have you looked at the quality of your data? Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling Web Services from Python
Ivan Zuzak wrote: > I need a package/tool that generates web service proxies that will do > all the low-level HTTP work. (Someting like the WSDL.EXE tool in .NET > Framework) The ZSI and SOAPy packages [1] that i found (should) have > those functionalities but either have a bug (SOAPy) or either do not > work for arbitrary web services (ZSI). You might want to read this, specifically 12.5 and 12.6 for WSDL: http://diveintopython.org/soap_web_services/index.html It uses SOAPpy, which may or may not be different than SOAPy, depending on if you made a typo or not. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: updated pre-PEP: The create statement
Carl Banks wrote: > Steven Bethard wrote: >> I've updated the PEP based on a number of comments on comp.lang.python. >> The most updated versions are still at: >> >> http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt >> http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html >> >> In this post, I'm especially soliciting review of Carl Banks's point >> (now discussed under Open Issues) which asks if it would be better to >> have the create statement translated into: >> >> = ("", *, **) >> >> instead of the current: >> >> = ("", , ) >> >> The former allows the create statement to be applied to a wider variety >> of callables; the latter keeps a better parallel with the class statement. > > Meh. I don't think the args, kwargs is a good idea at all, and wasn't > suggesting that. For this construction not to apply to type objects > would be a mistake. I wanted us to consider whether it was a problem > for it not to work in certain useful cases (such as dicts), and whether > it was deal-breaking, and what to do about it if not. > > Off the top of my head, a simple way to make this work for both types > and dicts is to have a special static method called __make__ (or > __create__) that is called by this syntax. For type objects, __make__ > is a synonym for __new__. For dict, it can call __new__ with the third > argument. I've updated the PEP along these lines, and I've now submitted it for a PEP number. The current drafts are now at: http://ucsu.colorado.edu/~bethard/py/pep_make_statement.txt http://ucsu.colorado.edu/~bethard/py/pep_make_statement.html I'll post them again once I get a PEP number. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: how you know you're a programming nerd
John Salerno wrote: > So last night I had a dream that me and two other guys needed to get a > simple task done in Java. We were staring at the problem in confusion > and I kept saying "First we have to create a class, then instantiate it, > then..." etc. etc. They didn't agree with me so we kept arguing back and > forth about it. > > Finally, in frustration, I shout "God, Python is so much easier than any > other language!" :) > > It's not the first time I've had a dream about programming (and the > others were much more uncomfortable because they involved math), but > it's the first time Python has snuck into my subconscious. I think Freud might have had something to say about that. > > And as a sidenote, I don't know Java at all, so I have no idea how it > found its way into my brain. Of course, it wasn't real Java syntax I was > seeing, I'm sure... -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeDecodeError help please?
On 2006-04-07, Robin Haswell <[EMAIL PROTECTED]> wrote: > Okay I'm getting really frustrated with Python's Unicode handling, I'm > trying everything I can think of an I can't escape Unicode(En|De)codeError > no matter what I try. > > Could someone explain to me what I'm doing wrong here, so I can hope to > throw light on the myriad of similar problems I'm having? Thanks :-) > > Python 2.4.1 (#2, May 6 2005, 11:22:24) > [GCC 3.3.6 (Debian 1:3.3.6-2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. import sys sys.getdefaultencoding() > 'utf-8' import htmlentitydefs char = htmlentitydefs.entitydefs["copy"] # this is an HTML © - a copyright symbol print char > © str = u"Apple" print str > Apple str + char > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: > unexpected code byte a = str+char > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: > unexpected code byte Try this: import htmlentitydefs char = htmlentitydefs.entitydefs["copy"] char = unicode(char, "Latin1") str = u"Apple" print str print str + char htmlentitydefs.entitydefs is "A dictionary mapping XHTML 1.0 entity definitions to their replacement text in ISO Latin-1". So you get "char" back as a Latin-1 string. Then we use the builtin function unicode to make a unicode string (which doesn't have an encoding, as I understand it, it's just unicode). This can be added to u"Apple" and printed out. It prints out OK on a UTF-8 terminal, but you can print it in other encodings using encode: print (str + char).encode("Latin1") for example. For your search engine you should look at server headers, metatags, BOMs, and guesswork, in roughly that order, to determine the encoding of the source document. Convert it all to unicode (using builtin function unicode) and use that to build your indexes etc., and write results out in whatever you need to write it out in (probably UTF-8). HTH. -- http://mail.python.org/mailman/listinfo/python-list
Re: Jpype on RHEL v3
I found the problem. So if anyone else has it here is the fix. In the documentation distributed with JPype 0.5.1 in the examples/linux directory, there is a file that describes a problem with loading the jvm on linux. So one needs to modify the LD_LIBRARY_PATH environment variable to fix it. I did that after changing one line in /usr/lib/python2.4/site-packages/jpype/_linux.py line 37 to return "/etc/alternatives/java_sdk/jre/lib/i386/client/libjvm.so" so that jpype.getDefaultJVMPath() would return the correct libjvm.so path for my install. Then I did export LD_LIBRARY_PATH=/etc/alternatives/java_sdk/jre/lib/i386:/etc/alternatives/java_sdk/jre/lib/i386/client after doing that the sun 1.4.2 jre loaded just fine with: [EMAIL PROTECTED] root]# python2.4 Python 2.4.2 (#1, Dec 1 2005, 05:44:04) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-53)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import jpype >>> jpype.startJVM(jpype.getDefaultJVMPath()) >>> -- http://mail.python.org/mailman/listinfo/python-list
Newbie wxPython questions.
I am running through the wxPython guide and docs and extrapolating enough to get confused. BAsed on the tute in the getting started wiki I created a panel that has most of the elements I want; some check boxes and a couple of buttons. The button I have is a simple thing that is supposed to just close (destroy) the app. Only thing is, it destroys the panel and leaves the app behind. I have attempted to place this on teh frame by defining a frame; the button works great and closes the app, but because it isn't part of the panel, the panel is all squished up into the very top left corner and all you can see is the first checkbox, which you can't even check. Can I make a button on the panel destroy the frame? The next question I have is about adding a second button to the panel (or frame, I guess) that will then execute a bunch of things depending on which checkboxes are ticked. My attempts to add the button have been wrong so far, as you'll see with my code. The first code block is my panel only app. The second is how it looks after I defined the Frame first and then moved the Cancel button. TIA Nuffnough -- import wx, sys, os class Form1(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) self.quote = wx.StaticText(self, -1, "Launching :",wx.Point(20,30)) st = wx.StaticText(self, -1, "Select the applications you need to launch:")#, (10, 10) cb1 = wx.CheckBox(self, -1, "Read Calander, Check Email")#,(65,40), (150, 20), wx.NO_BORDER) cb2 = wx.CheckBox(self, -1, "Internet Browser") self.Bind(wx.EVT_CHECKBOX, self.EvtCheckBox, cb1) self.Bind(wx.EVT_CHECKBOX, self.EvtCheckBox, cb2) sizer = wx.BoxSizer(wx.VERTICAL) sizer.AddMany( [ cb1, cb2, ]) border = wx.BoxSizer(wx.VERTICAL) border.Add(st, 0, wx.ALL, 15) border.Add(sizer, 0, wx.LEFT, 50) self.SetSizer(border) pos = cb2.GetPosition().x + cb2.GetSize().width + 25 btn0 = wx.Button(self, -1, "Cancel", (pos, 150)) self.Bind(wx.EVT_BUTTON, self.OnCloseMe, btn0) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) ''' Commented out btn1 cause I couldn't make it work btn1 = wx.Button(self, -1, "Open Apps", (pos + 60, 150)) self.Bind(wx.EVT_BUTTON, self.OnTestButton, btn1) ''' def EvtCheckBox(self, event): self.log.write('EvtCheckBox: %d\n' % event.IsChecked()) cb = event.GetEventObject() if cb.Is3State(): self.log.write("\t3StateValue: %s\n" % cb.Get3StateValue()) def OnTestButton(self, evt): self.cb1.SetString(1, "FUBAR") def OnCloseMe(self, event): self.Close(True) def OnCloseWindow(self, event): self.Destroy() app = wx.PySimpleApp() frame = wx.Frame(None, -1, "An application launcher") Form1(frame, -1) frame.Show(1) app.MainLoop() -- import wx, sys, os ID_ABOUT = 101 ID_EXIT = 110 class Frame1(wx.Frame): def __init__(self,parent,id,title): wx.Frame.__init__(self,parent,wx.ID_ANY, title, size = (300, 400), style=wx.DEFAULT_FRAME_STYLE) #self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE) self.CreateStatusBar() # A Statusbar in the bottom of the window # Setting up the menu. filemenu= wx.Menu() filemenu.Append(ID_ABOUT, "&About"," Information about this program") filemenu.AppendSeparator() filemenu.Append(ID_EXIT,"E&xit"," Terminate the program") # Creating the menubar. menuBar = wx.MenuBar() menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content. pos = 20 btn0 = wx.Button(self, -1, "Button Text", (pos, 220)) self.Bind(wx.EVT_BUTTON, self.OnCloseMe, btn0) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) #def OnTestButton(self, evt): #Run some code that checks which boxes are ticked #Then perform a function for each ticked box def OnCloseMe(self, event): self.Close(True) def OnCloseWindow(self, event): self.Destroy() self.Show(True) class Form1(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) self.quote = wx.StaticText(self, -1, "Choose Applications :",wx.Point(20,30)) st = wx.StaticText(self, -1, "Select the application(s) you need to open:")#, (10, 10) cb1 = wx.CheckBox(self, -1, "Email, Calender")#,(65,40), (150, 20), wx.NO_BORDER) cb2 = wx.CheckBox(self, -1, "Browser") self.Bind(wx.EVT_CHECKBOX, self.EvtCheckBox, cb1) self.Bind(wx.EVT_CHECKBOX, self.EvtCheckBox, cb2) sizer = wx.BoxSizer(wx.VERTICAL) sizer.AddMany( [ cb1,
Re: how you know you're a programming nerd
[EMAIL PROTECTED] wrote: > John Salerno wrote: >> So last night I had a dream that me and two other guys needed to get a >> simple task done in Java. We were staring at the problem in confusion >> and I kept saying "First we have to create a class, then instantiate it, >> then..." etc. etc. They didn't agree with me so we kept arguing back and >> forth about it. >> >> Finally, in frustration, I shout "God, Python is so much easier than any >> other language!" :) >> >> It's not the first time I've had a dream about programming (and the >> others were much more uncomfortable because they involved math), but >> it's the first time Python has snuck into my subconscious. > > I think Freud might have had something to say about that. I don't even want to know how he would have translated python. -- http://mail.python.org/mailman/listinfo/python-list
Python+GNU/Linux+Oracle 10 g Express Edition+cx_Oracle
Hi!! I'd like to install Oracle 10 g express edition over Ubuntu to use with Python 2.4. I have installed Ubuntu, Python 2.4 and Oracle database. I think that I have installed correctly cx_Oracle because I have cx_Oracle.so in /usr/share/python2.4/site-packages/ directory. My environment variables are ORACLE_HOME=/usr/lib/oracle and LD_LIBRARY_PATH=$ORACLE_HOME/lib. I am trying to connect to Oracle database: >>>import cx_Oracle >>>db=cx_Oracle.connect('sergio/[EMAIL PROTECTED]') Traceback (most recent call last):File "", line 1, in ? RuntimeError: Unable to acquire Oracle environment handle What is the problem? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython Question
Well you will need to download the " docs demos and tools " and that contains a windows help file that is easily searchable. If you run Linux there is a Gnome tool to run the help file in Linux if you so wish. -- http://mail.python.org/mailman/listinfo/python-list
best way to install python modules on linux
Hi, I am pretty new to python and will use it mainly in combination with scientific packages. I am running ubuntu breezy right now and see that some packages are out of date. Do you have any suggestion, how I can get/keep the latest python modules (e.g. scipy, numpy,...) on my ubuntu system? I.e. does there exist any script/program, which downloads and installs automatically the latest stable releases of selected modules? It would be nice, if the program can remove the installed modules, too!? Or would it be easier to stick to apt/deb and create own packages ... Greetings! Fabian -- http://mail.python.org/mailman/listinfo/python-list
os.execvp() is giving me trouble
Hi All, Sorry if this is a newbie question. I promise I have RTFMed, though. Here goes: I'm trying to invoke an external program from python. The program is jar.exe, which is part of java. The following is the command I want to send: jar -xvf file1.jar jile2.jar file3.jar os.execvp(file, args) is described as follows: execvp(file, args) Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process. args may be a list or tupe of strings. I have a list of strings that looks like this: jarfiles = ['c:\\documents and settings\\myname\\mydir\\file1.jar', 'c:\\documents and settings\\myname\\mydir\\file2.jar', 'c:\\documents and settings\\myname\\mydir\\file3.jar'] The jar command takes some arguments. I would like to give it the arguments "-xvf". I have tried both of the following options: 1) inserting "-xvf" as the first element in the list above and then calling os.execvp("jar", jarfiles); 2) directly calling without the list, as in os.execlp("jar", "-xvf", "c:\\documents and settings\\myname\\mydir\\file1.jar", "c:\\documents and settings\\myname\\mydir\\file2.jar", "c:\\documents and settings\\myname\\mydir\\file3.jar"); Neither of these options seems to work. The output looks like the following: C:\Documents and Settings\mydir\pythonscripts>Illegal option: : Usage: jar {ctxu}[vfm0Mi] [jar-file] [manifest-file] [-C dir] files (more usage output here...) If anyone knows how I can invoke a command and pass it a list of arguments, that would be helpful. By the way, I know that the pathnames of my jar files have spaces in them, so I have also tried enclosing them in double quotes by adding a double quote to the begining and end of every element in my list of jar files. I still got a very similar error. I also tried changing the paths to relative paths that didn't contain spaces and I still got a very similar error. Thanks, Jon -- complete source - import os; import glob; # define some useful directories we will be using in this script. home_dir = os.path.normcase(os.environ['USERPROFILE']); dist_dir = os.path.normcase(home_dir+"/mydir/dist/"); other_dir = os.path.normcase(home_dir+"/otherDir/"); os.chdir(home_dir); # get all the jar files in the mydir distribution directory jarfiles = glob.glob(dist_dir+"\\*.jar"); # delete every directory and file in the otherDir directory for root, dirs, files in os.walk(other_dir, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) # make the empty otherDir directory the current working directory os.chdir(other_dir); # for each jar file, extract it into the otherDir directory for jarfile in jarfiles: os.execlp("jar", "-xvf", jarfile); -- end source -- (I also tried using execvp and a list of arguments (all the jarfiles) but that didn't work either.) -- This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden. -- http://mail.python.org/mailman/listinfo/python-list
Re: glob and curly brackets
This would indeed be a nice feature. The glob module is only 75 lines of pure python. Perhaps you would like to enhance it? Take a look. -- http://mail.python.org/mailman/listinfo/python-list
how to use urllib2 to get a page with a socks 5 proxy?
example, the proxy server is :123.123.123.123 and the port is :1080 and the username/password is : user/pass I want to open http://www.google.com how to write this script? thanks. -- http://mail.python.org/mailman/listinfo/python-list
Screen placement based on screen resolution
I am trying to place a dialog in the center of the screen based on a users screen resolution. I can get the width and height of the screen, but I can't seem to use the following: root.geometry('WxH+X+Y') It appears the values for X and Y need to be integers and not a variable like width/2-40 S -- http://mail.python.org/mailman/listinfo/python-list
Re: Why did someone write this?
Sandra-24 wrote: > try: >exc_type, exc_value, exc_traceback = sys.exc_info() ># Do something > finally: >exc_traceback = None > > Why the try/finally with setting exc_traceback to None? The python docs > didn't give me any clue, and I'm wondering what this person knows that > I don't. You just have not found the right part of the doc: http://docs.python.org/lib/module-sys.html#l2h-337 -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ -- http://mail.python.org/mailman/listinfo/python-list
What does 'repair Python 2.5a1' do?
What does the repair command in the 2.5a1 msi installer do? Apparently it does not replace changed files, although it seems to replace deleted files. Thomas -- http://mail.python.org/mailman/listinfo/python-list
calculating system clock resolution
Hello all I have the problem of how to calculate the resolution of the system clock. Its now two days of head sratching and still there is nothing more than these few lines on my huge white sheet of paper stiring at me. Lame I know. import time t1 = time.time() while True: t2 = time.time() if t2 > t1: print t1, t2 # start calculating here break BTW t1 and t2 print out equal up to the fraction on my machine. What does python know that I don't? A pointer to the source lines where this is implemented would even be helpfull to clear this out. Can't seem to find it. Anyone any ideas? -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython Question
Thanks, I use Ubuntu Linux and there is tool called xchm which lets you do that. RunLevelZero wrote: > Well you will need to download the " docs demos and tools " and that > contains a windows help file that is easily searchable. If you run > Linux there is a Gnome tool to run the help file in Linux if you so > wish. -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to install python modules on linux
Fabian Braennstroem wrote: > Hi, > > I am pretty new to python and will use it mainly in > combination with scientific packages. I am running ubuntu > breezy right now and see that some packages are out of date. > Do you have any suggestion, how I can get/keep the latest > python modules (e.g. scipy, numpy,...) on my ubuntu system? > I.e. does there exist any script/program, which downloads > and installs automatically the latest stable releases of selected > modules? It would be nice, if the program can remove the > installed modules, too!? You will probably want to look at easy_install. http://peak.telecommunity.com/DevCenter/EasyInstall With easy_install, you could do something like the following: $ easy_install TurboGears and get the TurboGears package and all of its dependencies built and installed as eggs (the packaging format that easy_install uses; read the page I gave above). The packages are installed as self-contained bundles, so you can delete them easily using rm. There are plenty of opportunities for the community (i.e., you and I :-)) to contribute utility scripts that make such things easier. Unfortunately, neither numpy nor scipy will automatically work with the easy_install script at the moment. However, you can download the source and build eggs manually once you have the setuptools package installed (setuptools is the package that provides easy_install). You can then install the built eggs using easy_install. > Or would it be easier to stick to apt/deb and create own > packages ... Ubuntu is pretty good with keeping up-to-date Python packages, scipy being a notable exception in your case and mine. I would recommend using the Ubuntu packages for packages that are relatively less important to you and using easy_install for the packages for which you need the absolute latest version. -- Robert Kern [EMAIL PROTECTED] "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: how you know you're a programming nerd
Keep on coding. It'll just go away.. -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to install python modules on linux
You should consider gentoo as it big on python with all the latest packages. And no, installing doesn't take much effort. -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to install python modules on linux
Fabian Braennstroem wrote: > > I am pretty new to python and will use it mainly in > combination with scientific packages. I am running ubuntu > breezy right now and see that some packages are out of date. You can quite often backport some of the newer packages from packages.ubuntu.com, although this can often lead to a lot of work backporting dependencies and working around changes to the build environment in more recent Ubuntu work. For example, I promised Tim Parkin that I'd look into making Ubuntu Hoary packages for the python.org tools, but got substantially slowed down looking into backporting the Twisted 2 packages (which are only some of the many dependencies that Pyramid seems to have). Of course, I could just do a "python setup.py install" and forget about all this, but I don't want to discover bizarre behaviour later on in some installed package because some other, rarely-used package trampled over some important files or caused some naming conflict when it was installed. > Do you have any suggestion, how I can get/keep the latest > python modules (e.g. scipy, numpy,...) on my ubuntu system? > I.e. does there exist any script/program, which downloads > and installs automatically the latest stable releases of selected > modules? It would be nice, if the program can remove the > installed modules, too!? The removal part is typically the neglected thing here. My habit right now is to package up Python modules into Debian packages and to install them that way. Once upon a time, on Red Hat, I played with checkinstall [1] to create packages of things that didn't have a "make uninstall" feature, but I'm now fairly practised at making Debian packages that seem to work - thanks must go to Andrew Kuchling whose packaging scripts (from some software which he maintains) served as the basis for my own packaging attempts. > Or would it be easier to stick to apt/deb and create own > packages ... There's a big incentive to use the native package system: it works with the administration tools you have installed, and your packages should then integrate properly with all the other packages on your system. I've made packages from my own works and distributed them, and changing even a simple command issuing experience to a point-and-click installation experience does seem to have a dramatic influence on whether people will bother looking at software or not. Plus, they can always easily remove the software afterwards. ;-) Paul [1] http://asic-linux.com.mx/~izto/checkinstall/ -- http://mail.python.org/mailman/listinfo/python-list
Re: win32com
Hi! Answer in the mailing-list. @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Screen placement based on screen resolution
Tkinter takes strings as its arguments; it's TCL's legacy. You can use string formatting for this: x = width/2-40 y = height/2-30 root.geometry('%ldx%ld+%ld+%ld' % (width, height, x, y)) -- http://mail.python.org/mailman/listinfo/python-list
Re: Characters contain themselves?
WENDUM Denis 47.76.11 (agent) a écrit : > > While testing recursive algoritms dealing with generic lists I stumbled > on infinite loops which were triggered by the fact that (at least for my > version of Pyton) characters contain themselves. There is *no* character type in Python. 'a' is a string, and of course the string 'a' is a substring of string 'a'. -- http://mail.python.org/mailman/listinfo/python-list
Re: Screen placement based on screen resolution
Thanks. S "Lonnie Princehouse" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Tkinter takes strings as its arguments; it's TCL's legacy. You can use > string formatting for this: > > x = width/2-40 > y = height/2-30 > > root.geometry('%ldx%ld+%ld+%ld' % (width, height, x, y)) > -- http://mail.python.org/mailman/listinfo/python-list