Leipzig Python User Group - First Meeting 14.Feb.2006
We will meet the first time on 14.02.2006 at 8 pm. at the Training Centre of the Python Academy, which is located at Zur Schule 20, 04158 Leipzig, Germany. Our topic is the formation of the Leipzig Python User Group, or LE-Snakes. Food and drinks are provided. Please send a short mail to [EMAIL PROTECTED] to notify if you come, so we can make appropriate arrangements. The meeting will take place regularly once a month. The Training Centre of the Python Academy will be the default meeting place. Other locations will be announced. We plan to have one presentation per meeting about Python related topics. The title of the first presentation is: Mike Müller Parallelisierung von Pythonanwendungen mit Python Remote Objects (PYRO)| The presentation will be given in German. There are slides available in English also. If there is demand the presentation can be given in English as well. Everybody who uses Python, plans to do so or is interested in learning more about the language is encouraged to participate. While the meeting language will be mainly German, English speakers are very welcome. We will provide English interpretation if needed. Current information are available here: http://www.python-academy.de/LE-Snakes/index.html Wir treffen uns zum ersten Mal am 14.02.2006. um 20:00 Uhr im Schulungszentrum der Python Academy, Zur Schule 20, 04158 Leipzig. Unser Thema ist die Gründung der Leipzig Python User Group, der LE-Snakes. Für das leibliche Wohl wird gesorgt. Wir bitten um kurze Anmeldung per e-mail an: [EMAIL PROTECTED] Der Stammtisch soll regelmäßig einmal pro Monat in Leipzig stattfinden. Als Treffpunkt steht das Schulungszentrum der Python Academy zur Verfügung. Andere Treffpunkte werden bei den Einladungen zum Stammtisch bekannt gegeben. Geplant ist ein Vortrag zu einem Python-relevanten Thema pro Treffen. Der Titel des Vortrages des ersten Treffens lautet: Mike Müller Parallelisierung von Pythonanwendungen mit Python Remote Objects (PYRO) Teilnehmen kann jeder, der Interesse an Python hat, die Sprache bereits nutzt oder nutzen möchte. Die Arbeitssprachen des Treffens ist Deutsch. English sprechende Python-Enthusiastsen sind trotzdem herzlich eingeladen. Wir übersetzen gern. Aktuelle Infomationen dazu gibt es hier: http://www.python-academy.de/LE-Snakes/index.html -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Generators vs. Functions?
On Sun, 05 Feb 2006 03:31:24 +, Neil Schemenauer wrote: Peter Hansen [EMAIL PROTECTED] wrote: More precisely, the state of the function is *saved* when a yield occurs, so you certainly don't *recreate* it from scratch, but merely restore the state, and this should definitely be faster than creating it from scratch in the first place. Right. Resuming a generator is faster than calling a function. Have you actually measured this, or are you just making a wild guess? According to a short test performed by Magnus Lycka, resuming a generator takes more time than calling a function. My own test agrees. Here is my test, using Python 2.3. I've tried to make the test as fair as possible, with the same number of name lookups in both pieces of test code. # straight function, two name lookups import timeit t1 = timeit.Timer(stmt=func.next(), setup= ... class K: ... pass ... ... def next(): ... return 1 ... ... func = K() ... func.next = next ... ) t1.timeit() 0.63980388641357422 # generator, two name lookups t2 = timeit.Timer(stmt=gen.next(), setup= ... def g(): ... while 1: yield 1 ... ... gen = g() ... ) t2.timeit() 0.82081794738769531 # straight function, one name lookup t3 = timeit.Timer(stmt=f(), setup= ... def f(): ... return 1 ... ) t3.timeit() 0.47273492813110352 # generator, one name lookup t4 = timeit.Timer(stmt=gnext(), setup= ... def g(): ... while 1: yield 1 ... ... gnext = g().next ... ) t4.timeit() 0.55085492134094238 So on the basis of my tests, there is a small, but significant speed advantage to _calling_ a function versus _resuming_ a generator. Of course the other advantages of generators often far outweigh the tiny setup cost each time you call one. In addition, for any complex function with significant execution time, the call/resume time may be an insignificant fraction of the total execution time. There is little or no point in avoiding generators due to a misplaced and foolish attempt to optimise your code. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python support a peek like method for its file objects?
On Sun, 05 Feb 2006 05:45:24 +, Avi Kak wrote: Hello: Does Python support a peek like method for its file objects? I'd like to be able to look at the next byte in a disk file before deciding whether I should read it with, say, the read() method. Is it possible to do so in Python? # WARNING: untested fp = file(some file on disk, rb) b = while 1: # peek at the next byte c = fp.read(1) # decide whether to read it if c == ?: # pretend we never read the byte del c fp.seek(-1, 1) # but be careful in text mode! break # now read the byte for real b = fp.read(1) if not b: # we've reached the end of the file break fp.close() I'm not sure exactly why you'd want to do this, but it should be doable, at least for files that support seeking. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python support a peek like method for its file objects?
On Sun, 05 Feb 2006 19:25:21 +1100, Steven D'Aprano wrote: On Sun, 05 Feb 2006 05:45:24 +, Avi Kak wrote: Hello: Does Python support a peek like method for its file objects? I'd like to be able to look at the next byte in a disk file before deciding whether I should read it with, say, the read() method. Is it possible to do so in Python? # WARNING: untested Yes, and also completely broken. I don't know what I was thinking. Sigh. Try this (also untested, but not so obviously broken): fp = file(some file on disk, r) # should work in text mode b = while 1: # peek at the next byte c = fp.read(1) # decide whether to read it if c == ?: # pretend we never read the byte fp.seek(-1, 1) # but be careful in text mode! break # now read the byte for real b = c if not b: # we've reached the end of the file break fp.close() -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python support a peek like method for its file objects?
Avi Kak wrote: Hello: Does Python support a peek like method for its file objects? I'd like to be able to look at the next byte in a disk file before deciding whether I should read it with, say, the read() method. Is it possible to do so in Python? Your answer would be much appreciated. If it's a seekable file (not a stream input) then you can use file.tell() to get the current position, then file.read() to read some data, then file.seek(), giving it the position you got from file.tell(), to rewind to the same position. This is the safe version; in the unsafe version you can skip the file.tell() stuff and just use relative positioning in the file.seek() operation. If it's a socket, you can use recv() or recvfrom() if you set the flags argument to MSG_PEEK. If it's a stream, you're out of luck, and you'll have to buffer the data yourself, although you can use select() or poll() to check on availability of data if that's what you really want. At least, in theory. I haven't tried any of this in Python yet. --Blair -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python support a peek like method for its file objects?
Here's a version that should work in text mode as well: fp = file(some file on disk, r) b = while 1: p = fp.tell() # peek at the next byte; moves file position only if a byte is read c = fp.read(1) # decide whether to read it if c == ?: # pretend we never read the byte fp.seek(p) break # now read the byte for real b = c if not b: # we've reached the end of the file break fp.close() --Blair -- http://mail.python.org/mailman/listinfo/python-list
Re: Generators vs. Functions?
Steven D'Aprano wrote: So on the basis of my tests, there is a small, but significant speed advantage to _calling_ a function versus _resuming_ a generator. now add state handling to your micro-benchmark, and see if the function example still runs faster. (hint: functions and generators do different things, and are designed for different use cases. they're not two different ways to do the same thing, and benchmarks that ignore that simple fact are pretty much use- less, except, perhaps, for a very small group of VM developers.) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: OO conventions
Alex Martelli wrote: As you see, static methods have a small extra lookup cost (a couple hundred nanoseconds on my oldish laptop); I would've expected the opposite effect...I guess the runtime considers instances more active than the static portion of a class. Premature optimization is the root of all evil in programming, as Knuth wrote quoting Hoare -- and anybody who's read Knuth's work knows he is anything BUT indifferent to real optimization; the key is avoiding that premature part!-) Apropos of which someone mentioned in a thread on Slashdot today about writing an entire program's code in Python first and then optimizing portions to C or C++ only as performance warrants. Seems like a good idea. I've noticed Python is a lot easier to get up-and-running with, even if you're as unfamiliar with it as I am, compared to the other two. --Blair -- http://mail.python.org/mailman/listinfo/python-list
ActiveGrid and Python Frameworks.
Why is no one talking about ActiveGrid, which at least on the surface seems to be the most polished way to build web applications in Python so far. They have a sound financial backing, $10 million when I last heard, made news on non-Python circles, have a relatively friendly authoring environment and are probably addressing the enterprise more specifically than any other web framework. It somehow did not grow on me but I would love to hear what others' experiences are compared to other frameworks they use. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to run BeautifulSoup in Jython
ye juan schrieb: Hi, Anyone tries to use BeautifulSoup ( http://www.crummy.com/software/BeautifulSoup/ ) in Jython? I can not run that ,the error that Jython gives me is: unpack sequence too long. You've asked that on th jython mailing list and got a negative answer. What makes you think this forum here, with way more broader scope, will yield a different answer on that very specific topic? And your asking pretty much of people to guess what's wrong and maybe could be fixed, if all you provide is a single sentence of error-message. I suggest you read http://www.catb.org/~esr/faqs/smart-questions.html and come back with a little more information -like stacktraces, jython version used and so on. Then maybe, but only maybe, someone can tell if and how one can make BeautifulSoup run under jython. Diez -- http://mail.python.org/mailman/listinfo/python-list
jython newbee general question docu / os.fstat
Hi there, unfortunately I am new to Jython and my Jython Essentials book is still in the mail. I looked into the Jython API Doc but could not find the information. I am porting a Python library to Jython and some parts are missing. My question basically is where do I find information on what to use instead. E.g. I could not find information on the os module. I do not find the sys module docu either. The concrete problem is I have something like os.fstat(infile.fileno()) which provokes: IOError: fileno() is not supported in jpython. If this question is already documented somewhere please point me to this direction. I was not able to find it. Best Regards, Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Generators vs. Functions?
Steven D'Aprano wrote: t1.timeit() 0.63980388641357422 ... t2.timeit() 0.82081794738769531 So on the basis of my tests, there is a small, but significant speed advantage to _calling_ a function versus _resuming_ a generator. I get the same, but the difference is much less on my system: min(t1.timeit() for i in range(3)) 0.43929577641858941 min(t2.timeit() for i in range(3)) 0.46473169075954956 You missed though what is perhaps a more representative case. Generators have state, so for a fair comparison you need to restore some state. I think a fairer comparison is: t5 = timeit.Timer(stmt=func.next(), setup= class K: pass def next(self): return 1 func = K() ) min(t5.timeit() for i in range(3)) 0.58508302032805659 The method call is slower than the generator resumption and that is without even accessing any of the saved state. If you do access the saved state the generator runs at about the same speed as the original (local variable access is about as fast as accessing a constant), but the method slows down even more: t6 = timeit.Timer(stmt=gen.next(), setup= def g(n): while 1: yield n gen = g(42) ) min(t6.timeit() for i in range(3)) 0.46405506845144373 t7 = timeit.Timer(stmt=func.next(), setup= class K: def __init__(self, n): self.n = n def next(self): return self.n func = K(42) ) min(t7.timeit() for i in range(3)) 0.67426781895460408 -- http://mail.python.org/mailman/listinfo/python-list
Booksigning Party at PyCon This Year!
Because many authors of books related to Python will be in attendance at PyCon, we would like to organize a book signing activity. It seems logical to hold it Saturday night at the party at the Nerdbooks.com bookstore. Bring your own books or buy new ones in the store! And if you're an author in attendance who would like to promote your book, drop an email to jeff at taupro.com or come forward when we call the book signing to order in the store. So that the bookstore can have copies on-hand, we'd like to collect a list of titles you'd consider having signed. Please edit the following wiki page and add your choices. Authors, you can add your books too. http://us.pycon.org/TX2006/BookSigning -Jeff -- http://mail.python.org/mailman/listinfo/python-list
Re: Generators vs. Functions?
On Sun, 05 Feb 2006 09:49:21 +0100, Fredrik Lundh wrote: Steven D'Aprano wrote: So on the basis of my tests, there is a small, but significant speed advantage to _calling_ a function versus _resuming_ a generator. now add state handling to your micro-benchmark, and see if the function example still runs faster. ¿Que Mr Fawlty? Sorry, I'm not sure I follow what you mean. Do you mean, Make the function and generator do something significant? I expected that people would understand that I was talking only about the overhead of calling the function or generator, not the overall time needed to perform some useful task. Sorry for the less than clear explanation. (hint: functions and generators do different things, and are designed for different use cases. they're not two different ways to do the same thing, and benchmarks that ignore that simple fact are pretty much use- less, except, perhaps, for a very small group of VM developers.) I never meant to imply that generators were somehow worse than functions. As you say, they have different purposes, and for the sort of use case that generators are good for, the tiny extra overhead in restoring a generator is a cost well worth paying. But it is a cost. I personally don't believe it is a significant cost, except maybe for the odd special case or two. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
rexec in jython??
Hi there, I at the moment port a library from Python to Jython (at lease I try to do so :-))). The library uses the Rexec to form a type adapter to cast parameters given as text into the according Jython type. I learned rexec is not available in Jython. Is something that is commonly used in Jython for such tasks available? In general: how do I find such information by myself? Best Regards, Mark -- http://mail.python.org/mailman/listinfo/python-list
rexec in jython??
Hi there, I at the moment port a library from Python to Jython (at lease I try to do so :-))). The library uses the Rexec to form a type adapter to cast parameters given as text into the according Jython type. I learned rexec is not available in Jython. Is something that is commonly used in Jython for such tasks available? In general: how do I find such information by myself? Best Regards, Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: jython newbee general question docu / os.fstat
Mark Fink schrieb: Hi there, unfortunately I am new to Jython and my Jython Essentials book is still in the mail. I looked into the Jython API Doc but could not find the information. I am porting a Python library to Jython and some parts are missing. My question basically is where do I find information on what to use instead. E.g. I could not find information on the os module. I do not find the sys module docu either. The concrete problem is I have something like os.fstat(infile.fileno()) which provokes: IOError: fileno() is not supported in jpython. If this question is already documented somewhere please point me to this direction. I was not able to find it. The general problem lies within JAVA. Instead of python that tries to incorporate os-specific modules, it focuses of a common subset - excluding lots of functionality. fstat and lots of functions in os are not available - for example, you can't change the current working directory. fstat is a posix-call, which is also not available. The general rule of thumb is: whenever you encounter something missing, try to find a solution for java. That could e.g. be a JNI-interfaced special library to access the com-port or something else. If such a solution exists, use that (its easy enough from jython). If not - bad luck. Diez -- http://mail.python.org/mailman/listinfo/python-list
New Mailing List for PyCon Technology and Conference Software
I have arranged for the creation of a new mailing list under python.org for the discussion of software development for PyCon, of any type and for any year. We've been sending a lot of email privately and making the process more visible would be good I think. There are a few disjoint efforts and a list would bring them together. This list is also for the discussion of other technical matters related to PyCon such as the audio/video recording efforts. This list can also help us prepare for the conference-software sprint that Andrew Kuching is pushing for PyCon this year. Please consider signing up by visiting: http://mail.python.org/mailman/listinfo/pycon-tech -Jeff -- http://mail.python.org/mailman/listinfo/python-list
Re: rexec in jython??
sorry for the double post! It is the r_eval() functionality of the rexec module I am looking forward to replace -- http://mail.python.org/mailman/listinfo/python-list
Re: rexec in jython??
this is really funny... I tried to use eval(String) as an replacement. It works now but the calculation results from my tests are not as expected: 2 + 3 = 23 !!! 2 - 3 = 2-3... I have the feeling that there is a really easy solution for this. Unfortunately I have no enough experience -- http://mail.python.org/mailman/listinfo/python-list
Re: fairly large webapp: from Java to Python. experiences?
Giovanni Bajo wrote: Also Python code is pretty bare-metal, so that file.write or socket.write go to the syscall immediately. Try that in Java and you'll find 30 layers of complex abstractions for doubtful benefits and obvious slowness. +1 QOTW (I'd recommend the whole post but it might be too long.) Cheers, AdSR -- http://mail.python.org/mailman/listinfo/python-list
Re: rexec in jython??
Mark Fink wrote: this is really funny... I tried to use eval(String) as an replacement. It works now but the calculation results from my tests are not as expected: 2 + 3 = 23 !!! 2 - 3 = 2-3... I have the feeling that there is a really easy solution for this. Unfortunately I have no enough experience How about showing code? Otherwise we all have to use our crystal balls, and these thingies tend to be not so precise... Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Webmail with Python
On Sat, 04 Feb 2006 15:50:00 -0600, Larry Bates wrote: Thomas Guettler wrote: Hi, Is there an application like Squirrelmail[1] written in python? I want to access IMAP folder with a web-browser. Google shows me some dead projects. Most webmail applications seem to be written in PHP. Is there a useable webmailer written in python? Thomas Google turned up the following: http://bobomail.sourceforge.net/ The last release is soon four years old. I think it is dead. Look at the last message in the mailing list: http://sourceforge.net/mailarchive/forum.php?thread_id=8807764forum_id=6902 Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs C for a mail server
John J. Lee wrote: I guess the same is true of Python in some respects: it's still incrementally changing (more than C++, I guess), and isn't all that much younger than C++ (around 15 and 23 years old respectively). But C++ is almost entirely backwards compatible with C, which adds another dozen years or so... -- http://mail.python.org/mailman/listinfo/python-list
Re: rexec in jython??
This is the original code section of the library including the comments: class AutoAdapter(TypeAdapter): This adapter returns a type based on the format of the table cell contents, following python's rules for literals (plus a few others). We could fall back on this when we don't know what type is expected. I am lazy and so use rexec to do the work. #Note: The RExec class can prevent code from performing unsafe #operations like reading or writing disk files, or using TCP/IP #sockets. However, it does not protect against code using #extremely large amounts of memory or processor time. r_eval = RExec().r_eval def parse(self,s): if s.strip().lower() == 'true': return 1 elif s.strip().lower() == 'false': return 0 else: try: return self.r_eval(s) except SystemExit: return None except: return s I completely removed the import of rexec and replaced return self.r_eval(s) with return self.eval(s) -- http://mail.python.org/mailman/listinfo/python-list
Best way of finding terminal width/height?
Hi all! I use python for writing terminal applications and I have been bothered by how hard it seems to be to determine the terminal size. What is the best way of doing this? At the end I've included a code snippet from Chuck Blake 'ls' app in python. It seems to do the job just fine on my comp, but regrettably, I'm not sassy enough to wrap my head around the fine grain details on this one. How cross-platform is this? Is there a more pythonic way of doing this? Say something like: from ingenious_module import terminal_info cols, rows = terminal_info.size() Thanks for your time (and thanks Chuck for sharing your code!) /Joel Hedlund IFM Bioinformatics Linköping University Chuck Blake's terminal_size code snippet: (from http://pdos.csail.mit.edu/~cblake/cls/cls.py). def ioctl_GWINSZ(fd): TABULATION FUNCTIONS try:### Discover terminal width import fcntl, termios, struct, os cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) except: return None return cr def terminal_size(): ### decide on *some* terminal size # try open fds cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) if not cr: # ...then ctty try: fd = os.open(os.ctermid(), os.O_RDONLY) cr = ioctl_GWINSZ(fd) os.close(fd) except: pass if not cr: # env vars or finally defaults try: cr = (env['LINES'], env['COLUMNS']) except: cr = (25, 80) # reverse rows, cols return int(cr[1]), int(cr[0]) -- http://mail.python.org/mailman/listinfo/python-list
Re: rexec in jython??
Mark Fink wrote: This is the original code section of the library including the comments: class AutoAdapter(TypeAdapter): This adapter returns a type based on the format of the table cell contents, following python's rules for literals (plus a few others). We could fall back on this when we don't know what type is expected. I am lazy and so use rexec to do the work. #Note: The RExec class can prevent code from performing unsafe #operations like reading or writing disk files, or using TCP/IP #sockets. However, it does not protect against code using #extremely large amounts of memory or processor time. r_eval = RExec().r_eval def parse(self,s): if s.strip().lower() == 'true': return 1 elif s.strip().lower() == 'false': return 0 else: try: return self.r_eval(s) except SystemExit: return None except: return s I completely removed the import of rexec and replaced return self.r_eval(s) with return self.eval(s) And what does self.eval look like? Crystal ball still not working Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling
Simon Faulkner wrote: Pardon me if this has been done to death but I can't find a simple explanation. I love Python for it's ease and speed of development especially for the Programming Challenged like me but why hasn't someone written a compiler for Python? I guess it's not that simple eh? In case you really just want to run your Python programs on computers without Python installed, there are several tools that will create a myprogram.exe from your myprogram.py. These tools don't make machinecode executables. Instead, they basically bundle python.exe, your program and whatever is needed into an single .exe-file. Google for e.g. py2exe or cx_freeze. -- http://mail.python.org/mailman/listinfo/python-list
Interpreting Unicode scripts
Hello, I am considering embedding Python in a C++ application, which works internally in UTF-16. The only API I can find for running scripts is PyRun_SimpleString(const char*). Does that mean that Python is unable to execute scripts containing characters from more than one code page? Thanks, Keith MacDonald -- http://mail.python.org/mailman/listinfo/python-list
NumPy error
Hello: I am using the following versions of Python and packages on Windows XP (SP2): Python 2.4.2 NumPy 0.9.4.win32-py2.4 SciPy 0.4.4 for Python 2.4 and Pentium 4/SSE2 In the Python Shell I am running the following: from scipy.optimize import fmin def rosen(x): return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0) x0 = [1.3, 0.7, 0.8, 1.9, 1.2] xopt = fmin(rosen, x0) I get the following error: Traceback (most recent call last): File pyshell#6, line 1, in -toplevel- xopt = fmin(rosen, x0) File C:\Python24\Lib\site-packages\scipy\optimize\optimize.py, line 191, in fmin sim = Num.zeros((N+1,N),x0.dtypechar) AttributeError: 'numpy.ndarray' object has no attribute 'dtypechar' Any idea what the problem might be? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Interpreting Unicode scripts
Keith MacDonald wrote: I am considering embedding Python in a C++ application, which works internally in UTF-16. The only API I can find for running scripts is PyRun_SimpleString(const char*). Does that mean that Python is unable to execute scripts containing characters from more than one code page? reading PEP 263 might help: http://www.python.org/peps/pep-0263.html (summary: encode as utf-8, prepend # coding: utf-8\n, and you're done) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling
For short : this was kind of a joke... I understand that what you were looking for is a 'native code' compiler. AFAIK, this could of course be done, but due to Python's very dynamic nature, it's not sure this would lead to drastically better performances. This is a standard response to a rather frequent question here. But I am not sure I ever understood. Scheme / Lisp are about as dynamic as Python. Yet they have quite efficient native compilers. Ex: Bigloo Scheme. Another standard response is nobody felt the need or got around to it. And yet a number of Lisp and Scheme compilers exist when these languages have a much smaller user base. Am I missing something here? -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling
Ravi Teja wrote: This is a standard response to a rather frequent question here. But I am not sure I ever understood. Scheme / Lisp are about as dynamic as Python. if that were fully true, it would be fairly trivial to translate Python to scheme or lisp and compile it. Another standard response is nobody felt the need or got around to it. And yet a number of Lisp and Scheme compilers exist when these languages have a much smaller user base. Am I missing something here? an endless supply of grad students ? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: NumPy error
jason wrote: Hello: I am using the following versions of Python and packages on Windows XP (SP2): Python 2.4.2 NumPy 0.9.4.win32-py2.4 SciPy 0.4.4 for Python 2.4 and Pentium 4/SSE2 I fell for that yesterday. Cost me two hours. You have to install NumPy 0.9.2. Make sure you cleaned up the site-packages, and if you build stuff yourself, a clean rebuild is necessary. Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: rexec in jython??
:-))) it works! I replaced it to return eval(s) and the results look extremely well guess I should get one of this crystal balls myself. one minor issue is still left: correct me if I am wrong: result of 2/-3 is 0 (at least this is how it is defined in the testcase) In Jython 2.1.3: 2/-3 -1 Anyway many thanks for your help. Without this would have taken forever. -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way of finding terminal width/height?
On 2006-02-05, Joel Hedlund [EMAIL PROTECTED] wrote: I use python for writing terminal applications and I have been bothered by how hard it seems to be to determine the terminal size. What is the best way of doing this? The way used in the code you found. Alternatively, yould use ncurses, but that's massive overkill if all you want is the terminal window size. At the end I've included a code snippet from Chuck Blake 'ls' app in python. It seems to do the job just fine on my comp, but regrettably, I'm not sassy enough to wrap my head around the fine grain details on this one. Which details? We'd be happy to explain the code. Not that you need to understand the details to use the code. How cross-platform is this? It will work on any Unix system you're likely to encounter. I know it works on BSD, Solaris, and Linux. I no longer yave acces to a v7 system, but I'm pretty sure it would have worked on that as well -- except the one I used didn't have a large enough address space or disk drive to run Python. I don't know if it will work on MS Windows or not. Is there a more pythonic way of doing this? What's unpythonic about the example you found? It looks extremely pythonic to me. The use of the or operator when making ioctl calls and the try/except block when opening a file is classically pythonic. Say something like: from ingenious_module import terminal_info cols, rows = terminal_info.size() If that's what you want, put the code you found in to a file named ingenious_module.py. I don't see the point of of layering the namespace like that, though. Just call it terminal_info.py and do import terminal_info cols,rows = terminal_info.terminal_size() -- Grant Edwards grante Yow! Oh, FISH sticks, at CHEEZ WHIZ, GIN fizz, visi.comSHOW BIZ!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling
This is a standard response to a rather frequent question here. But I am not sure I ever understood. Scheme / Lisp are about as dynamic as Python. Yet they have quite efficient native compilers. Ex: Bigloo Scheme. If you provide the necessary annotations for optimization. Not sure about runtime. But then that is what psyco does (albeit for a limited range of machines) at runtime. And even in bigloo you end up with guarding statements for typechecking and an code-size explosion. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: New Python.org website ?
whisper If you build it, they will come. /whisper http://pydotorg.dyndns.org:8000 /F -- http://mail.python.org/mailman/listinfo/python-list
Re: New Python.org website ?
Hi Fredrik Lundh schrieb: whisper If you build it, they will come. /whisper http://pydotorg.dyndns.org:8000 Have access-problem. It's dnynds.org. Perhabs not everytime Online? bye Chris Ditze-Stephan /F ___ Chris Ditze-Stephan Zentric -- http://mail.python.org/mailman/listinfo/python-list
Re: New Python.org website ?
Chris Ditze-Stephan wrote: http://pydotorg.dyndns.org:8000 Have access-problem. It's dnynds.org. no, it's dyndns.org. did you make that typo in the browser too ? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread imbalance
Peter Hansen wrote: Ivan, what makes you say that Python is bad for threads? Did the qualifcation concurrently executing/computing have some significance that I missed? Because of the GIL (Giant interpreter lock). It can be a matter of opinion, but by good threading implementation I mean that all threads in the application should run natively on the underlying (p)threads library at all times, without implicit serialization. For example, Java and perl do this, possibly also lua and C#. Python and Ruby have a giant interpreter lock which prevents two threads of pure python code (not code written in C :)) ) in one interperter process executing at the same time. Much can be said about at the same time part, but at least in one case it is unambiguous: in multiprocessor machines. Someone writing a multithreaded server application could get in trouble if he doesn't know this (of course, it depends on the exact circumstances and the purpose of the application; for example system calls which block, such as read() and write() can execute concurrently, while two while True: pass threads cannot). This is not new information, it's available in many forms in this newsgroup's archives. I think it would also make implicit problems in the situation like that of the OP, where there's a watchdog thread monitoring some job or jobs, and the job(s) intefere(s) with the GIL by contenting for it, possibly when there are lots of threads or frequent spawning of processes or threads. I don't have the intention to badmouth Python, but to emphasize that one should be familira with all the details of the tool one's using :) -- http://mail.python.org/mailman/listinfo/python-list
Importing a class, please help...
Hi, Newbie to Python and I have a question please. I am using Windows XP, SPE 0.8.2.a and Python24. I have done this: import sys print sys.path no problem there, sys imports just fine. I have a folder that I called c\JavaProjects\PythonTesting and it shows up in the output from sys.path above. I have dropped a very simple Jar in that folder and I have attempted to do an Import on it. This is where things fail. I cannot see the contents of my Jar. What am I missing here? Would somebody please drop me a hint, please? I would HIGHLY appreciate an example; does anybody know of a website or page that would show me how to do this? I realize this is a simple question and I appreciate any help somebody would give me. Regards, joe -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing a class, please help...
anon [EMAIL PROTECTED] writes: to do an Import on it. This is where things fail. I cannot see the contents of my Jar. What am I missing here? That JARs are for Java and yo're using Python? -- Jorge Godoy [EMAIL PROTECTED] Quidquid latine dictum sit, altum sonatur. - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. -- http://mail.python.org/mailman/listinfo/python-list
Learning Python
I know this is probably a stupid question, but I'm learning Python, and am trying to get the if function to work with letters/words. Basicly, I'm trying to write a script that when run, says Please enter your name: Then, if the user types myself as the name , the output is OK. Thats all I want it to do (remember, Im just new). The code Ive tryed is: x = input(raw_input(Please enter your name: )) if x==myself: print 'OK' It kinda works - I can get to the please enter your name bit but then it simply reprints your input as output. Someone please HELP! p.s. Im using Ubuntu Linux 5.10 Breezy Badger. Dont know if you need that info, but just in case. -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing a class, please help...
anon wrote: Would somebody please drop me a hint, please? Yeah, the definition of JAR is Java ARchive, why the hell would a Python script be able to read a JAR in the first place (truth is it is, a JAR file is nothing but a renamed ZIP, therefore the zipfile module allows you to read it's content) and -- more importantly -- import Java classes. Notice the difference between *Python* script and *Java* class? That's because they're two different languages. If you want to use Java classes and modules in a Pythonic context, you want Jython (http://www.jython.org/) not Python (http://www.python.org/) -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
try: x = raw_input(Please enter your name: ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Byte wrote: x = input(raw_input(Please enter your name: )) if x==myself: print 'OK' It kinda works - I can get to the please enter your name bit but then it simply reprints your input as output. Someone please HELP! -- C:\python Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. help(input) Help on built-in function input in module __builtin__: input(...) input([prompt]) - value Equivalent to eval(raw_input(prompt)). help(raw_input) Help on built-in function raw_input in module __builtin__: raw_input(...) raw_input([prompt]) - string Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading. -- Where the hell did you get the idea of stacking input on a raw_input in the first place? -- http://mail.python.org/mailman/listinfo/python-list
Re: Generators vs. Functions?
Steven D'Aprano [EMAIL PROTECTED] wrote: Have you actually measured this, or are you just making a wild guess? I haven't timed it until now but my guess it not so wild. I'm pretty familiar with the generator implementation (having written the initial version of it). In Python 2.3, resuming a generator does a small amount of setup and then calls eval_frame(). Calling a function does more setup work and then also calls eval_frame(). Here is my test, using Python 2.3. I've tried to make the test as fair as possible, with the same number of name lookups in both pieces of test code. On my machine t4 is faster than t3. Your test is not so fair because the generator is doing a while loop (executing more bytecode instructions) while the function is just returning a value (one instruction). On your machine the function call may be faster due to CPU cache effects or branch prediction. In any case, the difference you are trying to measure is extremely small. Try adding some arguments to the functions (especially keyword arguments). What your test does show is that the speed difference should not come into the decision of which construct to use. Neil -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Hi Byte! Your code should look like this: x = raw_input('Please enter your name: ') if x == 'myself': print 'OK' Because myself should be a string and not a variable name, you have to put it in quotes. Regards, Florian. -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python support a peek like method for its file objects?
Avi Kak wrote: Does Python support a peek like method for its file objects? A short answer is, No, it does not. Peek was (I believe) put into Pascal to simplify certain problems; language processing , for example, is drastically simplified by 1-character look-ahead. Pascal was designed as a teaching language, and it provided primitives to ease the work students did, rather than reflect the realities of an underlying I/O system. Building usable Pascal runtimes was a pain in the posterior for precisely this reason. Often you can build simple code to accomplish your task without implementing a full peek. Peek affects: read, tell, relative seeks, end-of-file processing, and waits for user interaction. usually you need nearly none of this. Maybe all you need is a layer around a reader with a pushback function. class ReaderWithPushback(object): def __init__(self, somefile): self._read = somefile.read self.held = '' self.sawEOF = False def read(self, length): assert length 0 while len(self.held) length and not self.sawEOF: chunk = self._read(length - len(self.held)) if chunk: self.held += chunk else: self.sawEOF = True if len(self.held) length: self.held, result = (self.held[length :], self.held[: length]) else: self.held, result = '', self.held return result def pushback(self, somestuff): self.held = somestuff + self.held def peek(self, length=1): data = self.read(length) self.pushback(data) return data --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Florian Nykrin, that works! Thanks! p.s. Xavier Morel, you seem to be using Windows, not Linux, and I got the idea of stacking input on a raw_input from the official Python Tutorial. -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
On 2/5/06, Ivan Shevanski [EMAIL PROTECTED] wrote: On 2/5/06, Florian Nykrin [EMAIL PROTECTED] wrote: Hi Byte!Your code should look like this:x = raw_input('Please enter your name: ')if x == 'myself': print 'OK' Because myself should be a string and not a variable name, you have toput it in quotes.Regards, Florian.-- http://mail.python.org/mailman/listinfo/python-list -- Oh, I was under the impression that myself is a variable name. . .Who would type in myself as their name? If it is a variable it's fine how it is, but if it is a string put it in quotes.-Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
On 2/5/06, Ivan Shevanski [EMAIL PROTECTED] wrote: On 2/5/06, Ivan Shevanski [EMAIL PROTECTED] wrote: On 2/5/06, Florian Nykrin [EMAIL PROTECTED] wrote: Hi Byte!Your code should look like this:x = raw_input('Please enter your name: ')if x == 'myself': print 'OK' Because myself should be a string and not a variable name, you have toput it in quotes.Regards, Florian.-- http://mail.python.org/mailman/listinfo/python-list -- Oh, I was under the impression that myself is a variable name. . .Who would type in myself as their name? If it is a variable it's fine how it is, but if it is a string put it in quotes.-Ivan Ugh sorry read it wrong, thats right.-- -Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Byte wrote: p.s. Xavier Morel, you seem to be using Windows, not Linux, and I got the idea of stacking input on a raw_input from the official Python Tutorial. link, please. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Use input to enter numbers, and raw_input to enter strings. For example: x = input('Enter your age: ') y = raw_input('Enter your name: ') -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Byte wrote: p.s. Xavier Morel, you seem to be using Windows, not Linux what makes you think that basic Python functions work in radically different ways on different platforms ? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Interpreting Unicode scripts
That document did help, thanks, although I was initially disconcerted to see that it's written in the future tense. Anyway, it works with Python 2.4. Keith MacDonald Fredrik Lundh [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] reading PEP 263 might help: http://www.python.org/peps/pep-0263.html (summary: encode as utf-8, prepend # coding: utf-8\n, and you're done) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: NumPy error
Thanks. After executing the first line, I now get: from scipy.optimize import fmin Overwriting fft=function fft at 0x012116F0 from scipy.fftpack.basic (was function fft at 0x011C8A70 from numpy.dft.fftpack) Overwriting ifft=function ifft at 0x01211730 from scipy.fftpack.basic (was function inverse_fft at 0x011C8AB0 from numpy.dft.fftpack) And then I get the following result: xopt = fmin(rosen, x0) Optimization terminated successfully. Current function value: 0.66 Iterations: 141 Function evaluations: 243 print xopt [ 0.99910115 0.99820923 0.99646346 0.99297555 0.98600385] Two questions: 1. does the overwriting... message make sense? I uninstalled scipy and numpy and re-installed them. 2. has the algorithm (accuracy level) changed? the result seems different from that reported in http://www.scipy.org/Wiki/Documentation?action=AttachFiledo=gettarget=scipy_tutorial.pdf on page 12. Thanks again. Diez B. Roggisch [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] jason wrote: Hello: I am using the following versions of Python and packages on Windows XP (SP2): Python 2.4.2 NumPy 0.9.4.win32-py2.4 SciPy 0.4.4 for Python 2.4 and Pentium 4/SSE2 I fell for that yesterday. Cost me two hours. You have to install NumPy 0.9.2. Make sure you cleaned up the site-packages, and if you build stuff yourself, a clean rebuild is necessary. Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
what makes you think that basic Python functions work in radically different ways on different platforms ? Assumption. Im also new to programing, so could do something stupid like think a Windows path is a command/input/etc. (really, ive done things like that before.) Now, im running this on a terminal, but am acctually writing my scripts in a text editor. How can I get a script to do a sum with the editor? e.g. it asks for a sum, then does it etc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
http://docs.python.org/tut/node6.html#SECTION00610 -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Byte [EMAIL PROTECTED] wrote: http://docs.python.org/tut/node6.html#SECTION00610 I think you're confusing the tutorial's use of: int(raw_input(... which means get a string from the user and turn it into an integer (a very common idiom), with your use of: input(raw_input(... which means get a string from the user and use it as a prompt to get any value from the user (a very peculiar usage). The difference between `int' and `input' is rather enormous. Alex -- http://mail.python.org/mailman/listinfo/python-list
how to kill a python process?
Hello! This question does not concern programming in python, but how to manage python processes. Is there a way to name a python process? At least on Linux, if I have two python programs running, they both run under the name python #pidof program1.py [empty line] #pidof program1.py [empty line] # pidof python 1249 854 Is there a way to make them run under their own names, e.g., to make it easier to kill them by name using killall? Or am I stuck with registering the pid of each python process I create and then refer to that list whenever I need to selectively stop one of them? The latter makes managing a long list of processes very cumbersome... Thanks for any help! Mack -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Byte wrote: p.s. Xavier Morel, you seem to be using Windows, not Linux I don't see how this may even remotely be relevant, Python is cross platform and (mostly) works the same regardless of the OS I got the idea of stacking input on a raw_input from the official Python Tutorial. Reference please, I never saw that anywhere in the tutorial -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Byte wrote: http://docs.python.org/tut/node6.html#SECTION00610 -- x = int(raw_input(Please enter an integer: )) -- Unless my eyes fail me, it's written int, not input, the goal of this line is to convert the return value of raw_input (a string) into an integer. -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Thanks, never knew that, but they are using raw_input as a stack, aren't they? -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Byte wrote: Assumption. Im also new to programing, so could do something stupid like think a Windows path is a command/input/etc. (really, ive done things like that before.) Don't assume anything when you have no reason to, and especially don't assume that a cross-platform programming language behaves differently from a platform to another, especially on built-in basic functions Now, im running this on a terminal, but am acctually writing my scripts in a text editor. How can I get a script to do a sum with the editor? e.g. it asks for a sum, then does it etc. parse the expression, extract the operands and the operation, apply the operation to the operands (are you trying to code a calculator?) -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Yes, sorry, didnt realise diffrence between int and input. Since i'm such an idiot at this, any links to sites for people who need an unessicerily gentle learning curve? -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling
Fredrik Lundh wrote: Ravi Teja wrote: This is a standard response to a rather frequent question here. But I am not sure I ever understood. Scheme / Lisp are about as dynamic as Python. if that were fully true, it would be fairly trivial to translate Python to scheme or lisp and compile it. I only dabble in Lisp / Scheme. I am curious on how Python is more dynamic. Another standard response is nobody felt the need or got around to it. And yet a number of Lisp and Scheme compilers exist when these languages have a much smaller user base. Am I missing something here? an endless supply of grad students ? :-). -- http://mail.python.org/mailman/listinfo/python-list
Re: NumPy error
from scipy.optimize import fmin Overwriting fft=function fft at 0x012116F0 from scipy.fftpack.basic (was function fft at 0x011C8A70 from numpy.dft.fftpack) Overwriting ifft=function ifft at 0x01211730 from scipy.fftpack.basic (was function inverse_fft at 0x011C8AB0 from numpy.dft.fftpack) And then I get the following result: xopt = fmin(rosen, x0) Optimization terminated successfully. Current function value: 0.66 Iterations: 141 Function evaluations: 243 print xopt [ 0.99910115 0.99820923 0.99646346 0.99297555 0.98600385] Two questions: 1. does the overwriting... message make sense? I uninstalled scipy and numpy and re-installed them. I get that too - and I have no clue what it means, but I consider it a left-over warning or something like that. 2. has the algorithm (accuracy level) changed? the result seems different from that reported in http://www.scipy.org/Wiki/Documentation?action=AttachFiledo=gettarget=scipy_tutorial.pdf on page 12. No idea. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: how to kill a python process?
MackS schrieb: Hello! This question does not concern programming in python, but how to manage python processes. Is there a way to name a python process? At least on Linux, if I have two python programs running, they both run under the name python #pidof program1.py [empty line] #pidof program1.py [empty line] # pidof python 1249 854 Is there a way to make them run under their own names, e.g., to make it easier to kill them by name using killall? Or am I stuck with registering the pid of each python process I create and then refer to that list whenever I need to selectively stop one of them? The latter makes managing a long list of processes very cumbersome... Yes, you are. I'm not sure how to rename processes - but _if_ it kan be done, it means that somebody else could maybe do it, too - and in case of the same name is accidentially killed. So - stick with the PID- After all, it is not _so_ cumbersome to keep a reference to e.g. popen-objects. Diez -- http://mail.python.org/mailman/listinfo/python-list
Back-end for python.org
Fredrik Lundh wrote: whisper If you build it, they will come. /whisper http://pydotorg.dyndns.org:8000 Very cool. I'd love to see something like this on the actual website... Is the hope that in the real python.org version edits will show up immediately, as they do in your version? Or that the edits will be visible in the preview pane[1] and that clicking Save Changes will basically be a patch submission? [1] Currently, the style isn't the same in the preview pane, so if, for example, I add a Sidebar: section, I don't know if I've done it right until my edit is committed. I don't know how hard it would be to fix this so that the preview pane looks just like the actual page... STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread imbalance
Ivan Voras wrote: Peter Hansen wrote: Ivan, what makes you say that Python is bad for threads? Did the qualifcation concurrently executing/computing have some significance that I missed? Because of the GIL (Giant interpreter lock). ... Much can be said about at the same time part, but at least in one case it is unambiguous: in multiprocessor machines. Okay, I thought that might be what you were talking about. I agree that in multiprocessor situations the GIL can be a problem. I'm equally certain that the GIL is not involved in the OP's problem, unless he's running custom extensions that he's produced without any awareness of the GIL. I'm pretty sure that, for the OP's situation, Python threading is perfectly fine and the problems he's facing are not inherent, but related to the way he is doing things. I don't see enough information in his post to help further though. -Peter -- http://mail.python.org/mailman/listinfo/python-list
How to create a unix shell account with Python?
Hi! I couldn't find anything on creating a new linux user account in Python documentation. Anyone has any experience with this? You just run useradd command in shell or is there a more pythonic way? Thanks, Sebastjan -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
parse the expression, extract the operands and the operation, apply the operation to the operands How? Give me some example code, but please keep it simple. are you trying to code a calculator? Not intending to, just trying to learn Python. Suppose what i'm trying to code is a but like a CLI calculator, but i'm just writing it for my own educational beifits. -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing a class, please help...
On Sun, 05 Feb 2006 17:16:38 +0100, Xavier Morel [EMAIL PROTECTED] wrote: anon wrote: Would somebody please drop me a hint, please? Yeah, the definition of JAR is Java ARchive, why the hell would a Python script be able to read a JAR in the first place You are rude to an obvious newbie here ... please keep in mind that today's stupid newbies are tomorrow's Python professionals. ... If you want to use Java classes and modules in a Pythonic context, you want Jython (http://www.jython.org/) not Python (http://www.python.org/) Maybe he /is/ running Jython and failed to explain that properly? If I understand things correctly, jar files are not tied to Java but to the java bytecode format -- which Java and Jython share. In either case, we'd need more information from the original poster. /Jorgen -- // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.dyndns.org R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling
Simon Faulkner wrote: Pardon me if this has been done to death but I can't find a simple explanation. I love Python for it's ease and speed of development especially for the Programming Challenged like me but why hasn't someone written a compiler for Python? I guess it's not that simple eh? Simon read Brett Cannon's thesis about type inference http://www.ocf.berkeley.edu/~bac/thesis.pdf -- http://mail.python.org/mailman/listinfo/python-list
Re: how to kill a python process?
On 5 Feb 2006 09:10:04 -0800, MackS [EMAIL PROTECTED] wrote: Hello! This question does not concern programming in python, but how to manage python processes. Is there a way to name a python process? At least on Linux, if I have two python programs running, they both run under the name python ... Is there a way to make them run under their own names, e.g., to make it easier to kill them by name using killall? Funny, I had to experiment a bit to see how it worked. This is surely a FAQ, because it's important. IMHO, the interpreter for a Unix program should be invisible, so that the program behaves like as a first-class process in every way. $ python foo1.py This one gets called 'python', as expected. $ head -1 foo2.py #!/usr/bin/env python $ ./foo2.py This one gets called 'python', too. I've been using this version because I read somewhere it was the recommended idiom -- but I will stop doing it now that I know it mangles the process name. $ head -1 foo3.py #!/usr/bin/python $ ./foo3.py This is the traditional shebang form used for shell and Perl scripts, and it names the process 'foo3.py' so you can killall(1) it nicely. Or am I stuck with registering the pid of each python process I create and then refer to that list whenever I need to selectively stop one of them? If a program starts another one and needs to kill it, it /should/ remember its pid. You don't want programs which cannot live together on one machine without killing each other's children. But as I wrote above, you /do/ want to have meaningful information in top(1), ps(1) and so on. Having half a dozen processes named python (or java, or whatever) and wanting to kill one specific is not my idea of fun ... /Jorgen -- // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.dyndns.org R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Get System Date?
Is it possible to get the system date on a Windows XP machine? Most Convenient would to retrieve , MM, and DD as seperate variables. When I say system date, I'm thinking of the small clock in the lower-right hand corner, which has date as well as time, but if there's another clock that Python supports, it works for me as long as it's somewhat accurate. -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling
Actually optimizations are not what concern me. I am pretty happy with Pyrex/Swig etc for that. What I want is the ability to make a native DLL/SO. A whole lot easier to integrate/embed to other languages. -- http://mail.python.org/mailman/listinfo/python-list
Re: Get System Date?
Dustan: Is it possible to get the system date on a Windows XP machine? Most certainly: http://www.python.org/doc/lib/module-time.html -- René Pijlman -- http://mail.python.org/mailman/listinfo/python-list
Re: Generators vs. Functions?
On Sun, 05 Feb 2006 16:14:54 +, Neil Schemenauer wrote: Steven D'Aprano [EMAIL PROTECTED] wrote: Have you actually measured this, or are you just making a wild guess? I haven't timed it until now but my guess it not so wild. I'm pretty familiar with the generator implementation (having written the initial version of it). Well I guess you're forgiven then *sheepish grin* In Python 2.3, resuming a generator does a small amount of setup and then calls eval_frame(). Calling a function does more setup work and then also calls eval_frame(). It takes MORE setup to call a function than it takes to resume a generator? Here is my test, using Python 2.3. I've tried to make the test as fair as possible, with the same number of name lookups in both pieces of test code. On my machine t4 is faster than t3. Your test is not so fair because the generator is doing a while loop (executing more bytecode instructions) while the function is just returning a value (one instruction). A fair criticism, but then a generator with just one instruction is, well, pointless. On your machine the function call may be faster due to CPU cache effects or branch prediction. In any case, the difference you are trying to measure is extremely small. Try adding some arguments to the functions (especially keyword arguments). Small in absolute terms, but significant in relative terms: as an order of magnitude, a factor of about 1/10th. Of course, I never expected that calling/resuming cost to be significant for most real world uses. If I gave anyone that impression, it wasn't intended. What your test does show is that the speed difference should not come into the decision of which construct to use. I never said it should. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: triple quoted strings as comments
On Wed, 01 Feb 2006 13:41:33 GMT, Roel Schroeven [EMAIL PROTECTED] wrote: Roy Smith schreef: ... /* */ also allows for some truly spectacularly bad coding practices. Not long ago, I ran into some real-life code where a previous developer had commented out about 50 lines of C++ code by just putting a /* at the top and a */ at the bottom. I was tearing my hair out trying to figure out how the code worked until I noticed what he had done. That happened to me a few times. These days I use an editor with syntax highlighting that shows comments in another color than code. That helps tremendously. Syntax highlighting, same here. Plus version control so you can see who did it, and make a mental note not to trust that person in the future ;-) (#if 0 in C and C++ are better choices, but only marginally. Best is to remove the code unless you are sure it's needed again soon. Works in all languages.) /Jorgen -- // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.dyndns.org R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: Get System Date?
Dustan, Python has a module called, appropriately, time. Like most things in Python, it's fairly simple and straightforward to use. The module is documented here: http://docs.python.org/lib/module-time.html Breifly, though, the format you want is built right into time: import time now = time.localtime() print now (2006, 2, 5, 13, 21, 15, 6, 36, 0) So to get the year, month, and day you would just have to manipulate the values returned by time.gmtime(). - Dave -- http://mail.python.org/mailman/listinfo/python-list
translating PHP to Python
Anyone familiar with PHP? I'm trying to make a translation. In PHP you can get the current object's name by going like this: get_class(item) == 'ClassName' I've tried type(item), but since I can't be sure if I'll be in __main__ or as a child object, I can't guarantee what that value will return, so I can't just manipulate that value as a string. Is there a simple way to get the current object's name? You would think __name__ would work, right? It doesn't. Now here's another, similar one: You can reference an object's parent object directly in PHP, like so: //note the charming use of semi-colon. isn't it cute? parent::__construct( $stuffInAWeirdSyntaxThatDoesntMeanAnythingWhenYouReadIt); I'd like to avoid passing a reference to an object's parent in __init__, but is there a built in way in Python to say You, Parent Object, do ...stuff! Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Byte wrote: parse the expression, extract the operands and the operation, apply the operation to the operands How? Give me some example code, but please keep it simple. are you trying to code a calculator? Not intending to, just trying to learn Python. Suppose what i'm trying to code is a but like a CLI calculator, but i'm just writing it for my own educational beifits. Side note: have you read Dive into Python (http://diveintopython.org/) yet? If you haven't -- and are done reading the whole python tutorial -- you should, it's a very good and practical read. Now about the calculator, let's do a simple RPN notation (they're much simpler to compute than the regular notation, see http://en.wikipedia.org/wiki/RPN for some informations about RPN) First, we need an input -- expression = raw_input( ) -- Now we need to handle this input. An RPN expression is a space-separated list of tokens, these tokens being either operands (numbers) or operations. This means that we merely need to split our expression at the spaces -- expression = raw_input( ) tokens = expression.split() # split a string using spaces as default split delimiter -- Now we have a list of tokens. RPN calculations involve a stack, to keep the current operands. Python's `list` has everything you need to emulate a stack -- expression = raw_input( ) tokens = expression.split() # split a string using spaces as default split delimiter stack = list() -- Now, we have to handle each token. Either a token is a number (an operand), in which case we have to convert it to an integer (it's currently stored as a string), or it's an operation, in which case we have to apply the operation on the last two tokens of the computation stack and store the result back on the stack. This means that we have to store addition, substraction, multiplication and division. Luckily, there is the python module `operator` that stores an accessor to these operations (add, sub, mul, div). We could store them in a dictionary with an operation token as index: we feed the operation token to the dict, it outputs the operation function. -- import operator operations = { +: operator.add, -: operator.sub, *: operator.mul, /: operator.div } expression = raw_input( ) tokens = expression.split() # split a string using spaces as default split delimiter stack = list() -- Good, now all we need to know is to feed each token to the `operations` dict, let's try with the first token of the RPN expression 1 2 + 4 * 3 + operations['1'] Traceback (most recent call last): File pyshell#12, line 1, in -toplevel- operations['1'] KeyError: '1' Well, there is no 1 key in our dictionary, so we get an error. Kind of obvious. The Python dictionaries also have a get method that takes a key and a value, and they return the value (default) if the key doesn't exist, how would that one fare? operations.get('1',None) operations.get('2',None) operations.get('+',None) built-in function add Ok, it's return the operation function if it knows the token we feed it, and None if it doesn't. Now all we have to do is check if it returns None, and if it does we know it's an operand and not an operation. First we need to loop on the list of tokens: -- import operator operations = { +: operator.add, -: operator.sub, *: operator.mul, /: operator.div } expression = raw_input( ) tokens = expression.split() # split a string using spaces as default split delimiter stack = list() for token in tokens: operation = operations.get(token, None) if operation: # If operation is not None, therefore if the token was an operation token pass # do nothing for now else: # if operation is None == if the token is an operand token pass # do nothing either -- Ok, what are we supposed to do if the token is an operand? Convert the operand (token) to an integer (the token is a string), and then add it to our computational stack. The last part is done via the `append` methods of Python's list. If the token is an operation, we have to apply the operation to the last two operands of the stack, and push the result back on the stack To get the last operation of a Python list, we use the `pop`method, it defaults to returning the last value of a list. -- import operator operations = { +: operator.add, -: operator.sub, *: operator.mul, /: operator.div } expression = raw_input( ) tokens = expression.split() # split a string using spaces as default split delimiter stack = list() for token in tokens: operation = operations.get(token, None) if operation: # If operation is not None, therefore if the token was an operation token result = operation(stack.pop(), stack.pop()) # apply the operation on the last two items of the stack stack.append(result) # put the result back on the stack else: # if operation is None == if the token is an operand token
what's wrong with my popen reasoning?
Hi all, I am very new to Python programming. I am writing a program to manage wireless connections, this is for GNOME on Linux. I present the user with a connect button. I want to handle the connection for them slightly different depending on whether or not the wireless access point they are trying to connect to is secure. In either case, I have a similar question. In the first case, the wireless access point is secured. I want to bring up the GNOME applet for configuring a wireless access interface. I can pass the command line commands to bring it up, but I can't figure out how to bring it up in a modal fashion, so that my Python program waits for the user to dismiss it before my program gets control again. In the second case, the access point is not secured. I just want to fire off the command line utility (iwconfig) for connecting. In this case, I want my program to wait until iwconfig is done before continuing on. I figure that I could just write a line of code to read in from the console, but I thought there might be a more pythonic way of doing it. Here's my function so far, with variables replaced with constants to make it easier to read: def connect_clicked(self, widget, data=None): if locked: os.popen(sudo network-admin -c ath0) self.emit('connection-attempted', ath0) else: os.popen(sudo iwconfig ath0 ap 00:0F:B3:31:CB:01) self.emit('connection-attempted', ath0) Thanks much! Cheers, Rick -- http://mail.python.org/mailman/listinfo/python-list
Re: translating PHP to Python
Is there a simple way to get the current object's name? You would think __name__ would work, right? It doesn't. className = item.__class__.__name__ I'd like to avoid passing a reference to an object's parent in __init__, but is there a built in way in Python to say You, Parent Object, do ...stuff! Use the super() function to access an attribute of a parent clas class C(B): def meth(self, arg): super(C, self).meth(arg) -Farshid -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling
Ravi Teja wrote: This is a standard response to a rather frequent question here. But I am not sure I ever understood. Scheme / Lisp are about as dynamic as Python. Yet they have quite efficient native compilers. Ex: Bigloo Scheme. You might be missing two details here: 1. those compilers are less efficient than you might think 2. Scheme/Lisp are indeed less dynamic than Python Consider the following Scheme example: (module a) (define (add a b) (+ a b)) (print (add 3.0 4)) Bigloo generates the following code (which I have cleaned up quite a bit): /* toplevel-init */ obj_t BGl_toplevelzd2initzd2zzaz00() { AN_OBJECT; obj_t BgL_arg1078z00_10; BgL_arg1078z00_10 = BGl_addz00zzaz00(((double)3.0), ((long)4)); obj_t BgL_list1080z00_11; BgL_list1080z00_11 = MAKE_PAIR(BgL_arg1078z00_10, BNIL); return BGl_printz00zz__r4_output_6_10_3z00(BgL_list1080z00_11); } /* add */ obj_t BGl_addz00zzaz00(double BgL_az00_1, long BgL_bz00_2) { AN_OBJECT; obj_t BgL_list1084z00_12; obj_t BgL_arg1087z00_13; BgL_arg1087z00_13 = MAKE_PAIR(BINT(BgL_bz00_2), BNIL); BgL_list1084z00_12 = MAKE_PAIR(DOUBLE_TO_REAL(BgL_az00_1), BgL_arg1087z00_13); return BGl_zb2zb2zz__r4_numbers_6_5z00(BgL_list1084z00_12); } You can see several things from that: 1. The compiler was not able to/did not chose to implement the add operation using native C. Instead, it allocates two cons cells, and one object for the double; it then calls a generic implementation of +. 2. The compiler *did* infer that the procedure add is always called with (double long). This is because I didn't export it. If I exported the function, it would become obj_t BGl_zc3anonymousza31077ze3z83zzaz00(obj_t BgL_envz00_16, obj_t BgL_az00_17, obj_t BgL_bz00_18) { AN_OBJECT; obj_t BgL_az00_8;obj_t BgL_bz00_9; BgL_az00_8 = BgL_az00_17; BgL_bz00_9 = BgL_bz00_18; obj_t BgL_list1079z00_11; obj_t BgL_arg1081z00_12; BgL_arg1081z00_12 = MAKE_PAIR(BgL_bz00_9, BNIL); BgL_list1079z00_11 = MAKE_PAIR(BgL_az00_8, BgL_arg1081z00_12); return BGl_zb2zb2zz__r4_numbers_6_5z00(BgL_list1079z00_11); } In this case, all parameters are of type obj_t (which is a pointer type). Furthermore, looking at the actual implementation of 2+, it is defined as (define (2+ x y) (2op + x y)) and then 2op is defined as (define-macro (2op op x y) (let ((opfx (symbol-append op 'fx)) (opfl (symbol-append op 'fl)) (opelong (symbol-append op 'elong)) (opllong (symbol-append op 'llong))) `(cond ((fixnum? ,x) (cond ((fixnum? ,y) (,opfx ,x ,y)) ((flonum? ,y) (,opfl (fixnum-flonum ,x) ,y)) ((elong? ,y) (,opelong (fixnum-elong ,x) ,y)) ((llong? y) (,opllong (fixnum-llong ,x) ,y)) (else (error ,op not a number ,y ; more cases enumerating all possible ; combinations of fixnum, flonum, elong, and llong Now, compare this with Python: - In the general case of the add definition, the code Bigloo generates is roughly equivalent to the sequence of function calls the Python interpreter performs. For Python, def add(a,b): return a+b translates into 2 0 LOAD_FAST0 (a) 3 LOAD_FAST1 (b) 6 BINARY_ADD 7 RETURN_VALUE 8 LOAD_CONST 0 (None) 11 RETURN_VALUE The entire work is done in BINARY_ADD: It allocates a tuple with the two arguments, then dispatches to the actual __add__ implementation. Compared to the code Bigloo generates, this might be more efficient (a single memory allocation instead of two). - the approach of collecting all implementations of + in a single place of Bigloo cannot be transfered to Python. Python's implementation of + is dynamically extensible. - the approach of directly calling add() in the toplevel init cannot be applied to Python, either. The meaning of the name add can change between the time of definition and the actual call. Therefore, the simple function call must go through a table lookup. So while it would be possible to apply the same strategy to Python, it likely wouldn't gain any performance increase over the interpreter. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Most prominent Tkinter applications?
I'm looking for examples of best practices in Tkinter/Python programming. What are the most prominent Python applications out there that use Tkinter as the GUI toolkit? These can be commercial or open-source, but are preferably multi-platform. I know IDLE is written in Tkinter, so that's one example. Can anyone direct me to others? -- Cheers, Kevin Walzer, PhD WordTech Software - Tame the Terminal http://www.wordtech-software.com sw at wordtech-software.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Get System Date?
Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
I asked to keep it simple! Anyway, ill try Dive into Python, thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: translating PHP to Python
Farshid, This is a great help, thanks. The second point won't work, though, because by parent class I mean, simply, the object that created the current object, *not* the class the current class is based on. So, for example: class A(object): def __init__(self): self.thing = Thing() self.thing.meth() def do_stuff(self): print Stuff class Thing(object): def meth(self): #now here's what I WANT self.parent.do_stuff(args) Is there a built in way to do this in Python, or do I have to pass parent when I init Thing? Sorry if this is confusing. It confuses me, too. I should have been a carpenter. - Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython Conventions
Thanks for all the replies. I'm admittedly new to GUI programming, so I'm making sure to read up on the MVC pattern and related things like the observer pattern. I appreciate the help. Jared -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way of finding terminal width/height?
Which details? We'd be happy to explain the code. Not that you need to understand the details to use the code. OK, why '1234' in here, and what's termios.TIOCGWINSZ, and how should I have known this was the way too do it? fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234') Am I interpreting C structs here, and if so - why is python giving me C structs? And what's 'hh' anyway? struct.unpack('hh', ... ) Why 0, 1 and 2? cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) I don't know if it will work on MS Windows or not. Linux and unix are my main concerns, but it would be neat to know if it would work on Win/Mac. What OS:es set the COLS/ROWS env vars? What OS:es can leverage the termios module? I have a hunch that we have 100% overlap there, and then this solution leaves me at square one (arbitrary choice of 80*25) for the others OS:es (or am I wrong?). How do Win/Mac people do this? What's unpythonic about the example you found? Maybe I did bit of poor wording there, but In my experience python generally has a high level of abstraction, which provides linguistically appealing (as in in english) solutions to almost any problem. Like for example how os.path.isfile(s) tells me if my string s corresponds to a file. I guess that's what I mean really. I sort of expected to find something like my terminal_size() example in the built-in modules. I didn't expect to have to do that struct fcntl ioctl boogey to solve this relatively simple (?) problem. Thanks for your help! /Joel -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Byte [EMAIL PROTECTED] wrote: Thanks, never knew that, but they are using raw_input as a stack, aren't they? No. raw_input is a function object, using it as a stack is a rather meaningless phrase. You can use a list as a stack, but that's totally and absolutely unrelated to that spot in the tutorial. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Get System Date?
Dustan [EMAIL PROTECTED] wrote: Is it possible to get the system date on a Windows XP machine? Most Convenient would to retrieve , MM, and DD as seperate variables. When I say system date, I'm thinking of the small clock in the lower-right hand corner, which has date as well as time, but if there's another clock that Python supports, it works for me as long as it's somewhat accurate. import datetime x=datetime.date.today() , mm, dd = x.year, x.month, x.day print 2006 print mm 2 print dd 5 As you see, these are integers (so, for example, mm is not '02' but just 2). Pretty easy to make them into strings, of course, if you want. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a unix shell account with Python?
Sebastjan Trepca wrote: I couldn't find anything on creating a new linux user account in Python documentation. Anyone has any experience with this? You just run useradd command in shell or is there a more pythonic way? Just run useradd. -- http://mail.python.org/mailman/listinfo/python-list
Re: translating PHP to Python
Dave wrote: The second point won't work, though, because by parent class I mean, simply, the object that created the current object, *not* the class the current class is based on. Good you clarified that, because parent definitely isn't used that way by most other people here. And, in fact, there's no requirement that an instance (object) be involved in creating a new object. Python allows functions that are not methods in a class. What would you expect to happen if a mere function was doing the creating? So, for example: class A(object): def __init__(self): self.thing = Thing() self.thing.meth() def do_stuff(self): print Stuff class Thing(object): def meth(self): #now here's what I WANT self.parent.do_stuff(args) Is there a built in way to do this in Python, or do I have to pass parent when I init Thing? It's pretty much standard to pass in references to the caller, or perhaps even more standard to pass in a callable, often in the form of a a bound method when an object's method is doing the calling. On the other hand, what you are showing here is something that *would* normally be done with subclassing, and therefore with a parent class involved (using the conventional meaning of parent). class A(object): def __init__(self): self.do_stuff() class Thing(A): def do_stuff(self): print Stuff But since this was a contrived example, I can't really tell what would work best for you in your real use case. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Generators vs. Functions?
Duncan Booth wrote: Steven D'Aprano wrote: So on the basis of my tests, there is a small, but significant speed advantage to _calling_ a function versus _resuming_ a generator. I get the same, but the difference is much less on my system: With Python 2.4? Doesn't surprise me a bit. I tested with 2.3 (vanilla Red Hat EL4 install) and it seems Steven used 2.3 as well. My little test was just an attempt to test a claim that the setup time would be shorter for generator calls than for function calls. It's so easy to test timing with Python, so it's surprising that people speculate so much about theories with no measurements. Who knows what the call time ratios will be in Python 2.6? I think the important point is the one Fredrik is making: You won't have a function implementation or a generator implementation with the same code body. The other differences in the code will typically mean much more than the call overhead. If we're in some nested loop where we call a function so trivial that the call overhead makes performance suffer, by all means, inline these few lines of code in the loop! -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Xavier Morel wrote: Where the hell did you get the idea of stacking input on a raw_input in the first place? I'm guessing it goes something like: input is a verb, but raw_input is a noun, so raw_input looks like a cast or conversion or stream constructor, and input looks like an action... raw_input is a bad name for get_interactive_input, anyway... --Blair -- http://mail.python.org/mailman/listinfo/python-list