Roundup Issue Tracker release 1.0.1
I'm proud to release this, the 1.0.1 release of Roundup. Features in this release: - scripts/import_sf.py will import a tracker from Sourceforge.NET - added hasRole('Role Name') to HTMLUser Fixed in this release: - SQL generation for sort/group by separate Link properties (sf bug 1417565) - fix timezone offsetting in email Date: header - fix security check for hasPermission('Permission', None) If you're upgrading from an older version of Roundup you *must* follow the Software Upgrade guidelines given in the maintenance documentation. Roundup requires python 2.3 or later for correct operation. To give Roundup a try, just download (see below), unpack and run:: python demo.py Release info and download page: http://cheeseshop.python.org/pypi/roundup Source and documentation is available at the website: http://roundup.sourceforge.net/ Mailing lists - the place to ask questions: http://sourceforge.net/mail/?group_id=31577 About Roundup = Roundup is a simple-to-use and -install issue-tracking system with command-line, web and e-mail interfaces. It is based on the winning design from Ka-Ping Yee in the Software Carpentry Track design competition. Note: Ping is not responsible for this project. The contact for this project is [EMAIL PROTECTED] Roundup manages a number of issues (with flexible properties such as description, priority, and so on) and provides the ability to: (a) submit new issues, (b) find and edit existing issues, and (c) discuss issues with other participants. The system will facilitate communication among the participants by managing discussions and notifying interested parties when issues are edited. One of the major design goals for Roundup that it be simple to get going. Roundup is therefore usable out of the box with any python 2.3+ installation. It doesn't even need to be installed to be operational, though a disutils-based install script is provided. It comes with two issue tracker templates (a classic bug/feature tracker and a minimal skeleton) and five database back-ends (anydbm, sqlite, metakit, mysql and postgresql). -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Movable Python 1.0.0 for Python 2.3 2.4
It's finally happened, `Movable Python http://www.voidspace.org.uk/python/movpy/`_ is finally released. Versions for Python 2.3 2.4 are available from `The Movable Python Shop http://voidspace.tradebit.com/groups.php`_. The cost is £5 per distribution, payment by PayPal. £1 from every distribution goes to support the development of `SPE http://pythonide.stani.be/`_, the Python IDE. This gives you free support (via the `Movable Python Mailing List http://groups.google.com/group/movpy`_), and access to updates, for a year. There is a minor issue with the Python 2.2 version. This will be fixed and released in the next few days. In the meantime the previous version (0.4.6) is available for download from the shop. If you purchase this distribution your year will run from the date of the release of 1.0.0. Paying for **Movable Python** supports the development of the other Open Source `Voidspace Python Projects http://www.voidspace.org.uk/python/index.shtml`_. What is Movable Python ? === **Movable Python** is a distribution of Python for Windows that doesn't need to be installed. It easily fits onto a USB memory stick. Python on a stick. It is integrated with SPE, the Python IDE, to make **Movable Python** a portable Build, Test, and Run environment. It has a nice GUI to launch programs and control its behaviour. Movable Python is useful in the following situations: * Machines where you can't install programs. * Where you need a portable 'Build, Test, and Run' Python environment. * Having several versions of Python on the same machine for forward/backward compatibility testing. * Easily deploying Python scripts without having to install Python. * Try before you buy - test Python without having to install it, including new versions . * 'Python Runtime Environment'. '``.py``' files can be associated with movpy. For more information, see `An Introduction to Movable Python http://www.voidspace.org.uk/python/movpy/introduction.html`_. What's New ? == Changes since version 0.4.6. Completely new method for running files. This means you can launch multiple programs from the GUI. Lots of new libraries and tools included. Virtually all the included tools have had version upgrades since the last release. The GUI does a lot more : * Version number and Python version displayed on the GUI * You can pass arguments to your programs * It remembers the last directory you ran a program from * You choose if launched programs have a console box or not * You can configure the options programs are run with * You can edit the default options * Four configurable Quick Launch buttons * You can launch SPE from the GUI * You can launch the documentation (About) * You can launch an interpreter console * You can close the GUI without having to launch a program or go to the interpreter The following (command line) options are new : * ``f`` - run script in it's directory * ``b`` - pause after running script * ``o`` - override default options * ``die`` - get rid of GUI after running * ``k`` - run with console from movpyw * ``koff`` - run without console from movpy Complete documentation rewrite. Docs are now built with `rest2web http://www.voidspace.org.uk/python/rest2web/`_. ``movpyw.exe`` is now included in the Python 2.2 distribution. Bug fixed where first command line argument to your program was always lost. {sm;:oops:} Bug fixed so that ``IPOFF`` actually works now. Bug fixed so that ``-p`` in ``config.txt`` now works. Lots of other minor changes and improvements. {sm;:-)} Known Issues == There are some (minor) known issues with version 1.0.0. These will be fixed soon. * Version for Python 2.2 not yet available. * Possible issue running ``movpy.exe`` from long file paths on Windows 98. * The ``lib`` directory is not added to ``sys.path`` before entering interactive mode. There are also several items in the `TODO http://www.voidspace.org.uk/python/movpy/TODO.html`_ list. Many of these are future ways that **Movable Python** could be developed. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: How do I dynamically create functions without lambda?
Terry Hancock wrote: Frankly this paper sounds like a bid for the Journal of Irreproducible Results that somehow got accidentally submitted to a serious journal http://www.improbable.com/ig/ig-pastwinners.html#ig2000 /F -- http://mail.python.org/mailman/listinfo/python-list
Best way to determine if a certain PID is still running
I'm launching a process via an os.spawnvp(os.P_NOWAIT,...) call. So now I have the pid of the process, and I want a way to see if that process is complete. I don't want to block on os.waitpid(), I just want a quick way to see if the process I started is finished. I could popen(ps -p %d % pid) and see whether it's there anymore...but since pids get reused, there's the chance (however remote) that I'd get a false positive, plus I don't really like the idea of calling something non-pure-python to find out. So, should I run a monitor thread which just calls os.waitpid() and when the thread indicates via an event that the process completed, I'm golden? All suggestions welcome, looking for simple and clean over wickedly-clever, -David -- Presenting: mediocre nebula. -- http://mail.python.org/mailman/listinfo/python-list
Movable Python 1.0.0 for Python 2.3 2.4
It's finally happened, `Movable Python http://www.voidspace.org.uk/python/movpy/`_ is finally released. Versions for Python 2.3 2.4 are available from `The Movable Python Shop http://voidspace.tradebit.com/groups.php`_. The cost is £5 per distribution, payment by PayPal. £1 from every distribution goes to support the development of `SPE http://pythonide.stani.be/`_, the Python IDE. This gives you free support (via the `Movable Python Mailing List http://groups.google.com/group/movpy`_), and access to updates, for a year. There is a minor issue with the Python 2.2 version. This will be fixed and released in the next few days. In the meantime the previous version (0.4.6) is available for download from the shop. If you purchase this distribution your year will run from the date of the release of 1.0.0. Paying for **Movable Python** supports the development of the other Open Source `Voidspace Python Projects http://www.voidspace.org.uk/python/index.shtml`_. What is Movable Python ? === **Movable Python** is a distribution of Python for Windows that doesn't need to be installed. It easily fits onto a USB memory stick. Python on a stick. It is integrated with SPE, the Python IDE, to make **Movable Python** a portable Build, Test, and Run environment. It has a nice GUI to launch programs and control its behaviour. Movable Python is useful in the following situations: * Machines where you can't install programs. * Where you need a portable 'Build, Test, and Run' Python environment. * Having several versions of Python on the same machine for forward/backward compatibility testing. * Easily deploying Python scripts without having to install Python. * Try before you buy - test Python without having to install it, including new versions . * 'Python Runtime Environment'. '``.py``' files can be associated with movpy. For more information, see `An Introduction to Movable Python http://www.voidspace.org.uk/python/movpy/introduction.html`_. What's New ? == Changes since version 0.4.6. Completely new method for running files. This means you can launch multiple programs from the GUI. Lots of new libraries and tools included. Virtually all the included tools have had version upgrades since the last release. The GUI does a lot more : * Version number and Python version displayed on the GUI * You can pass arguments to your programs * It remembers the last directory you ran a program from * You choose if launched programs have a console box or not * You can configure the options programs are run with * You can edit the default options * Four configurable Quick Launch buttons * You can launch SPE from the GUI * You can launch the documentation (About) * You can launch an interpreter console * You can close the GUI without having to launch a program or go to the interpreter The following (command line) options are new : * ``f`` - run script in it's directory * ``b`` - pause after running script * ``o`` - override default options * ``die`` - get rid of GUI after running * ``k`` - run with console from movpyw * ``koff`` - run without console from movpy Complete documentation rewrite. Docs are now built with `rest2web http://www.voidspace.org.uk/python/rest2web/`_. ``movpyw.exe`` is now included in the Python 2.2 distribution. Bug fixed where first command line argument to your program was always lost. {sm;:oops:} Bug fixed so that ``IPOFF`` actually works now. Bug fixed so that ``-p`` in ``config.txt`` now works. Lots of other minor changes and improvements. {sm;:-)} Known Issues == There are some (minor) known issues with version 1.0.0. These will be fixed soon. * Version for Python 2.2 not yet available. * Possible issue running ``movpy.exe`` from long file paths on Windows 98. * The ``lib`` directory is not added to ``sys.path`` before entering interactive mode. There are also several items in the `TODO http://www.voidspace.org.uk/python/movpy/TODO.html`_ list. Many of these are future ways that **Movable Python** could be developed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to determine if a certain PID is still running
David Hirschfield [EMAIL PROTECTED] writes: So, should I run a monitor thread which just calls os.waitpid() and when the thread indicates via an event that the process completed, I'm golden? Umm, what OS? And do you have any control over the program running in the subprocess, or is it doing something arbitrary? I.e. I'm wondering if can you do stuff like sharing a file descriptor with the subprocess, or keeping a pipe open. Using a monitor thread doesn't sound too bad, but there may be ways to avoid it. But if you're willing to launch a thread, why not just spawn there without NOWAIT? -- http://mail.python.org/mailman/listinfo/python-list
newbie - script works in PythonWin - fails from Python
Hi, I have a script that runs fine when I run it from within PythonWin but causes a WindowsError: Exception when I try to run it from the command line using python.exe. What is PythonWin doing differently? -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to determine if a certain PID is still running
On Thu, Feb 02, 2006 at 05:10:24PM -0800, David Hirschfield wrote: I'm launching a process via an os.spawnvp(os.P_NOWAIT,...) call. So now I have the pid of the process, and I want a way to see if that process is complete. I don't want to block on os.waitpid(), I just want a quick way to see if the process I started is finished. I could popen(ps -p %d % pid) and see whether it's there anymore...but since pids get reused, there's the chance (however remote) that I'd get a false positive, plus I don't really like the idea of calling something non-pure-python to find out. You could try this: import os, errno try: os.kill(pid, 0) except OSError, e: if e.errno == errno.ESRCH: # process has finished ... else: # process exists ... Unfortunately, this way cannot save you from getting false positives with reused pids. The IMO better way is to use the subprocess module that comes with Python 2.4. How to replace os.spawn* calls is described here: http://www.python.org/doc/2.4.2/lib/node244.html -- Lars Gustäbel [EMAIL PROTECTED] To a man with a hammer, everything looks like a nail. (Mark Twain) -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie - script works in PythonWin - fails from Python
[EMAIL PROTECTED] wrote: I have a script that runs fine when I run it from within PythonWin but causes a WindowsError: Exception when I try to run it from the command line using python.exe. What is PythonWin doing differently? is that the entire traceback ? what is the script doing when you get that error message ? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie - script works in PythonWin - fails from Python
[EMAIL PROTECTED] wrote: Hi, I have a script that runs fine when I run it from within PythonWin but causes a WindowsError: Exception when I try to run it from the command line using python.exe. What is PythonWin doing differently? Hello Marcus, Can you post the full exception, and preferably the snippet of code (with relevant context) that caused it. This will give people a better chance of being able to help you. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie - script works in PythonWin - fails from Python
I'm using ctypes and loading a DLL and running a DLL function. As I say it works perfectly with no errors when I run from PythonWin but gives the following exception when run from command line. WindowsError: exception code 0xeedfade I can use the DLL with no issues in other languages too. It works fine in VB, C++ and in Python when run from PythonWin but gets an exception when run from python.exe PythonWin must be doing something different, but I can't find anything in the documentation. -- http://mail.python.org/mailman/listinfo/python-list
Re: would it be feasable to write python DJing software
Levi Campbell wrote: Any and all mixing would probably happen in some sort of multimedia library written in C (it would be both clumsy to program and slow to execute if the calculations of raw samples/bytes were done in python) so there shouldn't be a noticable performance hit. Actually, manipulating and mixing audio samples can be both fast and elegant, in Python, if you use Numeric or a similar library. -Sw. -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
[EMAIL PROTECTED] wrote: What do you think? The impression I get from your suggestion is that you haven't really understood Python. I'm sure that some things could be better designed or better documented, but your suggestions would actually make things worse. Sorry. Today, Python has a syntactic shortcut. If 'a' is an instance of class 'A', a.f(x,y,z) is a shortcut for A.f(a,x,y,z). If you don't use the shortcut, there is no magic at all, just the unusual occurence of a type check in Python! If you use the shortcut, Python code looks just like most other OO languages. This isn't very magical. What you suggest doesn't remove magic, but it introduces a bunch of inconsistencies! But: Foo.__dict[bar]__(1,2,3) Does work. I agree that this isn't completely clean, and there are some other ways in which the distinction between functions, unbound methods and bound methods seem a bit quirky to me. I don't think the problem is in the syntax though, and if it had been a real problem, it would had been solved. class Foo: def self.bar(a,b): return a+b Foo().bar(1,2) = 3 First of all, you are using a really poor example of a method, since it doesn't use any attributes of the Foo instance. That function doesn't seem to belong in that class at all. If it should be in the class, it should be a static method, so self should not be involved at all. In modern Python it would look like this: class Foo(object): @staticmethod def bar(a, b): return a+b Anyway, my impression is that you haven't fully understood how namespaces work in Python, at least not the distinction between class namespaces and instance namespaces. Please study this a bit more. Hopefully, you'll find enlightenment and things will fall into place for you. You are really giving self a magic meaning with your suggestion which isn't needed at all. So far, the existence of x.y somewhere in Python always implied that x was already introduced explicitly in the program, and you suggest that we violate that both in the def self.x-row, and inside the methods when we access attributes. Provoking a language can be a way of learning it, and provoking people can sometimes lead to new insights, but it's important to have an open mind. When learning a new language, it's probably better to try to adapt oneself to it, rather than the other way around. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie - script works in PythonWin - fails from Python
On Fri, 03 Feb 2006 02:29:03 -0800, marcus.tettmar wrote: I'm using ctypes and loading a DLL and running a DLL function. As I say it works perfectly with no errors when I run from PythonWin but gives the following exception when run from command line. WindowsError: exception code 0xeedfade I find it hard to believe that this is the entire exception traceback. This is what a traceback looks like: dosomething wrong(20) # oops, space in the function name File stdin, line 1 dosomething wrong(20) ^ SyntaxError: invalid syntax See how much information is given by the traceback? If I just posted SyntaxError: invalid syntax to the newsgroup with no further information, what do you think the chances are anyone would guess the cause of the problem? So, how about trying again with the complete traceback? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: would it be feasable to write python DJing software
[EMAIL PROTECTED] wrote: Actually, manipulating and mixing audio samples can be both fast and elegant, in Python, if you use Numeric or a similar library. ... at which point you're actually doing it in C, not pure python... :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
That usage (self is second parameter to B.test) is bound to cause trouble in general, but in this case doesn't have any effect I can see. The function call test would be resolved from its first parameter, instance of A, and that function would return 1. One of us is missing something here, could be me. Probably my example wasn't clear, let's try another: class A: def test(a, **kwargs): return 1 class B: def test(b, **kwargs): return 2 test(a=A(), b=B()) self isn't a keyword, so nothing should forbid this code. What is the interpreter to do if it stumbles across this test call? I mean, named-argument lookup is a tricky thing even if you do know what function you're calling. If this would depend on one of the parameters, I think it would become completely unintelligible. (you can think of more complex examples yourself) That's exactly the problem, it doesn't read from left to right, because we swap back and forth between function(parameter and parameter.function notation. That's because they're doing two different things: object.method() does an attribute lookup, while function(parameter) looks for the function in the current scope. -- http://mail.python.org/mailman/listinfo/python-list
Re: Server side newbie
Can you point me to sample code somewhere? If I had a server-side python script that increments the number in an edit control on clicking a button, I think I could take it from there. -- http://mail.python.org/mailman/listinfo/python-list
Re: would it be feasable to write python DJing software
Ivan Voras wrote: [EMAIL PROTECTED] wrote: Actually, manipulating and mixing audio samples can be both fast and elegant, in Python, if you use Numeric or a similar library. ... at which point you're actually doing it in C, not pure python... :) Only in as much as doing anything in Python is *really* doing it in C, surely ? Come to that, you're **really** doing it in machine code... All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: would it be feasable to write python DJing software
Fuzzyman wrote: Only in as much as doing anything in Python is *really* doing it in C, surely ? Come to that, you're **really** doing it in machine code... I've yet to see someone calling if a == '5': print it's 5 machine code. It's the distinction on which level the program's logic is implemented, not at which level it's executed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
Yes, that's what I had in mind when I said it could be made recursion-safe. It's still not thread-safe, but I think that could be done too, using thread-local-variables instead of globals. class TestB: @memberFunction def do(x): z = __ # lambda's shouldn't directly reference '__' x.do(lambda : z) Yes, that's what I meant when I said it wasn't lambda-safe. That means a completely legal and (in my code) common expression can behave totally unexpected. Would be a no-go for me. But I think it gets worse: class TestA: @memberFunction def do(): yield 1 yield 2 yield __ class TestB: @memberFunction def bar(): for x in TestA().do(): print x TestB().bar() Doesn't behave as expected, and the only way I can see to fix it would be to declare a local function inside TestA's do function... -- http://mail.python.org/mailman/listinfo/python-list
Re: would it be feasable to write python DJing software
Ivan Voras wrote: Come to that, you're **really** doing it in machine code... I've yet to see someone calling if a == '5': print it's 5 machine code. It's the distinction on which level the program's logic is implemented, not at which level it's executed. uhuh? so why did you just argue that if foo.bar(): bar.aba() means doing it in C if bar and aba happens to be parts of an extension library ? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
On Fri, 03 Feb 2006 12:00:52 +0100, Magnus Lycka wrote: Today, Python has a syntactic shortcut. If 'a' is an instance of class 'A', a.f(x,y,z) is a shortcut for A.f(a,x,y,z). It is easy to work around (break?) that behaviour: class A(object): def foo(self): print normal method foo a = A() def foo(self): print special method foo from new import instancemethod a.foo = instancemethod(foo, a) Now we can see that a.foo() is no longer a shortcut for A.foo(a): a.foo() special method foo A.foo(a) normal method foo So instances can have methods that they don't inherit from their class! -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
First of all, you are using a really poor example of a method, since it doesn't use any attributes of the Foo instance. Agreed. I tried to post a short example, and it obviously was to short to make my point clear. lets take a longer one. Current syntax: class Pair: def __init__(self, a,b): self.a = a self.b = b def sum(self): return self.a + self.b def product (this): return this.a + this.b My alternative syntax suggestion would be this one: class Pair: def self.__init__(a,b): self.a = a self.b = b def self.sum(): return self.a + self.b def this.product (): return this.a + this.b You are really giving self a magic meaning with your suggestion which isn't needed at all. No. I hope this is clearer in the example above. self shouldn't be a keyword. It's a special kind of argument now, so why shouldn't we explicitly _declare_ that it's a special kind of argument? (as explicit is better than implicit) So far, the existence of x.y somewhere in Python always implied that x was already introduced explicitly in the program, Yes, but y(x) also implies that x and y have been introduced explicitly before, unless it's in a def statement. The def statement always introduces new variables. and you suggest that we violate that both in the def self.x-row, and inside the methods when we access attributes. def x(self): declares two new identifiers, x and self Why shouldn't def self.x(): declare two new identifiers (x and self), too? Attribute acces wouldn't change. -- http://mail.python.org/mailman/listinfo/python-list
Re: Server side newbie
[EMAIL PROTECTED] writes: Can you point me to sample code somewhere? If I had a server-side python script that increments the number in an edit control on clicking a button, I think I could take it from there. Oh man, I hate to say this since it's not a good situation, but what you're asking is a little bit more complicated than I think you're expecting. You need a server app with some notion of sessions (I assume the user is supposed to be able to increment the number more than once), so you have to know a bit about how servers and HTTP work, plus how to write HTML, in addition to Python and some suitable server side modules. Your best bet might be to use a web framework that already understands sessions, but 1) you have to decide which one to use, since there are several to choose from with differing sets of features; and 2) these frameworks are designed for writing complex apps, so learning them may be a bit much for something this simple. But if your idea is to build towards a real web app that does something more serious, then a framework is the way to go. There's an old book about how database-backed web sites work, that is pretty long, but well written. It's online: http://philip.greenspun.com/panda -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
I still see newbie-friendliness as a MAJOR plus for Python -- it increases the chance that users of your software will become contributors. Yes, I 100% agree to that point! But the point is, the current situation is not newbie-friendly (I can tell, I am a newbie): I declare a method with 3 parameters but when I call it I only pass 2 parameters. That's confusing. If I declare a member variable, I write: self.x = ValueForX, why can't I be equally explicit for declaring member functions? -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
On Fri, 03 Feb 2006 03:23:00 -0800, n.estner wrote: That usage (self is second parameter to B.test) is bound to cause trouble in general, but in this case doesn't have any effect I can see. The function call test would be resolved from its first parameter, instance of A, and that function would return 1. One of us is missing something here, could be me. Probably my example wasn't clear, let's try another: class A: def test(a, **kwargs): return 1 class B: def test(b, **kwargs): return 2 test(a=A(), b=B()) self isn't a keyword, so nothing should forbid this code. What is the interpreter to do if it stumbles across this test call? You could try running it to see: class A: ... def test(a, **kwargs): return 1 ... class B: ... def test(b, **kwargs): return 2 ... test(a=A(), b=B()) Traceback (most recent call last): File stdin, line 1, in ? NameError: name 'test' is not defined Oops! You have defined a name test in two namespaces, the class A and the class B, but there is no name test in the global namespace you are trying to run it in. Since namespaces are critical to Python, your test code is a problem that just cannot happen in Python. It is a non-issue. Python will not get confused between the two definitions of test. I mean, named-argument lookup is a tricky thing even if you do know what function you're calling. If this would depend on one of the parameters, I think it would become completely unintelligible. (you can think of more complex examples yourself) That's exactly the problem, it doesn't read from left to right, because we swap back and forth between function(parameter and parameter.function notation. That's because they're doing two different things: object.method() does an attribute lookup, while function(parameter) looks for the function in the current scope. No, function(parameter) does not look for a function. It looks for any object at all, and then tries to call it. Both calls do almost the same thing. object.method() looks up the name method in the object namespace, function(parameter) looks up the name function in the current namespace. Neither method nor function must be methods or functions, although if they are not callable objects, calling them will raise an exception. But regardless of what sort of objects they are, the look up proceeds in the same fashion. Unless you understand namespaces, you don't understand Python, and any criticism is likely to be due to misunderstanding. As near as I can tell, your original complaint might be solved simply: it seems to me that you are concerned about that extraneous self parameter for methods that don't need it: class Foo: def bar(self, a,b): return a+b Foo().bar(1,2) = 3 If bar doesn't need the instance or class Foo, perhaps it would be better off as an ordinary function rather than bound to a class. But if bar does need to be a method, perhaps you want something like this: # for Python 2.2 and up class Foo: def bar(a,b): return a+b bar = staticmethod(bar) # for Python 2.4 and up class Foo: @staticmethod def bar(a,b): return a+b Foo().bar(1,2) works exactly the same as before, but your definition of bar doesn't need that extraneous self parameter. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Server side newbie
swisscheese wrote: I have a simple python desktop app with several edit controls and a couple of buttons. It just does some math. What's the simplest way to make it a server-side app so visitors to my site can run the app via their browser? If the math is simple, you can just use JavaScript. No need to bother running it on the server. -- http://mail.python.org/mailman/listinfo/python-list
Re: HTMLDocument and Xpath
[EMAIL PROTECTED] Hi, I want to use xpath to scrape info from a website using pyXML but I keep getting no results. For example, in the following, I want to return the text Element1 I can't get xpath to return anything at all. What's wrong with this code? Your xpath expression is wrong. test = Evaluate('td', doc_node.documentElement) Try one of the following alternatives, all of which should work. test = Evaluate('//td', doc_node.documentElement) test = Evaluate('/html/body/table/tr/td', doc_node.documentElement) test = Evaluate('/html/body/table/tr/td[1]', doc_node.documentElement) HTH, Alan. -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
You could try running it to see: class A: ... def test(a, **kwargs): return 1 ... class B: ... def test(b, **kwargs): return 2 ... test(a=A(), b=B()) Traceback (most recent call last): File stdin, line 1, in ? NameError: name 'test' is not defined Oops! You have defined a name test in two namespaces, the class A and the class B, but there is no name test in the global namespace you are trying to run it in. Since namespaces are critical to Python, your test code is a problem that just cannot happen in Python. It is a non-issue. Python will not get confused between the two definitions of test. I've been answering to Donn Cave's suggestion. Read it, and you will understand what I mean. As near as I can tell, your original complaint might be solved simply: it seems to me that you are concerned about that extraneous self parameter for methods that don't need it: No, I wasn't talking about functions that don't use the self parameter. I rarely ever have such functions. I just tried to make the example as short as possible. -- http://mail.python.org/mailman/listinfo/python-list
fixedint.py enhanced for auto-coercion (fixed-width python integers)
Hi Dan, I find that when doing bit-twiddling in pure Python, fixed-width integer support is an extremely handy capability to have in Python regardless of what the apologists (for its absence) say. I added some stuff to fixedint.py to make x=SByte(80) x+200 fixedint.SignedType(8)(24) the above work. Perhaps you can review the code to see if there are any major flaws in it? Right after I started using it, I realized there has to be a lot more thought put into the conventions for the coecion rules. What should x=SByte(80) 200+x return for example... ? - START OF CODE - import operator def _toFixedUnsigned(n, b): Truncate n to a b-bit unsigned long. return n ((1L b) - 1)# bitmask of b 1's def _toFixedSigned(n, b): Truncate n to a b-bit signed long. result = _toFixedUnsigned(n, b) if result = (1L b - 1): # More than maxint? result -= 1L b # Then wrap around. return result class _Integer(object): Abstract base class for SignedType and UnsignedType. # Numeric conversions def __long__(self): return self._value def __int__(self): return int(self._value) def __float__(self): return float(self._value) def __nonzero__(self): return self._value != 0 # String conversions. def __str__(self): return str(self._value) # Arithmetic def __pos__(self): return self def __neg__(self): return type(self)(-self._value) def __add__(self, other): if isinstance(other, type(self)): return type(self)(self._value + other._value) else: return type(self)(self._value + self.__class__(other)._value) def __sub__(self, other): if isinstance(other, type(self)): return type(self)(self._value - other._value) else: return type(self)(self._value - self.__class__(other)._value) def __mul__(self, other): if isinstance(other, type(self)): return type(self)(self._value * other._value) else: return type(self)(self._value * self.__class__(other)._value) def __floordiv__(self, other): if isinstance(other, type(self)): return type(self)(self._value // other._value) else: return type(self)(self._value // self.__class__(other)._value) def __mod__(self, other): if isinstance(other, type(self)): return type(self)(self._value % other._value) else: return type(self)(self._value % self.__class__(other)._value) def __divmod__(self, other): return self // other, self % other # Relational def __cmp__(self, other): return cmp(long(self), other) # Bit-bashing def __lshift__(self, other): return type(self)(self._value other) def __rshift__(self, other): return type(self)(self._value other) def __invert__(self): return type(self)(~self._value) def __and__(self, other): if isinstance(other, type(self)): return type(self)(self._value other._value) else: return type(self)(self._value self.__class__(other)._value) def __or__(self, other): if isinstance(other, type(self)): return type(self)(self._value | other._value) else: return type(self)(self._value | self.__class__(other)._value) def __xor__(self, other): if isinstance(other, type(self)): return type(self)(self._value ^ other._value) else: return type(self)(self._value ^ self.__class__(other)._value) _utypes = {} def UnsignedType(bits): Returns a fixed-width unsigned int type with the given number of bits. if bits in _utypes: return _utypes[bits] else: class unsigned(_Integer): __doc__ = '%d-bit unsigned integer type' % bits def __init__(self, value): self._value = _toFixedUnsigned(value, bits) def __repr__(self): return 'fixedint.UnsignedType(%d)(%d)' % (bits, self._value) return unsigned Byte = UnsignedType(8) UShort = UnsignedType(16) UInt = UnsignedType(32) ULong = UnsignedType(64) _stypes = {} def SignedType(bits): Returns a fixed-width signed int type with the given number of bits. if bits in _stypes: return _stypes[bits] else: class signed(_Integer): __doc__ = '%d-bit signed integer type' % bits def __init__(self, value): self._value = _toFixedSigned(value, bits) def __repr__(self): return 'fixedint.SignedType(%d)(%d)' % (bits, self._value) return signed SByte = SignedType(8) Short = SignedType(16) Int = SignedType(32) Long = SignedType(64) -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
Op 2006-02-03, [EMAIL PROTECTED] schreef [EMAIL PROTECTED]: First of all, you are using a really poor example of a method, since it doesn't use any attributes of the Foo instance. Agreed. I tried to post a short example, and it obviously was to short to make my point clear. lets take a longer one. Current syntax: class Pair: def __init__(self, a,b): self.a = a self.b = b def sum(self): return self.a + self.b def product (this): return this.a + this.b My alternative syntax suggestion would be this one: class Pair: def self.__init__(a,b): self.a = a self.b = b def self.sum(): return self.a + self.b def this.product (): return this.a + this.b You are really giving self a magic meaning with your suggestion which isn't needed at all. No. I hope this is clearer in the example above. self shouldn't be a keyword. It's a special kind of argument now, so why shouldn't we explicitly _declare_ that it's a special kind of argument? (as explicit is better than implicit) Self is not a special kind of argument. It is the accessing of the method that provides for the magic. Simplified one could say the following is happening. def _Pair__init__(self, a, b): self.a = a self.b = b def _Pair_sum(self): return self.a + self.b def _Pair_product(this): return this.a * this.be class Pair: def __init__(self, ...): self.__init__ = BoundMethod(self, _Pair__init__) self.sum = BoundMethod(self, _Pair_sum) self.product = BoundMethod(self, _Pair_product) self.__init__(...) So when p is an instance of Pair, p.sum is not your defined function but a BoundMethod. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: OO conventions
On Thu, 02 Feb 2006 17:00:26 -0800, Blair P. Houghton wrote: Image would be a superclass to JPGImage, BMPImage, PNGImage, etc... But which to use could only be determined AFTER opening the file, because file.jpg doesn't have type JPG, it has type string and semantic value maybe a jpeg file or maybe something misnamed as a jpeg file. Absolutely. So Image.open(filename) seems right as a factory function that opens the file, figures out what it really is, constructs the appropriate subclass object (likely by passing a string to the constructor, e.g., JPGImage(filename)), and returns the object via the superclass type. The caller can then either check a flag in the superclass to see what type the subclass is, or just assume it's the right type of image for the filename extension (or does Python have RTTI? I don't recall if I've seen it, yet...). RTTI = Run Time Type Information, yes? Objects in Python are strongly typed, if that's what you mean. So if each image kind (jpeg, tiff, png, etc.) is a subclass, then you can easily use introspection to find out which subclass it is. Though if the filename doesn't match the content, someone should raise an exception... That depends on whether you believe DOS style filename extensions are significant, or that they are a poor substitute for real metadata. If you come from Windows land, you might thing the file extension is the file type. If you come from Linux land, you might think that file extensions are just a label stuck on the file name as a convenience for the user. If you come from Macintosh land, especially pre-OS X, you probably think that file extensions are at best a useful redundancy and at worst an abomination. From a UI perspective, an application should never refuse to handle a file because of a mismatch between the file type contents, the file type metadata (if any), and the file extension, with one important proviso as follows. In general, if your application handles (say) both JPEGs and GIFs, and the user tries to open a JPEG named foo.gif, then the correct action is to advise the user that the file is actually a JPEG, and give them the opportunity to open the file anyway. Whether that is best handed internally by making Image.read() raise an exception or not is a question for the class designer. The proviso is, if there are potential security implications of that mismatch (e.g. an executable file masquerading as a .text file), and the target audience is technically naive, then I believe it may be appropriate for the application to refuse to handle the file. Don't let the user shoot themselves in the foot if they aren't technically sophisticated enough to realise they are shooting themselves in the foot. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
On Fri, 03 Feb 2006 03:51:03 -0800, n.estner wrote: My alternative syntax suggestion would be this one: class Pair: def self.__init__(a,b): self.a = a self.b = b def self.sum(): return self.a + self.b def this.product (): return this.a + this.b This would be a fairly major change to Python, so I think we can say right up front that the chances of this happening before Python 3 are zero, and even in Python 3 the chances are about the same as the chances of Richard Stallman suddenly announcing that he's taken a job for Microsoft writing Digital Restrictions Management software. But still, let's continue. After all, all you have to do is convince Guido that this syntax is better... You are really giving self a magic meaning with your suggestion which isn't needed at all. No. I hope this is clearer in the example above. self shouldn't be a keyword. Which it isn't now either. It's a special kind of argument now, so why shouldn't we explicitly _declare_ that it's a special kind of argument? (as explicit is better than implicit) And a foolish consistency is the hobgoblin of little minds *wink* [snip] def x(self): declares two new identifiers, x and self Why shouldn't def self.x(): declare two new identifiers (x and self), too? Sure, but now the call foo.bar has special meaning inside a def statement than elsewhere. Elsewhere, foo.bar is an attribute access, looking up attribute bar in foo's namespace. Using your syntax, in a def statement foo.bar is a pair of declarations: it declares a name foo, and it declares a second name bar. This inconsistency is, I think, worse than the implicit use of self. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Embedding Python into C/C++ applications
Hi Could somebody, please tell me where I can find information about embedding Python into a C/C++ application. The example in the docs is rather simple. I am looking for something a bit more complex and longer -- Best Regards John -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
On Fri, 03 Feb 2006 03:59:10 -0800, n.estner wrote: I still see newbie-friendliness as a MAJOR plus for Python -- it increases the chance that users of your software will become contributors. Yes, I 100% agree to that point! But the point is, the current situation is not newbie-friendly (I can tell, I am a newbie): I declare a method with 3 parameters but when I call it I only pass 2 parameters. That's confusing. Yes, I understand what you mean now. When I was a newbie, it took me a little while to get the difference between ordinary functions and methods too, although I had little OO experience before Python. I don't know if that helped or hindered the learning experience. With the current syntax, you have to learn some special behaviour: class Foo: def bar(self, x, y): pass but you call Foo().bar(x, y) But with your syntax, you still have to learn special behaviour: # outside the class definition self.bar # look up bar in self's namespace. self must already exist. # inside a class definition class Foo: self = Something() # normal class attribute self created # this works because self is not a keyword # Foo now has an attribute self def self.bar(x, y): # create a method bar with self in bar's namespace # Foo now has an attribute bar (which is a method) pass self.bar = None # normal attribute access # Foo attribute self is modified to have an attribute bar # there is no conflict between self the attribute and self the # special parameter because they live in different namespaces # but looking at them, there is an apparent conflict So, most of the time, foo.bar looks up attribute bar in foo; but in a method definition, foo.bar assigns attribute foo in bar. That's special behaviour too, and it seems to me probably harder to live with and even more confusing than the behaviour you aim to remove. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO conventions
Steven D'Aprano wrote: [...] If a class has a natural, obvious default state (e.g. a mutable string class might start off empty, a mutable int class might start off as zero, a binary tree might start off as an empty node with no children) then it makes sense to initialise the class, then add your data. But if the class has no natural default state, then it makes no sense to create an empty object with no data, a non-image image so to speak. I don't think this is all there is to it. Even though a class such as Image might not have a sensible default, initial state it still might not be reasonable to burden it with the ability to collect the information needed to reach such an initial state. To put it it another way: a car is a car, it isn't a car factory. In other words, if you find yourself writing methods like this: class Klass: def foo(self): if self.data is None: raise KlassError(Can't foo an uninitialized Klass object.) else: # do something Factory functions (or classes) are there to solve this problem and still allow a clean separation of concerns. Although instances of Klass are created uninitialized, they only live in this state within their factory and only reach trhe outside world only when they are in a usable state. Cheers, Nicola Musatti -- http://mail.python.org/mailman/listinfo/python-list
Re: Server side newbie
Thanks but the math is a bit complex and already coded and debugged in a python desktop gui. -- http://mail.python.org/mailman/listinfo/python-list
Re: Control if a input text is IP
Fredrik Lundh wrote: Sbaush wrote: My app has in input an ip address in IPv4 notation. is there a function that control if input is a string in IPv4 notation? here's one way to do it: Here's a function from the 'validate' module that comes with ConfigObj : def dottedQuadToNum(ip): Convert decimal dotted quad string to long integer dottedQuadToNum('1 ') 1L dottedQuadToNum(' 1.2') 16777218L dottedQuadToNum(' 1.2.3 ') 16908291L dottedQuadToNum('1.2.3.4') 16909060L dottedQuadToNum('1.2.3. 4') Traceback (most recent call last): ValueError: Not a good dotted-quad IP: 1.2.3. 4 dottedQuadToNum('255.255.255.255') 4294967295L dottedQuadToNum('255.255.255.256') Traceback (most recent call last): ValueError: Not a good dotted-quad IP: 255.255.255.256 # import here to avoid it when ip_addr values are not used import socket, struct try: return struct.unpack('!L', socket.inet_aton(ip.strip()))[0] except socket.error: # bug in inet_aton, corrected in Python 2.3 if ip.strip() == '255.255.255.255': return 0xL else: raise ValueError('Not a good dotted-quad IP: %s' % ip) return All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to determine if a certain PID is still running
David Hirschfield [EMAIL PROTECTED] wrote: I'm launching a process via an os.spawnvp(os.P_NOWAIT,...) call. So now I have the pid of the process, and I want a way to see if that process is complete. I don't want to block on os.waitpid(), I just want a quick way to see if the process I started is finished. On Unix, you can do kill (pid, 0), and if you get back ESRCH, you know the pid doesn't exist. It is the classic way to ask if a process is running on Unix. But, there's several problems with that, the biggest one being that those semantics don't seem to be exposed by phthon's os.kill() method. So, should I run a monitor thread which just calls os.waitpid() and when the thread indicates via an event that the process completed, I'm golden? That's what I would do. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I dynamically create functions without lambda?
Terry Hancock wrote: Note also in the datasets that *overperformers* *underrated* their performance. Well, if you're the best in the group and aren't perfectly exact in your evaluation of your position relative to others, you can't overrate yourself. It's quite natural that the self evaluation curve would be flatter than the actual curve, since noise will drive the curve towards the middle, and it's also natural that the bad performers are also less good at evaluating their own work, but the strange thing is that the lowest quartile has higher self- evaluation than the second lowest. I can't say my general picture of coworkers generally support *this*, but I supect we've all run across people who were incompetent and unaware of it now and then... -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
[EMAIL PROTECTED] wrote: The main reason (at least for me) is that there's simply too much magic in it. Why does the expression left of the '.' get promoted to the first parameter? One of the reasons I like Lua is because it doesn't do this, instead using the : operator to designate method-style calls. eg. a:foo(b, c) -- looks up foo within a, and calls it with (a, b, c) as parameters a.foo(b, c) -- looks up foo within a, and calls it with (b,c) as parameters This means there doesn't need to be a distinction between methods and functions, just a different operator to treat a function as if it was a method. When I started out in Python I figured that I could just assign functions to objects and treat them then as if they were methods, as I would in Lua, but quickly learned that it wasn't that simple. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Regular expression query
It's probably quite simple, but what I want is a regular expression to parse strings of the form: parameter=12ab parameter=12ab foo bar parameter='12ab' parameter='12ab' biz boz parameter=12ab parameter=12ab junk in each case returning 12ab as a match. parameter is known and fixed. The parameter value may or may not be enclosed in single or double quotes, and may or may not be the last thing on the line. If the value is quoted, it may contain spaces. I've tried a regex of the form: re.compile(r'parameter=([\']?(.*?)\1( *|$)') This works fine when the parameter's value is quoted, but if the quotes are missing, it falls over since the \1 is empty and so the non-greedy match anything ends up matching nothing. Any suggestions? Thanks M -- http://mail.python.org/mailman/listinfo/python-list
Re: HTMLDocument and Xpath
Alan Kennedy wrote: [EMAIL PROTECTED] Hi, I want to use xpath to scrape info from a website using pyXML but I keep getting no results. For example, in the following, I want to return the text Element1 I can't get xpath to return anything at all. What's wrong with this code? Your xpath expression is wrong. test = Evaluate('td', doc_node.documentElement) Try one of the following alternatives, all of which should work. test = Evaluate('//td', doc_node.documentElement) test = Evaluate('/html/body/table/tr/td', doc_node.documentElement) test = Evaluate('/html/body/table/tr/td[1]', doc_node.documentElement) HTH, Alan. I tried all of those and in every case, test returns []. Does Evaluate only work with XML documents? Shawn -- http://mail.python.org/mailman/listinfo/python-list
Re: OO conventions
Blair P. Houghton wrote: (snip) So Image.open(filename) seems right as a factory function that opens the file, figures out what it really is, constructs the appropriate subclass object (likely by passing a string to the constructor, e.g., JPGImage(filename)), and returns the object via the superclass type. Why via the superclass type ? returns the object is enough. The caller can then either check a flag in the superclass to see what type the subclass is, Why the h... ? We don't care what type it is, as long at it does what we expect it to do. or just assume it's the right type of image Yes (snip) (or does Python have RTTI? Much better than 'RTTI'. I don't recall if I've seen it, yet...). obj.__class__ is a reference to the class (which is itself an object...) Though if the filename doesn't match the content, someone should raise an exception... Why ? filenames and extensions are nothing more than conventions. Image.open() 's responsability is to create an object of the appropriate class, period. If *your program* needs to ensure that the image type matches the filename, it's your problem to check this. But this means that Image.open(filename) is a static method of the superclass, not requiring instantiation. AFAIK, it's just a function in the Image module (which is itself an object - instance of class module - but that's orthogonal). Image(string) could easily default to assuming string is a filename, doing the same work as Image.open(filename), though it would at least partially construct an Image instance each time it's called, which isn't what you want. Image.open(filename) defined as a static method (wait...is that possible in Python? I hate being the newbie) It is (search for 'staticmethod' and 'classmethod'). But there's not much use for 'static methods' in Python - we usually just use plain functions ('classmethods' are another beast - much more useful than staticmethods) -- 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
web.py + cheetah delivering incomplete pages
hi, yesterday i started with web.py / flup / cheetah, and managed to get a first webpage to diaplay on my windows box running apache. unfortunately, the following code import web urls = ( '(.*)', 'view' ) class view: def GET( self, name ): web.render( 'view.html' ) web.internalerror = web.debugerror if __name__ == '__main__': web.run( urls ) using this template, view.html: div #if $name I just wanted to say hello to $name. #else Hello, world! #end if /div #set $ninetyNine = 99 #for $count in $range($ninetyNine, 0, -1) div$count/div #end for h1finis./h1 will never print out the finis line -- it always stops short of that, displaying a 7 at the bottom of the page. it is tho the last few lines end up in a buffer and get see the light of day. any ideas? _wolf -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
Op 2006-02-03, Ben Sizer schreef [EMAIL PROTECTED]: [EMAIL PROTECTED] wrote: The main reason (at least for me) is that there's simply too much magic in it. Why does the expression left of the '.' get promoted to the first parameter? One of the reasons I like Lua is because it doesn't do this, instead using the : operator to designate method-style calls. eg. a:foo(b, c) -- looks up foo within a, and calls it with (a, b, c) as parameters a.foo(b, c) -- looks up foo within a, and calls it with (b,c) as parameters This means there doesn't need to be a distinction between methods and functions, just a different operator to treat a function as if it was a method. That is nice. I wonder if the following is possible in Lua: fun = a:foo fun(b, c) with the same effect as: a:foo(b, c) -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie - script works in PythonWin - fails from Python
Hi, This is all I get: error 250477278 Traceback (most recent call last): File script1.py, line 5, in ? Inst = lib.Initialize(0) WindowsError: exception code 0xeedfade I get this when running python.exe script1.py ** When run from inside PythonWin it runs beautifully and returns with no errors ** Regardless of what the error actually is it *works* when run from PythonWin. It fails only when run from the command line. I'm trying to find out why there is a difference. Clearly both either run a different interpreter or with different switches. I was hoping someone knows what the difference is. -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
[EMAIL PROTECTED] wrote: Having read previous discussions on python-dev I think I'm not the only Python programmer who doesn't particularly like python's self parameter: bang ! You're dead ! (no no, just kidding !-) class Foo: old-style classes are deprecated. class Foo(object): def bar(self, a,b): return a+b (snip) The point is, I _do_ think it's a good idea to explicitly write self.SomeMember for member-access, With Python's lookup rules, it couldn't be otherwise anyway !-) so I thought: why can't we be equally explicit about member function declaration? Because there's no such thing as a member function in Python. Wouldn't it be nice if I could write (say, in Python 3k, or maybe later): class Foo: def self.bar(a,b): return a+b Foo().bar(1,2) = 3 'bar' is not an instance attribute, but a class attribute - it belongs to *class* Foo, not to an instance of Foo. BTW, 'self' does not yet exist (and cannot possibly exist) when this code is eval'd (how could an instance of class Foo exists before class Foo itself exists ?). That way, the declaration would match the invocation (at least syntactically), and the magic-feeling is gone. In the long run, the old-style syntax (i.e. if there's no '.' in the method name) could be used for static methods. s/static/class/ What do you think? That you should learn more about the inners of Python's object model (and specially at the Descriptor protocol). class Foo(object): def __init__(self, a): self.a = a def bar(obj, b): return obj.a + b f = Foo(1) bar(f, 2) Foo.bar = bar Foo.bar(f, 2) f.bar(2) The only 'magic' here is that when bar() is called *as an attribute of a Foo instance*, the instance is passed as the first parameter. In fact, this is much more explicit (well, IMHO) than the 'this' reference in Java or C++. -- 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: would it be feasable to write python DJing software
On 2006-02-03, Ivan Voras [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: Actually, manipulating and mixing audio samples can be both fast and elegant, in Python, if you use Numeric or a similar library. ... at which point you're actually doing it in C, not pure python... :) If that's the way you want to look at it, there is nothing that can be done in pure python. Both the built-ins and the basic operators and sematics are implimented in C. Unless you're running Jython on a platform that has a hardware JVM, I suppose. But noboby in this discussion is doing that. -- Grant Edwards grante Yow! Should I get at locked in the PRINCICAL'S visi.comOFFICE today -- or have a VASECTOMY?? -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie - script works in PythonWin - fails from Python
[EMAIL PROTECTED] writes: Hi, This is all I get: error 250477278 Traceback (most recent call last): File script1.py, line 5, in ? Inst = lib.Initialize(0) WindowsError: exception code 0xeedfade I get this when running python.exe script1.py ** When run from inside PythonWin it runs beautifully and returns with no errors ** Regardless of what the error actually is it *works* when run from PythonWin. It fails only when run from the command line. I'm trying to find out why there is a difference. Clearly both either run a different interpreter or with different switches. I was hoping someone knows what the difference is. One difference is that PythonWin runs a messageloop. Does the documentation of the library you call say something about the error code you get? Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
Magnus Lycka [EMAIL PROTECTED] wrote: ... which isn't needed at all. So far, the existence of x.y somewhere in Python always implied that x was already introduced explicitly in the program, and you suggest that we violate that both in the Almost... import (and from) statements are exceptions to this. import x.y binds or rebinds name x on the fly, as well as attribute y of x. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: would it be feasable to write python DJing software
If that's the way you want to look at it, there is nothing that can be done in pure python. Both the built-ins and the basic operators and sematics are implimented in C. What makes python a powerful programming language? It's the fact that it bundles up all sorts of c-code into a nice easy to use language. When you write _any_ python, you are taking a peice of c here, a piece of c here, and when you import a pure python module, you're really just importing more c, because it's all being built from c. What makes a builtin faster? It's the fact that there's less work to be done before it's called. As more work needs to get done to find the builtins that make it possible to run, execution time increases. Plain and simple. So, to answer the original posters question, Use python to peice together the things you need. You're development time will be fast, and you will probably see some good results. -- Andrew Gwozdziewycz [EMAIL PROTECTED] http://ihadagreatview.org http://plasticandroid.org -- http://mail.python.org/mailman/listinfo/python-list
Re: would it be feasable to write python DJing software
On 2006-02-03, Fuzzyman [EMAIL PROTECTED] wrote: Come to that, you're **really** doing it in machine code... And probably not the machine code emitted by the assembler but rather the actual micro-code that's implemented in hardware that's running a program that implements the VM for the machine code emitted by the assemblers. Hell, from the Python point of view it might as well be tortoises all the way down. -- Grant Edwards grante Yow! Dehydrated EGGS are at STREWN across ROULETTE visi.comTABLES... -- http://mail.python.org/mailman/listinfo/python-list
Re: Fromatting an xml file
sir_alex [EMAIL PROTECTED] writes: Hi! I have a little problem writing xml files formatted in a way like the following: rootnode nodebla/node nodebla/node /rootnode Every new node element should have a tabulation before it, but when I use xml.dom.minidom I use writexml, which considers as a new node also the text (in my little example, bla phrases), so the best result I achieved has been the following rootnode node bla /node /rootnode but I don't want the text to be written on newlines... is there a good solution? Thanks! Based on recommendations from this newsgroup, I write XML directly, instead of going through DOM. That in turn requires a mechanism for tabbed indents, so I wrote tabbedwriter: http://www.seanet.com/~hgg9140/comp/index.html http://www.seanet.com/~hgg9140/comp/tabbedwriter/doc/tabbedwriter.help -- [EMAIL PROTECTED] 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
Steven D'Aprano [EMAIL PROTECTED] wrote: ... Why shouldn't def self.x(): declare two new identifiers (x and self), too? Sure, but now the call foo.bar call? has special meaning inside a def statement than elsewhere. Elsewhere, foo.bar is an attribute access, looking up attribute bar in foo's namespace. or setting it, as in foo.bar=23, or setting both names, as in import foo.bar Using your syntax, in a def statement foo.bar is a pair of declarations: it declares a name foo, and it declares a second name bar. declares isn't really pythonic -- let's talk about binding or setting names, instead. This inconsistency is, I think, worse than the implicit use of self. I don't think there's any inconsistency in deciding that syntax x.y has different meanings (as to what gets looked up or bound) in different contexts, because it already does: mostly look up y in namespace x, but in x.y=... it's bind y in namespace x and in import x.y it's bind x AND then bind y in namespace y. Since def x.y(... is currently a syntax error, it would introduce no backwards compatibility to assign a meaning to it. Since the 'def' statement binds something to the name that follows it (which currently must be a plain identifier), that's what it should do if it allowed the following name to be a compound one, too. Unfortunately, none of this suggests that it's reasonable to have def x.y(z): ... mean the same as def y(x, z): ... and I have no idea of how it would generalize to def x.y.z(t): ... (while import x.y.z generalizes in a pretty obvious way wrt import x.y). So, I'm not supporting the OP's idea; just rejecting the specific objections to it. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular expression query
Martin Biddiscombe wrote: It's probably quite simple, but what I want is a regular expression If it's simple, then you probably *dont* want a regexp. to parse strings of the form: parameter=12ab parameter=12ab foo bar parameter='12ab' parameter='12ab' biz boz parameter=12ab parameter=12ab junk in each case returning 12ab as a match. parameter is known and fixed. The parameter value may or may not be enclosed in single or double quotes, and may or may not be the last thing on the line. If the value is quoted, it may contain spaces. I've tried a regex of the form: re.compile(r'parameter=([\']?(.*?)\1( *|$)') This works fine when the parameter's value is quoted, but if the quotes are missing, it falls over since the \1 is empty and so the non-greedy match anything ends up matching nothing. Any suggestions? yes : forget regexps, use str methods. parse = lambda l: \ l.split('=',1)[1].split()[0].strip().strip('\) NB : I tried my best to make it as obfuscated as a regexp so you still gain extra bonus points from Perl-addicts !-p - but feel free to rewrite this cleanly. Thanks HTH -- 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
problems writing tuple to log file
i am having a problem writing a tuple to a text file. my code is below. what i end up getting is a text file that looks like this burger, 7up burger, 7up burger, 7up and this is instead of getting a list that should look like this burger, 7up fries ,coke cake ,milk note that i have print statements that print out the results of the scraping and they are fine. they print out burger, fries, cake and then 7up, coke, milk however there is something faulty in my writing of the tuple to the text file. perhaps related to the indentation that causes it to write the same stuff over and over? for row in bs('div'): data=[] for incident in bs('span'): foodlist = [] b = incident.findPrevious('b') for oText in b.fetchText( oRE): #foodlist.append(oText.strip() + ',) foodlist += oText.strip() + ',' food = ''.join(foodlist) print food for incident in bs('span2'): drinklist = [] for oText in incident.fetchText( oRE): drinklist += oText.strip() + ',' drink = ''.join(drinklist) print drink tuple = (food + drink \n) data.append(tuple) f = open(data.txt, 'a') f.write ( ''.join( tuple ) ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular expression query
parameter=12ab parameter=12ab foo bar parameter='12ab' parameter='12ab' biz boz parameter=12ab parameter=12ab junk in each case returning 12ab as a match. parameter is known and fixed. The parameter value may or may not be enclosed in single or double quotes, and may or may not be the last thing on the line. If the value is quoted, it may contain spaces. I've tried a regex of the form: re.compile(r'parameter=([\']?(.*?)\1( *|$)') Below is a test-harness that seemed to spit out the results you want (I threw in some bogus tests to make sure they failed too) with the given value for exp. The resulting match object will have your desired value in group(1)...though it will include whatever quotes happened to be in it. You may also need to anchor accordingly with ^ and $ It doesn't gracefully handle escaped quotes in your value -tim import re tests = [ ('parameter=12ab', True), ('parameter=12ab foo bar', True), (parameter='12ab', True), (parameter='12ab' biz boz, True), ('parameter=12ab', True), ('parameter=12ab junk', True), ('parameter=12ab', False), ('parameter=\'12ab', False), ('parameter=12ab\'', False), ('parameter=12ab\' foo baz', False) ] exp = r'parameter=(([\'])(.*?)\2|[^\' ]+).*' r = re.compile(exp) print Using regexp: %s % exp for test,expectedResult in tests: if r.match(test): result = True else: result = False if result == expectedResult: print [%s] passed % test else: print [%s] failed (expected %s, got %s) % (test, expectedResult, result) -- http://mail.python.org/mailman/listinfo/python-list
py2exe question
Hi, I just installed py2exe to create a binary of my Python script. However, py2exe does not seem to create a binary from my .py script. This is what I have done: I create a setup.py script: # setup.py from distutils.core import setup import py2exe setup(name=APP1, scripts=[C:\\Python24\\_APP1.py],) I then ran python setup.py py2exe I see a lot of stuff scrolling on the screen. A 'built' directory is created. At the end I get a message saying that I may or may not need to include some DLL (all windows system DLLs). and that's it. No error message but also no binary. When I remove 'scripts=[C:\\Python24\\_APP1.py]' from the setup.py file, I get exactly the same result. The same output, no error, no binary. Any idea what I am doing wrong here? Where should the compiled binary go? Any help much appreciated. Kris -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to determine if a certain PID is still running
Am Thu, 02 Feb 2006 17:10:24 -0800 schrieb David Hirschfield: I'm launching a process via an os.spawnvp(os.P_NOWAIT,...) call. So now I have the pid of the process, and I want a way to see if that process is complete. I don't want to block on os.waitpid(), I just want a quick way to see if the process I started is finished. I could popen(ps -p %d % pid) and see whether it's there anymore...but since pids get reused, there's the chance (however remote) that I'd get a false positive, plus I don't really like the idea of calling something non-pure-python to find out. Hi, at least on linux you can test this: os.path.exists(/proc/%d % mypid) If you want to be sure that the pid is not reused, you can look at: /proc/PID/cmdline Maybe you can read the parent-pid in the proc directory. This should be the pid if your script. HTH, Thomas -- Thomas Güttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: learning python, using string help
On Fri, 2 Feb 2006, [EMAIL PROTECTED] wrote: silly newbie mistake your code runs fine on my openbsd box. ( I didnt uncomment the return map(...) line My apologies - i should have made it clearer in the comment that it was hardwired to return example data! thanks for the awesome example! I'm not sure how awesome it is - it's pretty simple, and probably has lots of bugs. Is the BSD ruptime output format the same as on HP-UX? I have a Mac myself, but no local machines broadcasting rwho data, so i don't get any output to play with when i run ruptime! tom -- hip whizzo teddy bear egghead realpolitik tiddly-om-pom-pom sacred cow gene blues celeb cheerio civvy street U-boat tailspin ceasefire ad-lib demob pop wizard hem-line lumpenproletariat avant garde kitsch sudden death Big Apple sex drive-in Mickey Mouse bagel dumb down pesticide racism spliff dunk cheeseburger Blitzkrieg Molotov cocktail snafu buzz pissed off DNA mobile phone megabucks Wonderbra cool Big Brother brainwashing fast food Generation X hippy non-U boogie sexy psychedelic beatnik cruise missile cyborg awesome bossa nova peacenik byte miniskirt acid love-in It-girl microchip hypermarket green Watergate F-word punk detox Trekkie naff all trainers karaoke power dressing toy-boy hip-hop beatbox double-click OK yah mobile virtual reality gangsta latte applet hot-desking URL have it large Botox kitten heels ghetto fabulous dot-commer text message google bling bling 9/11 axis of evil sex up chav -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie - script works in PythonWin - fails from Python
Unfortunately not. Is there any doc anywhere that shows how to make the script run from the command line the same way it does within PythonWin? -- http://mail.python.org/mailman/listinfo/python-list
Wanted: Django Programmer Seeking PyCon Fame and Glory
Coming to PyCon 2006 in Dallas in a few weeks? Want to make a name for yourself before you arrive? Think Django is cool and want everyone else to know it? Whip up a Django app to slide into the PyCon website (already running Django in part) that hooks into Google's Map API. Provide a way for conference attendees to stick virtual pins on where they are from (and perhaps leave a popup note for others to find ;-). There are already 350 people signed up, so your application must scale that far. The PyCon website already runs PostgreSQL or store the data in a local file of some flavor, your choice, but make sure its reasonably CPU efficient. The trick is to provide a user API for attendees to enter or mark their origin. Must be themable to drop into the site's existing layout. You only have until Feb 22 to implement it, and achieve glory. The conference website is at http://us.pycon.org. Drop me a line if you have questions to get your finished application installed on the conference server. (offer includes fame only, no fortune). -Jeff P.S. Can't make it to PyCon this year? Hey, you too can write the app and let'm know what they missed! -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
On Fri, 03 Feb 2006 07:40:38 -0800, Alex Martelli wrote: Steven D'Aprano [EMAIL PROTECTED] wrote: ... Why shouldn't def self.x(): declare two new identifiers (x and self), too? Sure, but now the call foo.bar call? Call? Who said anything about a call? *wink* Okay, poor choice of words. I'm not exactly sure what a better choice would be. Token? Too specific. Maybe it would have been better to just have just said ...but now foo.bar has has special meaning inside a def statement than elsewhere. Elsewhere, foo.bar is an attribute access, looking up attribute bar in foo's namespace. or setting it, as in foo.bar=23, Conceptually, both setting and getting an attribute involves a look up in the general sense: you need to look up the attribute to get its value, or to find out where to put its value. You are correct (of course!) that foo.bar can either be a get or a set, but I'm doing lots of hand-waving here and I didn't think it was necessary to get bogged down in too much detail. or setting both names, as in import foo.bar Ah, I completely forgot about import. But see below. Using your syntax, in a def statement foo.bar is a pair of declarations: it declares a name foo, and it declares a second name bar. declares isn't really pythonic -- let's talk about binding or setting names, instead. Yes, you're right, it is a bad habit. Years of Pascal don't die easily. This inconsistency is, I think, worse than the implicit use of self. I don't think there's any inconsistency in deciding that syntax x.y has different meanings (as to what gets looked up or bound) in different contexts, because it already does: mostly look up y in namespace x, but in x.y=... it's bind y in namespace x Which from my perspective are conceptually two sides of the coin. The model I have is y is a label in some namespace x, and you have to (in some sense) look up where y should go regardless of whether you are setting the value or getting the value. Do you think this model is so far from the actual behaviour of Python that it is useless? Or is it fair to lump getting and setting attributes/names together? and in import x.y it's bind x AND then bind y in namespace y. I assume that's a typo and you mean bind y in namespace x. But even import x.y is conceptually a lookup, equivalent to x.y = __import__(x.y), with the understanding that x = __import__(x) is automagically run first. [hand-waving, hand-waving, hand-waving... of course imports do a lot more than just setting a name in a namespace] But in all three of: foo.bar = something something = foo.bar import foo.bar the hierarchy goes from left to right, with bar being inside foo, for some meaning of inside. The Original Poster's syntax would reverse that, with def foo.bar(x,y) creating parameter foo inside method bar. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: would it be feasable to write python DJing software
On Fri, 3 Feb 2006, Ivan Voras wrote: Levi Campbell wrote: Hi, I'm thinking about writing a system for DJing in python, but I'm not sure if Python is fast enough to handle the realtime audio needed for DJing, could a guru shed some light on this subject and tell me if this is doable or if I'm out of my fscking mind? Perhaps surprisingly, it is: http://www.python.org/pycon/dc2004/papers/6/ At least, you can certainly mix in realtime in pure python, and can probably manage some level of effects processing. I'd be skeptical about decoding MP3 in realtime, but then you don't want to write your own MP3 decoder anyway, and the existing ones you might reuse are all native code. Any and all mixing would probably happen in some sort of multimedia library written in C (it would be both clumsy to program and slow to execute if the calculations of raw samples/bytes were done in python) Clumsy? Clumsier than C? No, python isn't as good with binary data as it is with text or objects, but on the whole program scale, it's still miles ahead of C. My advice would be to tackle the task in the same way you'd tackle any other: write it in pure python, then fall back to native code where it's unavoidable. When i say 'pure python', i don't mean 'not using any native modules at all', obviously - if someone's written an MP3 decoder, don't eschew it because it happens to be in C. Also, bear in mind that resorting to native code doesn't automatically mean writing in C - you can start doing stuff like moving from representing buffers as lists of ints to using NumPy arrays, using the functions in the standard audioop module, whatever; if that's not fast enough, rewrite chunks of the code in pyrex (a derivative of python that can be compiled to native code, via translation to C); if it's still not fast enough, go to C. Oh, and before you start going native, try running your program under psyco. tom -- Throw bricks at lawyers if you can! -- http://mail.python.org/mailman/listinfo/python-list
Re: problems writing tuple to log file
[EMAIL PROTECTED] wrote: i am having a problem writing a tuple to a text file. my code is below. what i end up getting is a text file that looks like this burger, 7up burger, 7up burger, 7up and this is instead of getting a list that should look like this burger, 7up fries ,coke cake ,milk note that i have print statements that print out the results of the scraping and they are fine. they print out burger, fries, cake and then 7up, coke, milk however there is something faulty in my writing of the tuple to the text file. perhaps related to the indentation that causes it to write the same stuff over and over? for row in bs('div'): What kind of function is 'bs'? Should you use 'row' (which you are looping over) inside the loop? Seems that your code is equal to for row in range(len(bs('div'))): for incident in bs('span'): Just like you use 'incident' here, inside the other loop. foodlist = [] b = incident.findPrevious('b') for oText in b.fetchText( oRE): #foodlist.append(oText.strip() + ',) foodlist += oText.strip() + ',' food = ''.join(foodlist) print food After print food you repeat the loop, overwriting food until last round. And after you have found the last food, you put it in tuple. tuple = (food + drink \n) A tip: 'tuple' is a built-in function, just like 'open' you use. This statement overwrites that function with a string. It is usually a good idea to leave the built-ins as they are, and use some other names for variables. -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
... Unfortunately, none of this suggests that it's reasonable to have def x.y(z): ... mean the same as def y(x, z): ... Actually, it shouldn't. The idea was, that def x.y(z): ... (explicitly) introduces an unbound method. That's not introducing a new conect to python, it's just making the difference between an unbound method and a not-bindable function explicit. Currently, def(x,y): ... can mean two different things: In the context of a class, it introduces an unbound method, in global or local contexts it introduces a function. I don't want to have a new syntax for that, I want two different syntaxes for these two different meanings. and I have no idea of how it would generalize to def x.y.z(t): ... Nor do I. Is that a problem? -- http://mail.python.org/mailman/listinfo/python-list
Compiling
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 -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie - script works in PythonWin - fails from Python
On Fri, 03 Feb 2006 07:00:37 -0800, marcus.tettmar wrote: Hi, This is all I get: error 250477278 What is this line? That doesn't look like part of a Python traceback. I suppose it is possible that the DLL is printing it before the exception is raised. Or did you type it yourself? Traceback (most recent call last): File script1.py, line 5, in ? Inst = lib.Initialize(0) WindowsError: exception code 0xeedfade I get this when running python.exe script1.py You're still making it as hard as possible for anyone to help you. Is it a secret what DLL you are trying to call? What is lib? Googling on 0xeedfade suggests that it is an internal Delphi error, possibly an out-of-memory error. Are you calling a Delphi DLL? What does that exception mean? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie - script works in PythonWin - fails from Python
Thomas Heller wrote: This is all I get: error 250477278 Traceback (most recent call last): File script1.py, line 5, in ? Inst = lib.Initialize(0) WindowsError: exception code 0xeedfade I get this when running python.exe script1.py ** When run from inside PythonWin it runs beautifully and returns with no errors ** Regardless of what the error actually is it *works* when run from PythonWin. It fails only when run from the command line. I'm trying to find out why there is a difference. Clearly both either run a different interpreter or with different switches. I was hoping someone knows what the difference is. One difference is that PythonWin runs a messageloop. Does the documentation of the library you call say something about the error code you get? a quick googling indicates that 0xEEDFADE is usually caused by an internal unhandled exception in Delphi. maybe there's some Borland- specific DLL that's not found when the code is running from the con- sole ? I suppose you could use process explorer to see if you can figure out what Borland DLL:s the program is using: http://www.sysinternals.com/ProcessesAndThreadsUtilities.html /F -- http://mail.python.org/mailman/listinfo/python-list
Re: problems writing tuple to log file
[EMAIL PROTECTED] wrote: i am having a problem writing a tuple to a text file. my code is below. I'd rather say you are having a problem with logic. what i end up getting is a text file that looks like this burger, 7up burger, 7up burger, 7up Which is exactly what one would expect (in the best case...) given the code you've written. and this is instead of getting a list that should look like this burger, 7up fries ,coke cake ,milk however there is something faulty in my writing of the tuple to the text file. Nope, the problem is elsewhere. perhaps related to the indentation that causes it to write the same stuff over and over? You clearly have a problem with indentation (hint : use spaces not tabs), but this is not the cause of your problem. for row in bs('div'): data=[] for incident in bs('span'): foodlist = [] Do you understand that this reinitialise foodlist on each iteration ? b = incident.findPrevious('b') for oText in b.fetchText( oRE): #foodlist.append(oText.strip() + ',) foodlist += oText.strip() + ',' Concatening a string to a list may not exactly do what you think. Try printing foodlist, you'll be surprised. food = ''.join(foodlist) Do you understand that this overwrite 'food' on each iteration ? print food for incident in bs('span2'): drinklist = [] Same observation as above for oText in incident.fetchText( oRE): drinklist += oText.strip() + ',' idem drink = ''.join(drinklist) idem print drink tuple = (food + drink \n) 1/ dont use 'tuple' as an identified, it shadows the builtin type tuple. 2/ anyway, this is *not* a tuple. What you get here is a string made of the concatenation of the actual values of food and drink plus a newline. Ok, at this stage, the name 'food' *may* exist, in which case it'll be bound to the value found for the last iteration of the first 'for' loop. Note that it may also not exist at all, if bs('span') returns an empty sequence - in which case you'll get a nice NameError exception. Same for 'drink' of course. data.append(tuple) Why to you append this to a list that you don't use ? f = open(data.txt, 'a') This may fail. Please use a try/except block. f.write ( ''.join( tuple ) ) And please close the file once done. Your code is such a mess that it's difficult to know for sure what you're trying to do - and you don't provide much context (hint : when asking for help, try and post the minimal *runnable* code that exhibit your problem - 'runnable' meaning that anyone can run your snippet in it's python interpreter). What follows is an attempt at rewriting the whole damn thing so it as at least a chance to behave sensibly - I wouldn't bet that this actually what you *should* write but I hope this may help you understand where your errors are. But please dont ask for further help on this code before you've folowed a good (preferably programming-newbie oriented) Python tutorial ('learning to think like a computer scientist' may be a wise choice). # - data=[] for row in bs('div'): foodlist = [] for incident in bs('span'): b = incident.findPrevious('b') for oText in b.fetchText( oRE): foodlist.append(oText.strip()) drinklist = [] for incident in bs('span2'): for oText in incident.fetchText( oRE): drinklist.append(oText.strip()) # I suppose you expect to have 1 drink for 1 food assert len(foodlist) == len(drinklist) pairs = zip(foodlist, drinklist) data += pairs try: f = open(data.txt, 'a') except IOError, e: # handle error here print oops, failed to open 'data.txt' : %s % e else: f.write(\n.join([%s, %s % pair for pair in data]) f.close() # - A last advice : Python comes with an interactive interpreter, which is a real powertool for learning, testing and debugging. So *use it*. HTH -- 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: newbie - script works in PythonWin - fails from Python
Hi, Sorry, I'm not trying to make things hard! I just can't figure why it works when run from PythonWin and not from Python - PythonWin MUST load some extra library. Anyway, I have finally fixed it by adding import win32com to the top of the script. Am guessing the DLL uses COM and PythonWin must already load it. -- http://mail.python.org/mailman/listinfo/python-list
Python on Windows
I've just written my first (simple) WxPython program - yy! What would folks suggest is the easiest way to package it to run on other windows PCs? I would love a single .exe file that would run without ANY OTHER FILES even if it was 50 Mb! TIA Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on Windows
Simon Faulkner wrote: I've just written my first (simple) WxPython program - yy! What would folks suggest is the easiest way to package it to run on other windows PCs? I would love a single .exe file that would run without ANY OTHER FILES even if it was 50 Mb! TIA Simon Py2Exe -- http://mail.python.org/mailman/listinfo/python-list
Re: OS.MKDIR( ) Overwriting previous folder created...
The corect way is to try os.mkdir, catch the exception and check the errno value, which tell you why the call failed. If the directory exists, you can ignore the exception, if its another error, you usually had to raise it again and let the caller handle it. Example: import errno try: os.mkdir(path) except OSError, err: if err.errno != errno.EEXIST: raise Any other way may have race conditions, for example, you check if the directory exits, and its missing, then another process or thread creates it before you try to create the missing directory, and your mkdir call will raise. -- 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? But there *is* a compiler for Python. http://www.python.org/doc/2.4.2/lib/module-compiler.html -- 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: Python on Windows
Simon Faulkner wrote: I've just written my first (simple) WxPython program - yy! What would folks suggest is the easiest way to package it to run on other windows PCs? I can't tell for sure since I do not use Windows, but I think Py2Exe is what you're looking for. -- 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: Compiling
Simon Faulkner wrote: ... why hasn't someone written a compiler for Python? I guess it's not that simple eh? What would you call PyPy? As to the idea of a python-to-machine code translator, the benefit would not be very great without at least a PyPy level of understanding of the code -- no simple translation would be much faster than the CPython implementation. By the way, be careful about your tone. It sounds like brick-throwing in this generally friendly newsgroup. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling
Simon Faulkner: why hasn't someone written a compiler for Python? http://www.python.org/doc/faq/general.html#can-python-be-compiled-to-machine-code-c-or-some-other-language -- René Pijlman -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling
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? But there *is* a compiler for Python. http://www.python.org/doc/2.4.2/lib/module-compiler.html ty Bruno, I must confes that I don't understand much of that chapter! I will work harder... :-) -- 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? The simple explanation for the lack of a Python compiler is the massive dynamisism (sp) in Python - since you can change practically everything at any time, in order to compile a generic python program, you have to effectively include the entire interpreter. It's been done before (Python2C was the name, I think), but there wasn't much of a speed-up vs. CPython, and it hasn't been updated to work with recent versions of Python. Recently there has been work on JIT type dynamic compilation techniques, and static compilation of a reduced Python subset. If you want to know more, look up the PyPy project. http://www.codespeak.net/pypy -- http://mail.python.org/mailman/listinfo/python-list
Re: web.py + cheetah delivering incomplete pages
hi, i think you'd have better luck at http://groups.google.com/group/webpy -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling
Simon Faulkner wrote: 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? But there *is* a compiler for Python. http://www.python.org/doc/2.4.2/lib/module-compiler.html ty Bruno, I must confes that I don't understand much of that chapter! I will work harder... :-) Hint : You probably don't need to understand anything in this chapter. This compiler compiles Python source code to Python bytecode, which is then executed by the Python interpreter. You may not have noticed - since the Python interpreter is smart enough to call the compiler when needed - but Python is compiled to bytecode before execution. Just look at all the .pyc files on your filesystem. 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. HTH -- 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: Compiling
Simon Faulkner wrote: 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? There are various compilers for Python, but they vary in terms of capabilities, language support and method of operation. Disregarding Jython and the jythonc tool, which I believe is somewhat inspired by earlier tools for CPython, there has been a fair amount of activity and a number of works and/or papers on the topic. First of all, there have been conventional compilers such as Python to C [1] and other early attempts to do similar things [2, 3, 4]; such work possibly informed the construction of some of the bundler/installer tools [5]. Then, there were later attempts such as Starkiller [6] to produce low-level language code, and also compilers which produce other high-level languages [7, 8]. Most of the aforementioned projects have attempted to deal with normal Python, possibly with the exception of Starkiller. Subsequent works which deal with more restricted dialects of Python include ShedSkin [9]. Then, there are hybrid language compilers such as Pyrex [10] which avoid the issues of turning highly dynamic Python code into some low-level representation by allowing programmers to write speed-critical sections in a special Python dialect which translates better into C/C++. Finally, there are just-in-time compilers such as Psyco [11] which make use of run-time information to generate machine code specialised for the operations being performed; the PyPy project [12] appears to have such concerns in mind in the design of possible replacement virtual machines for Python. I guess it's not that simple eh? Well, there have been other projects, too. Once upon a time there was a promising alternative implementation of Python called Vyper [13, 14] but work on that was discontinued. One prematurely-hyped work, pycore [15], involved translating Python to Smalltalk but disappeared almost instantly. I believe that many Python programmers who are vocal on such topics don't want to surrender any of the functionality that they've become accustomed to, and with additional functionality arriving all the time in CPython, it's arguably difficult to reconcile such functionality with performant low-level code generation (at least in advance of run-time). That said, there has been a movement to introduce static typing, ostensibly for reliability purposes, but such justifications have arguably arisen because claims about the various proposed typing models and performance have largely gone unproven. Paul [1] http://sourceforge.net/projects/p2c/ [2] http://www.python.org/workshops/1996-06/papers/hugunin.IPCIV.html [3] http://www.foretec.com/python/workshops/1998-11/proceedings/papers/riehl/riehl.html [4] http://www.foretec.com/python/workshops/1998-11/proceedings/papers/aycock-211/aycock211.html [5] http://davidf.sjsoft.com/mirrors/mcmillan-inc/install1.html [6] http://www.python.org/pycon/dc2004/papers/1/ [7] http://perthon.sourceforge.net/ [8] http://www.python.org/workshops/2000-01/proceedings/papers/aycock/aycock.html [9] http://sourceforge.net/projects/shedskin/ [10] http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ [11] http://psyco.sourceforge.net/ [12] http://codespeak.net/pypy/dist/pypy/doc/news.html [13] http://monkeyfist.com/articles/266 [14] http://gnosis.cx/publish/programming/charming_python_8.html [15] http://webpages.charter.net/allanms/2004/08/you-dont-tug-on-supermans-cape.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiling
Oh, and I forgot another Aycock creation: UCPy [16]. Paul [16] http://pages.cpsc.ucalgary.ca/~aycock/papers/ucpy.pdf -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
On 3 Feb 2006 08:58:56 -0800, [EMAIL PROTECTED] wrote: ... Unfortunately, none of this suggests that it's reasonable to have def x.y(z): ... mean the same as def y(x, z): ... Actually, it shouldn't. The idea was, that def x.y(z): ... (explicitly) introduces an unbound method. That's not introducing a new conect to python, it's just making the difference between an unbound method and a not-bindable function explicit. Currently, def(x,y): ... can mean two different things: In the context of a class, it introduces an unbound method, in global or local contexts it introduces a function. I don't want to have a new syntax for that, I want two different syntaxes for these two different meanings. Are you sure you actually understand what's going on? 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. def foo(): pass ... print type(foo) type 'function' class bar: ... def foo(self): pass ... print type(foo) ... type 'function' print type(bar.foo) type 'instancemethod' Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
MySQLdb question... using table name as arg
I have four tables that all have the same column names (50 in each.) I have created an admin program to edit, delete and add records to the tables and would like to use the table name as a variable in each query so the code can be used for each of the 4 tables. Usually I would do something like this by having 1 table with special column to categorize the records as I am doing with each table, but this specific application requires that I do it with 4 tables instead. To ensure that string are quoted properly without any hassle I use the execute function like so assuming c is my cursor object... c.execute(update tableName set col1 = %s, col2 = %s, col3 = %s, ..., (val1, val2, val3, ...)) But, not I want to do this with a variable tableName. If I add it to the tuple of parameters in the second arg before val1 and replace tableName with %s, then the tableName will be quoted in the query, causing an error. What is the best (easiest) way for me to accomplish this? I know it may be a stupid question but I just can't figure it out. Thanks for any help. -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb question... using table name as arg
On Fri, 2006-02-03 at 13:24, Sean Berry wrote: I have four tables that all have the same column names (50 in each.) I have created an admin program to edit, delete and add records to the tables and would like to use the table name as a variable in each query so the code can be used for each of the 4 tables. Usually I would do something like this by having 1 table with special column to categorize the records as I am doing with each table, but this specific application requires that I do it with 4 tables instead. To ensure that string are quoted properly without any hassle I use the execute function like so assuming c is my cursor object... c.execute(update tableName set col1 = %s, col2 = %s, col3 = %s, ..., (val1, val2, val3, ...)) But, not I want to do this with a variable tableName. If I add it to the tuple of parameters in the second arg before val1 and replace tableName with %s, then the tableName will be quoted in the query, causing an error. What is the best (easiest) way for me to accomplish this? I know it may be a stupid question but I just can't figure it out. As you have discovered, the table name is not allowed to be a parameter. You have to build the query string for the appropriate table, then hand it to execute for filling in the actual parameters: queryString = update +tableName+ set col1=%s, col2=%s,... c.execute(queryString, (val1, val2,...)) HTH, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
In article [EMAIL PROTECTED], [EMAIL PROTECTED] wrote: That usage (self is second parameter to B.test) is bound to cause trouble in general, but in this case doesn't have any effect I can see. The function call test would be resolved from its first parameter, instance of A, and that function would return 1. One of us is missing something here, could be me. Probably my example wasn't clear, let's try another: class A: def test(a, **kwargs): return 1 class B: def test(b, **kwargs): return 2 test(a=A(), b=B()) self isn't a keyword, so nothing should forbid this code. What is the interpreter to do if it stumbles across this test call? I mean, named-argument lookup is a tricky thing even if you do know what function you're calling. If this would depend on one of the parameters, I think it would become completely unintelligible. (you can think of more complex examples yourself) Still see no problem. Of course, it goes without saying that Python 2.4 doesn't work this way, but given that it's theoretically possible for f(a) to be resolved similarly to a.f, then I really do not see what you're seeing here. The kwargs parameter appears irrelevant from where I'm sitting. That's exactly the problem, it doesn't read from left to right, because we swap back and forth between function(parameter and parameter.function notation. That's because they're doing two different things: object.method() does an attribute lookup, while function(parameter) looks for the function in the current scope. But current scope is actually a compound lookup - function scope, global scope etc. Generalize it to object scope, and then you can have a notation that expresses these things consistently - QED. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb question... using table name as arg
Carsten Haese [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Fri, 2006-02-03 at 13:24, Sean Berry wrote: I have four tables that all have the same column names (50 in each.) I have created an admin program to edit, delete and add records to the tables and would like to use the table name as a variable in each query so the code can be used for each of the 4 tables. Usually I would do something like this by having 1 table with special column to categorize the records as I am doing with each table, but this specific application requires that I do it with 4 tables instead. To ensure that string are quoted properly without any hassle I use the execute function like so assuming c is my cursor object... c.execute(update tableName set col1 = %s, col2 = %s, col3 = %s, ..., (val1, val2, val3, ...)) But, not I want to do this with a variable tableName. If I add it to the tuple of parameters in the second arg before val1 and replace tableName with %s, then the tableName will be quoted in the query, causing an error. What is the best (easiest) way for me to accomplish this? I know it may be a stupid question but I just can't figure it out. As you have discovered, the table name is not allowed to be a parameter. You have to build the query string for the appropriate table, then hand it to execute for filling in the actual parameters: queryString = update +tableName+ set col1=%s, col2=%s,... c.execute(queryString, (val1, val2,...)) HTH, Thanks... that is kind of what I figured. -- http://mail.python.org/mailman/listinfo/python-list
Re: would it be feasable to write python DJing software
Grant Edwards wrote: On 2006-02-03, Ivan Voras [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: Actually, manipulating and mixing audio samples can be both fast and elegant, in Python, if you use Numeric or a similar library. ... at which point you're actually doing it in C, not pure python... :) If that's the way you want to look at it, there is nothing that can be done in pure python. I think people who say that deliberately misunderstand the point. Python is suitable for some things, not for others. So is C. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO conventions
Nicola Musatti wrote: I don't think this is all there is to it. Even though a class such as Image might not have a sensible default, initial state it still might not be reasonable to burden it with the ability to collect the information needed to reach such an initial state. To put it it another way: a car is a car, it isn't a car factory. What's the burden, though? Surely the only burden is that the class needs to take the relevant parameters to its __init__ method, which is no more of a burden than providing some other initialization method that takes the relevant parameters. Factory functions (or classes) are there to solve this problem and still allow a clean separation of concerns. Although instances of Klass are created uninitialized, they only live in this state within their factory and only reach trhe outside world only when they are in a usable state. This may be my limited imagination, but I can't think of a situation when you would prefer something like: def factory(info): k = Klass() data = get_initial_data(info) k.set_data(data) return k to: def factory(info): data = get_initial_data(info) return Klass(data) What would be the value of doing the initialization in a separate method, rather than the constructor? -- http://mail.python.org/mailman/listinfo/python-list
Python - python-list
Hello, I am trying to automate my personal website logons and recently discovered cPamie, which looks like it may be a very handy tool indeed. But, so far, I have not had any luck using it for website logons. This may or may not be a cPamie issue, so please bear with me. The site I am trying to log on to automatically displays my username, but I must feed it my password in order to log on. No problem. I can get my password in the textbox, just fine. Where I have problems, however, is with the invocation of the log on itself. I am no HTML guru and am much more familiar with Python than any of the more accepted web languages, but I can read it well enough to sort of partially diagnose the problem. It appears that the buttonname itself is hidden--which means (I think) that I cannot call a method requiring the input of a buttonname. I have tried a number of methods from cPamie in order to try to log on, in lieu of the buttonname, but so far I have been unsuccessful. Does anyone know of a solution to this problem? (Incidently, I can log on by pressing the button with my mouse, but it is key and mouse strokes I am trying to eliminate, of course) Thanking you in advance, Chris N. View this message in context: Python - python-list Sent from the Python - python-list forum at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb question... using table name as arg
Carsten Haese wrote: On Fri, 2006-02-03 at 13:24, Sean Berry wrote: I have four tables that all have the same column names (50 in each.) I ... would like to use the table name as a variable in each query so the code can be used for each of the 4 tables To ensure that string are quoted properly without any hassle I use the execute function like so assuming c is my cursor object... c.execute(update tableName set col1 = %s, col2 = %s, col3 = %s, ..., (val1, val2, val3, ...)) What is the best (easiest) way for me to accomplish this? I know it may be a stupid question but I just can't figure it out. As you have discovered, the table name is not allowed to be a parameter queryString = update +tableName+ set col1=%s, col2=%s,... c.execute(queryString, (val1, val2,...)) Since you are in control of the query strings, you might try: choose a string ('table' in this example) to represent the table name that will never appear in your queries to represent the table name, then do something like: for table_name in 'first', 'second', 'third', 'fourth': def perform(query, args): return cursor.execute( table_name.join(query.split('table')), args) perform('UPDATE table SET col1 = %s, col2 = %s', (val1, val2)) perform('UPDATE table SET col4 = %s, col5 = %s', (val4, val5)) Although, frankly, this doesn't sound like a well-designed database. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I dynamically create functions without lambda?
On Fri, 3 Feb 2006 09:39:39 +0100 Fredrik Lundh [EMAIL PROTECTED] wrote: Terry Hancock wrote: Frankly this paper sounds like a bid for the Journal of Irreproducible Results that somehow got accidentally submitted to a serious journal http://www.improbable.com/ig/ig-pastwinners.html#ig2000 /F Wow. It's a relief to know I'm not the only one who regards this paper as a joke. :-) Cheers, Terry -- Terry Hancock ([EMAIL PROTECTED]) Anansi Spaceworks http://www.AnansiSpaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: would it be feasable to write python DJing software
On Fri, 03 Feb 2006 20:03:01 +0100 Ivan Voras [EMAIL PROTECTED] wrote: Grant Edwards wrote: On 2006-02-03, Ivan Voras [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: Actually, manipulating and mixing audio samples can be both fast and elegant, in Python, if you use Numeric or a similar library. ... at which point you're actually doing it in C, not pure python... :) If that's the way you want to look at it, there is nothing that can be done in pure python. I think people who say that deliberately misunderstand the point. Python is suitable for some things, not for others. So is C. -- To me, doing it in C implies that I must write some C code. In this case, that won't be required at all. Everything the OP wants to do can be done exclusively by writing Python code. He will, of course, be *using* some extension libraries which might in turn have been written in C (or Fortran, assembly language, or ADA for that matter -- but practically speaking, C). This will be true whether he uses PyMedia, PyGame, Numeric or all three. Indeed, as an implementation matter only the glue code will be interpreted in Python -- but the OP will not have to write anything but such glue code. For me, who no longer writes *any* C code, not having to write the C code is a big win. And I think this is the PoV relevant to the OP. Cheers, Terry -- Terry Hancock ([EMAIL PROTECTED]) Anansi Spaceworks http://www.AnansiSpaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
Magnus Lycka [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Today, Python has a syntactic shortcut. If 'a' is an instance of class 'A', a.f(x,y,z) is a shortcut for A.f(a,x,y,z). If you don't use the shortcut, there is no magic at all, just the unusual occurence of a type check in Python! As was once pointed out to me some years ago, when I wrote something similar, a.f() is not just a shortcut for A.f(a) [a.__class__.f(a)]. The latter only looks for f in the class A namespace while the former also looks in superclass namespaces. The 'magical' part of accessing functions via instances is the implementation of dynamic inheritance. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: would it be feasable to write python DJing software
On 2006-02-03, Ivan Voras [EMAIL PROTECTED] wrote: Actually, manipulating and mixing audio samples can be both fast and elegant, in Python, if you use Numeric or a similar library. ... at which point you're actually doing it in C, not pure python... :) If that's the way you want to look at it, there is nothing that can be done in pure python. I think people who say that deliberately misunderstand the point. Python is suitable for some things, not for others. So is C. People who say what? -- Grant Edwards grante Yow! Do you need at any MOUTH-TO-MOUTH visi.comresuscitation? -- http://mail.python.org/mailman/listinfo/python-list
Run Windows shortcut
Assuming the shortcut is in the current directory, how could I launch the shortcut (without waiting for it to finish) ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
On Fri, 3 Feb 2006 15:27:51 -0500, Terry Reedy [EMAIL PROTECTED] wrote: Magnus Lycka [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Today, Python has a syntactic shortcut. If 'a' is an instance of class 'A', a.f(x,y,z) is a shortcut for A.f(a,x,y,z). If you don't use the shortcut, there is no magic at all, just the unusual occurence of a type check in Python! As was once pointed out to me some years ago, when I wrote something similar, a.f() is not just a shortcut for A.f(a) [a.__class__.f(a)]. The latter only looks for f in the class A namespace while the former also looks in superclass namespaces. The 'magical' part of accessing functions via instances is the implementation of dynamic inheritance. I'm not sure I follow. Surely you're not suggesting that this doesn't work: class X: ... def foo(self): ... print 'X.foo', self ... class A(X): ... pass ... o = A() A.foo(o) X.foo __main__.A instance at 0xb7cab64c But I can't think what else you might mean. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list