Can local function access local variables in main program?
I am confused by the following program: def f(): print x x=12345 f() result is: 12345 however: def f(): print x x=0 x=12345 f() result is: Traceback (most recent call last): File ...\test.py, line 5, in ? f() File ...\test.py, line 2, in f print x UnboundLocalError: local variable 'x' referenced before assignment I am using Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 I also tested it on python 2.5, which gives the same result. -- http://mail.python.org/mailman/listinfo/python-list
Re: count increment...
Beema shafreen wrote: 8 --- file my script: #!/usr/bin/env python fh = open('complete_span','r') line = fh.readline().split('#') old_probe = line[0].strip() old_value = line[1].strip() print old_probe, old_value count = 1 Better to start the count off as zero line = while line: This will do nothing, because line has nothing. start with: line = First rubbish thing to get the while loop going or even better, see below line = fh.readline().strip() if line : round about here, you should maybe increment the count. something like : count += 1 anywhere under this true branch of the 'if line' Do you realise that this whole if line can be avoided, as the while loop will look after it if you read the first line outside the loop at the start, and read the next line at the end of the while, before looping back? It is a redundant check. current_probe, current_value = line.split('#')[0:2] probe =current_probe.strip() value = current_value.strip() if int(old_value) int(value): res_value='%s\t%s'%(old_value, old_probe) print res_value Then you have a fighting chance that the following may work, if you have enough lines in your file. if count = 244000: break old_probe,old_value =probe, value fh.close() HTH - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Can local function access local variables in main program?
On Sat, 03 Nov 2007 07:18:17 +, Sullivan WxPyQtKinter wrote: def f(): print x x=0 x=12345 f() result is: Traceback (most recent call last): File ...\test.py, line 5, in ? f() File ...\test.py, line 2, in f print x UnboundLocalError: local variable 'x' referenced before assignment When Python compiles your function f(), it sees that you have assigned to x, and that there is no line global x, so it knows that x is a local variable. But when you call f(), you try to print x before the local x has a value assigned to it. Hence the (accurate but hardly user-friendly) error message. You can also do this: help(UnboundLocalError) Help on class UnboundLocalError in module exceptions: class UnboundLocalError(NameError) | Local name referenced but not bound to a value. As far as I know, there is no way to read the value of global x if and only if local x doesn't exist. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Can local function access local variables in main program?
On Sat, 03 Nov 2007 07:18:17 +, Sullivan WxPyQtKinter wrote: I am confused by the following program: def f(): print x x=12345 f() result is: 12345 If python can't discover x in your current scope and you do not bind to it there, it will automatically access that global name x. however: def f(): print x x=0 x=12345 f() result is: Traceback (most recent call last): File ...\test.py, line 5, in ? f() File ...\test.py, line 2, in f print x UnboundLocalError: local variable 'x' referenced before assignment Here, you *do* assign to x in this scope so this is essentially the same as the following (without any function scope):: print x x = 12345 This can't work since you haven't used x when you try to print it. You can make this work using the `global` statement:: def foo(): ... global x ... print x ... x = 0 ... x = 12345 print x 12345 foo() 12345 print x 0 See more in the `lexical reference about the global statement http:// docs.python.org/ref/global.html. HTH, Stargaming -- http://mail.python.org/mailman/listinfo/python-list
Re: python newbie
On Sat, 03 Nov 2007 08:36:24 +0200, Hendrik van Rooyen wrote: Bruno Desthuilliers wrote: functions are *not* methods of their module. Now I am confused - if I write: result = foo.bar(param) Then if foo is a class, we probably all agree that bar is a method of foo. There are funny edge cases (e.g. bar might be an attribute with a __call__ method) but in general, yes, bar would be a method of foo. But the same syntax would work if I had imported some module as foo. Same syntax, different semantics. Just like: wholemeal bread sandwich and cloudy apple juice have the same syntax but very different meanings: in the first one, the adjective wholemeal refers to the bread, not the entire sandwich, but in the second cloudy refers to the juice and not the apple. So what's the difference ? Why can't bar be called a method of foo, or is it merely a convention that classes have methods and modules have functions? It is more than merely a convention. In Python, functions and methods are different things. They are very similar, but under the hood they are different: def function(): ... pass ... class Parrot(object): ... def method(self): ... pass ... type(function) type 'function' type(Parrot.method) type 'instancemethod' You might also like to call dir() on a function and a method and see how they differ. Methods are, in fact, lightweight wrappers around functions, and the underlying function can be found in the im_func attribute of the method. Note that I am purposely refraining from mentioning a module that has a class that has a method. But that isn't a problem. That is merely a module's class' method. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to pass a function name and its arguments inside the arguments of other function?
On Sat, 03 Nov 2007 02:21:30 +, jmborr wrote: I need something like this: 1: superfoo( non-keyword-args, keyword-args, methodname, *kargs, *kwargs): 2: non-keyword-args and keyword-args are arguments that 3: apply to superfoo, while *kargs and **kwargs are arguments 4: that apply to methodname. See below 5: object=someClass() 6: result=getattr(object,methodname)(*kargs,**kwargs) 7: return result The problem is: how can I pass both arguments for superfoo and methodname in line 1: ? Is it possible? -Jose I don't really understand the problem (could you give some (fictional) working sample how you plan to use this and leave out the line numbers for better readability?) but perhaps using traditional tuples and dicts instead of */** unpacking would be enough? Like:: superfoo(fooargs=(1,2,3), fookwargs={'foo': 'bar}, objargs=('a', 'b'), objkwargs={'x': 5}) Cheers, Stargaming -- http://mail.python.org/mailman/listinfo/python-list
Re: Is pyparsing really a recursive descent parser?
On Nov 3, 6:33 am, Just Another Victim of the Ambient Morality [EMAIL PROTECTED] wrote: Paul McGuire [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Nov 2, 5:47 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: Pyparsing is no recursive descent parser. It doesn't go back in the input stream. The ``OneOrMore(Word(alphas))`` part eats the 'end' and when it can't get more, the parser moves to the ``Literal('end')`` part which fails because the 'end' is already gone. Is there a way to get pyparsing to parse a grammar like this? Negative lookahead maybe: grammar = (OneOrMore(NotAny(Literal('end')) + Word(alphas)) + Literal('end')) Ciao, Marc 'BlackJack' Rintsch- Hide quoted text - - Show quoted text - Well I'll be darned! All this time, I thought recursive descent described the recursive behavior of the parser, which pyparsing definitely has. I never knew that backing up in the face of parse mismatches was a required part of the picture. It has recursion in it but that's not sufficient to call it a recursive descent parser any more than having a recursive implementation of the factorial function. The important part is what it recurses through... In pyparsing, each construction gets composed from more fine-grained constructions, and they are called recursively to match or not match against the input string. For example, taking your working parser example: grammar = (OneOrMore(NotAny(Literal('end')) + Word(alphas)) + Literal('end')) This creates the following data structure: - And - OneOrMore - And - NotAny - Literal('end') - Word(alphas) - Literal('end') Every instance in this structure derives from the base class ParserElement, which defines a method parse(). parse() in turn calls preParse(), parseImpl(), and postParse(). If parseImpl succeeds, it returns a ParseResults object and the next location within the input string to continue parsing. The parseImpl methods are most often overridden in the subclasses (a few override postParse as well), such as: - And.parseImpl invokes parse() (note the recursion) on each of the expressions in its list. All must succeed or And.parseImpl throws an exception. - OneOrMore.parseImpl invokes parse() on its contained expression, which must succeed at least once; if not, the exception is rethrown. If the contained expression succeeds once, then its parse() method is called again and again until it fails, but no exceptions are rethrown, since only one match was actually required. - NotAny inverts the success/failure of its contained expression. If the expression's parse() method succeeds, NotAny.parseImpl throws an exception. If the contained expression's parse() method throws an exception, NotAny returns successfully. (NotAny does not advance the parse location, nor does it return any tokens.) - Literal and Word are terminals, in that they do not invoke any other expression's parse() method. Literal.parseImpl tests whether its string exists at the current parse location, and throws an exception if it doesn't. Word.parseImpl tests whether the current parse location contains a letter in the Word instance's set of valid initial characters - if so success; if not, throws an exception. It then advances through the input string, matching characters in the Word instance's set of valid body characters. The entire matched string is then returned, along with an updated string index at which to continue parsing. Thank you for the detailed description of pyparsing's implementation. In my concept of recursive descent parsing, I was under the impression that pyparsing's use of this data structure, and *recursive* calls of parse() as it *descends* through the data structure, constituted a recursive descent parser. What the OP requested was a more regular expression-ish matcher, with backup (or backtracking). In my concept of recursive descent parsing, I was under the impression that one should recurse through all rule combinations to ensure that the grammar is fully applied. As I have mentioned before, merely having recursion in your algorithm is insufficient. What you recurse through is key. pyparsing recurses through rules but what's important is to recurse through rule combinations. I think the confusing aspect of pyparsing for someone like me coming from an (E)BNF and formal language background is that scanning and parsing are merged into one. pyparsing is scannerless and where a tokenizer such as Pythons performs a longest match tokenization but interprets CFGs correctly ( in the bounds of the parsers power ) one has to disambiguate grammars in pyparsing where you expect a CFG to be established. Note that I don't like pyparsings approach and it is clearly not for everyone. I rather tend to make the experience that
Re: IDLE
On Nov 3, 12:44 am, Russ P. [EMAIL PROTECTED] wrote: I've been programming in python for a few years using XEmacs on Solaris and Linux. I've been thinking about trying IDLE for a long time, but either it wasn't available on my system or I procrastinated. I finally have it available, and I gave it a try. I immediately encountered a basic problem for which I could not find a solution in the intro docs. I want to run a script in one directory that reads input from a file in another directory. Maybe I'm just not very smart, but I couldn't figure out how to do it. Will someone please give me a clue? More generally, I don't see much discussion of IDLE on this newsgroup. Are many python programmers using it? I see that some of the intro and tutorial docs have not been updated for several years. Is IDLE still actively supported? Or would I be better off just going directly to a commercially supported IDE such as Wing? Thanks. On Nov 3, 12:44 am, Russ P. [EMAIL PROTECTED] wrote: I've been programming in python for a few years using XEmacs on Solaris and Linux. I've been thinking about trying IDLE for a long time, but either it wasn't available on my system or I procrastinated. I finally have it available, and I gave it a try. I immediately encountered a basic problem for which I could not find a solution in the intro docs. I want to run a script in one directory that reads input from a file in another directory. Maybe I'm just not very smart, but I couldn't figure out how to do it. Will someone please give me a clue? More generally, I don't see much discussion of IDLE on this newsgroup. Are many python programmers using it? I see that some of the intro and tutorial docs have not been updated for several years. Is IDLE still actively supported? Or would I be better off just going directly to a commercially supported IDE such as Wing? Thanks. Hi Russ, IDLE is still actively supported on the groups and mailing lists, maintained, and even developed. True, the amount of developer time going into it isn't what it used to be; that's why the tutorial and docs are so outdated. Much of the discussion about it (including some questions) goes on in the idle-dev _at_ python.org mailing list. Which IDE to use is mostly a matter of personal preference. I like IDLE very much because it is clean and uncluttered, but AFAIK most Python developers move on to more feature-rich IDEs. Even if you don't end up using it in the long term, IDLE is really awesome for learning Python (though perhaps you are beyond that stage?). It is admittedly not as powerful an editor as some other IDEs out there, or on the other end of the map, it isn't nearly as powerful as Emacs/Vi. But even if you don't use it for editing, it is IMO the best Python shell out there. As for your question, I couldn't quite understand what you're trying to do. In general, you can have the script use os.chdir() to go to the relevant directory and then open() the file, or you can use open() directly with a relative/full path to it. (This question isn't IDLE specific in any way, unless I misunderstood...) (If you're trying to run a script and pipe input to it via stdin, IDLE doesn't support that - I don't know of any Python shell that does.) - Tal reduce(lambda m,x:[m[i]+s[-1] for i,s in enumerate(sorted(m))], [[chr(154-ord(c)) for c in '.-,l.Z95193+179-']]*18)[3] -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE
Just curious: What makes you wish to move from emacs to idle? Admission: I used to be a dyed-in-the-wool emacs guy but Ive been having trouble with it lately. eg Yesterday when editing a largish file (I think it was setup.py) it kept going to sleep and when I killed emacs it said LALR parsing. and made me wait for nearly a minute! So just wondering what trouble others are having with emacs and python. -- http://mail.python.org/mailman/listinfo/python-list
Re: (MAC) CoreGraphics module???
On Fri, 02 Nov 2007 14:09:25 -0500, Robert Kern [EMAIL PROTECTED] wrote: David C. Ullrich wrote: [...] So CoreGraphics is a builtin in Apple-Python, explaining why I didn't find the relevant CoreGraphics.py anywhere on the hard drive, eh? Okay, which version of OS X do you have? In 10.3 and 10.4 it used to be here: /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-mac/CoreGraphics.py I'm using 10.4. Yesterday I checked that there is indeed a /System/Library/Frameworks/Python.framework but I didn't look any deeper because I already knew that CoreGraphics.py wasn't there. Come to think of it, it could well be that it's there and I didn't find it because Spotlight didn't want to show me things inside /System? I'll check. (I'll check soon - again, I'm at home and the Mac's at the office.) I notice that in 10.5, it no longer exists, though. [How do I get to the Python I want?] Python-Python installed a couple of symlinks into /usr/local/bin and then put /usr/local/bin in the front of your $PATH environment variable so it gets picked up first on the terminal. For my Python-Python 2.5, I have python python2.5 pythonw pythonw2.5 python-config python2.5-config Remove these and then when you type python at the terminal, you will get /usr/bin/python, which points to the Apple-Python. Thanks. Right this second I have no idea _where_ I should go to remove that, but I can probably find out. It's in .bashrc or somewhere, I bet, No, don't tell me... OR: Is there something special I could do with CoreGraphics scripts and/or how I invoke them so that _they_ would use the Apple-Python while other scripts would just use the Python-Python as now? For scripts executed from the terminal, you could start them with a hash-bang line: #!/usr/bin/python Use chmod u+x on the script, and then you can execute it like any other program from the terminal. Curiously, I did make one of the sample scripts executable and it still didn't work. I _think_ the hash-bang at the start was usr/bin/python (I did verify yesterday that /usr/bin/python is pointing to ApplePython.) Again, don't tell me... [ApplicationLauncher mystery] I'm afraid I don't. I don't use ApplicationLauncher. Thanks anyway - this has all been very informatiive. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: (MAC) CoreGraphics module???
On Fri, 2 Nov 2007 13:14:16 +0100, Tommy Nordgren [EMAIL PROTECTED] wrote: On 2 nov 2007, at 02.10, David C. Ullrich wrote: [Why doesn't CoreGraphics work?] -- http://mail.python.org/mailman/listinfo/python-list There are Python wrappers for the Cocoa API. These can be used with binaries from Python.org. The name of the module is PyObjC, and can be downloaded from sourceforge. Ah. I'd read about this in the context of using Python in Xcode applications, which seems like something I definitely want to learn how to do, but it was scheduled for later... PyObjC will also allow a person to access Cocoa things from an ordinary Python script? If so, keen. Thanks. There are binary builds for Python up to version 2.4.1. For Python 2.5.1, it is necessary to build it yourself, which I've found out requires modifying setup.py. (The problem is that setup.py tries to use two modules that's not installed by default on Tiger) -- What is a woman that you forsake her, and the hearth fire and the home acre, to go with the old grey Widow Maker. --Kipling, harp song of the Dane women Tommy Nordgren [EMAIL PROTECTED] David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Can local function access local variables in main program?
Sullivan WxPyQtKinter wrote: UnboundLocalError: local variable 'x' referenced before assignment For your reference: http://groups.google.de/groups?q=group:comp.lang.python+UnboundLocalError Regards, Björn -- BOFH excuse #12: dry joints on cable plug -- http://mail.python.org/mailman/listinfo/python-list
Re: simple question on dictionary usage
On Oct 27, 6:42 am, Karthik Gurusamy [EMAIL PROTECTED] wrote: On Oct 26, 9:29 pm, Frank Stutzman [EMAIL PROTECTED] wrote: My apologies in advance, I'm new to python Say, I have a dictionary that looks like this: record={'BAT': '14.4', 'USD': '24', 'DIF': '45', 'OAT': '16', 'FF': '3.9', 'C3': '343', 'E4': '1157', 'C1': '339', 'E6': '1182', 'RPM': '996', 'C6': '311', 'C5': '300', 'C4': '349', 'CLD': '0', 'E5': '1148', 'C2': '329', 'MAP': '15', 'OIL': '167', 'HP': '19', 'E1': '1137', 'MARK': '', 'E3': '1163', 'TIME': '15:43:54', 'E2': '1169'} From this dictionary I would like to create another dictionary calld 'egt') that has all of the keys that start with the letter 'E'. In otherwords it should look like this: egt = {'E6': '1182','E1': '1137','E4': '1157','E5': '1148', 'E2': '1169','E3': '1163'} This should be pretty easy, but somehow with all my googling I've not found a hint. One possible solution (read list-comprehension if you not familiar with it): record={'BAT': '14.4', 'USD': '24', 'DIF': '45', 'OAT': '16', ... 'FF': '3.9', 'C3': '343', 'E4': '1157', 'C1': '339', ... 'E6': '1182', 'RPM': '996', 'C6': '311', 'C5': '300', ... 'C4': '349', 'CLD': '0', 'E5': '1148', 'C2': '329', ... 'MAP': '15', 'OIL': '167', 'HP': '19', 'E1': '1137', ... 'MARK': '', 'E3': '1163', 'TIME': '15:43:54', ... 'E2': '1169'} egt =dict([(k,record[k]) for k inrecordif k.startswith('E')]) egt {'E5': '1148', 'E4': '1157', 'E6': '1182', 'E1': '1137', 'E3': '1163', 'E2': '1169'} Karthik Thanks in advance -- Frank Stutzman Hallo, a functional and concise way. egt= dict( filter( lambda item: item[0][0] == E , record.iteritems() )) Rainer -- http://mail.python.org/mailman/listinfo/python-list
Re: __file__ vs __FILE__
Jeff McNeil wrote: I've used the 'os.path.realpath(os.path.pardir)' construct in a couple of scripts myself. In Windows? Using Linux, this gives me ... I use os.path.dirname(os.path.abspath(__file__)) That ought to work within the interactive interpreter. Why do you also enter that code in the interpreter? If it is in a module, you should always be able to use __file__. Regards, Björn -- BOFH excuse #238: You did wha... oh _dear_ -- http://mail.python.org/mailman/listinfo/python-list
Re: python newbie
Hendrik van Rooyen wrote: So what's the difference ? Why can't bar be called a method of foo, or is it merely a convention that classes have methods and modules have functions? In depends on which terminology you use. As Steven told, Python methods are special functions. In contrast, the thing that is often generally referred to as method is often just some function of some object. This comes from other languages, I think, where it's not that liberal with functions. Regards, Björn -- BOFH excuse #405: Sysadmins unavailable because they are in a meeting talking about why they are unavailable so much. -- http://mail.python.org/mailman/listinfo/python-list
Re: py2exe (or other exe builder) on Vista system for Vista/XP install targets.
Michael wrote: Björn, what library files end up being in your dist directory for that project? Would you mind posting a copy of the output of dir? Okay, sorry for the delay. Here the output of py2exe is, for directory contents see below. | The following modules appear to be missing | ['FCNTL', 'OpenSSL', 'email.Generator', 'email.Iterators', | 'email.Utils', 'pywintypes', 'resource', 'win32api', 'win32con', | 'win32event', 'win32file', 'win32pipe', 'win32process', | 'win32security', 'wx.Timer'] | | *** binary dependencies *** | Your executable(s) also depend on these dlls which are not | included, you may or may not need to distribute them. | | Make sure you have the license if you distribute any of them, and | make sure you don't distribute files belonging to the operating | system. | | OLEAUT32.dll - C:\windows\system32\OLEAUT32.dll | USER32.dll - C:\windows\system32\USER32.dll | SHELL32.dll - C:\windows\system32\SHELL32.dll | ole32.dll - C:\windows\system32\ole32.dll | comdlg32.dll - C:\windows\system32\comdlg32.dll | WSOCK32.dll - C:\windows\system32\WSOCK32.dll | COMCTL32.dll - C:\windows\system32\COMCTL32.dll | ADVAPI32.dll - C:\windows\system32\ADVAPI32.dll | GDI32.dll - C:\windows\system32\GDI32.dll | WS2_32.dll - C:\windows\system32\WS2_32.dll | MSVCP71.dll - C:\Program Files\Python25\lib\site-packages\ | wx-2.8-msw-unicode\wx\MSVCP71.dll | WINMM.dll - C:\windows\system32\WINMM.dll | KERNEL32.dll - C:\windows\system32\KERNEL32.dll | gdiplus.dll - C:\Program Files\Python25\lib\site-packages\ | wx-2.8-msw-unicode\wx\gdiplus.dll | RPCRT4.dll - C:\windows\system32\RPCRT4.dll Output of dir in the dist directory follows: | 01.11.2007 20:51DIR . | 01.11.2007 20:51DIR .. | 18.04.2007 07:5177.824 bz2.pyd | 01.11.2007 20:51 4.874.503 library.zip | 29.06.2007 20:19 348.160 MSVCR71.dll | 18.04.2007 07:51 135.168 pyexpat.pyd | 18.04.2007 07:51 2.113.536 python25.dll | 18.04.2007 07:51 7.680 select.pyd | 18.04.2007 07:51 475.136 unicodedata.pyd | 18.04.2007 07:51 4.608 w9xpopen.exe | 07.08.2007 20:47 135.168 wxbase28uh_net_vc.dll | 07.08.2007 20:47 1.327.104 wxbase28uh_vc.dll | 07.08.2007 20:50 708.608 wxmsw28uh_adv_vc.dll | 07.08.2007 20:50 3.158.016 wxmsw28uh_core_vc.dll | 07.08.2007 20:51 479.232 wxmsw28uh_html_vc.dll | 07.08.2007 21:12 909.312 _controls_.pyd | 07.08.2007 21:09 950.272 _core_.pyd | 07.08.2007 21:11 716.800 _gdi_.pyd | 18.04.2007 07:52 323.584 _hashlib.pyd | 07.08.2007 21:14 659.456 _misc_.pyd | 18.04.2007 07:5253.248 _socket.pyd | 18.04.2007 07:52 655.360 _ssl.pyd | 07.08.2007 21:11 647.168 _windows_.pyd | 08.01.2007 15:49 9.216 _zope_interface_ | coptimizations.pyd (my files, an exe and a data file, snipped) Regards HTH, Björn -- BOFH excuse #417: Computer room being moved. Our systems are down for the weekend. -- http://mail.python.org/mailman/listinfo/python-list
Re: python newbie
Steven D'Aprano [EMAIL PROTECTED] wrote: Then if foo is a class, we probably all agree that bar is a method of foo. There are funny edge cases (e.g. bar might be an attribute with a __call__ method) but in general, yes, bar would be a method of foo. But that 'funny edge case' is exactly the point here: if foo is a module then bar probably is an attribute with a __call__ method. modules are not special in any way, except that you cannot subclass them. Oops, sorry I got that wrong. Modules are not special in any way, they can have methods as well as functions: import string class MyModule(type(string)): def bar(self, param): print In method bar of %r, param=%r % (self, param) foo = MyModule('foo', 'This is the foo module') exec def baz(param): print Function baz, param=%r % (param,) in foo.__dict__ foo.bar(42) In method bar of module 'foo' (built-in), param=42 foo.baz(42) Function baz, param=42 foo.bar bound method MyModule.bar of module 'foo' (built-in) foo.baz function baz at 0x01160830 help(foo) Help on module foo: NAME foo - This is the foo module FILE (built-in) foo.__file__='foo.py' foo module 'foo' from 'foo.py' sys.modules['foo'] = foo del foo import foo foo.bar('hello') In method bar of module 'foo' from 'foo.py', param='hello' -- http://mail.python.org/mailman/listinfo/python-list
Re: python newbie
Duncan Booth [EMAIL PROTECTED] writes: modules are not special in any way, except that you cannot subclass them. Oops, sorry I got that wrong. Modules are not special in any way, they can have methods as well as functions: I've felt for a long time that you should be able to define __call__ on a module, but that doesn't seem to be allowed, at least if you try it in the obvious way. -- http://mail.python.org/mailman/listinfo/python-list
Re: __file__ vs __FILE__
On 3 Nov, 04:21, klenwell [EMAIL PROTECTED] wrote: I apologize in advance for coming at this from this angle but... In PHP you have the __FILE__ constant which gives you the value of the absolute path of the file you're in (as opposed to the main script file.) With the function dirname, this makes it easy to get the parent dir of a particular file from within that file: $parent_dir = dirname(__FILE__); I'm looking for the best way to accomplish this in Python. This seems to work: parent_dir = os.path.normpath(os.path.join(os.path.abspath(__file__), '..')) Can anyone confirm the reliability of this method or suggest a better (one-line) method for accomplishing this? Thanks, Tom This is not really 'one-line' since you have to import two modules first, but it looks nicer...: import sys, os print sys.argv[0] # absolute file name print os.path.dirname(sys.argv[0]) # absolute dir name -- http://mail.python.org/mailman/listinfo/python-list
Poor python and/or Zope performance on Sparc
Hello everybody, I'm posting this message because I'm quiet frustrated. We just bought a software from a small software vendor. In the beginning he hosted our application on a small server at his office. I think it was a Fujitsu-Siemens x86 running debian Linux. The performance of the DSL-Line was very poor, so we decided to buy an own machine to host the application ourselves. The application is based on the Zope Application server (2.8.8-final w/ python 2.3.6) along with many other packages like ghostview, postgres, freetype, python imaging lib, etc... I once saw the application running at the office of my software vendor and it was running very well. So I thought that - when the bottleneck of poor DSL performance has disappeared - the software will run as fast as at his office. But I erred. The performance is more than poor. We have a Sun T1000 with 8 cores and 8 GB of RAM. First, I installed Solaris 10 because I know this OS better than Debian Linux. Result: poor Performance. After that I decided to migrate to debian: [EMAIL PROTECTED] uname -a Linux carmanager 2.6.18-5-sparc64-smp #1 SMP Wed Oct 3 04:16:38 UTC 2007 sparc64 GNU/Linux Result: Almost even worse. The application is not scaling at all. Every time you start a request it is hanging around on one cpu and is devouring it at about 90-100% load. The other 31 CPUs which are shown in mpstat are bored at 0% load. If anybody needs further information about installed packages, I'll post it here. Any hints are appreciated! Thanks, Joe. PS: Fortunately the Sun is not bought yet. It's a trybuy from my local dealer. So if there are any hints like buy a new machine because Sun is crap I will _not_ refuse obediance. -- http://mail.python.org/mailman/listinfo/python-list
Python launcher not working on Mac after Leopard upgrade?
I just installed Leopard on my Mac. I already was using Python 2.5. I can run a Python script from a terminal window by typing python script.py as one would expect ... but not using the Python launcher either directly or indirectly (by double clicking on a Python icon). Has anyone else observed this and, more importantly, found a fix for this problem? André -- http://mail.python.org/mailman/listinfo/python-list
Python IDE
Hi, I have recently moved from Windows XP to Ubuntu Gutsy. I need a Python IDE and debugger, but have yet to find one as good as Pyscripter for Windows. Can anyone recommend anything? What are you all using? Coming from a Visual Studio background, editing text files and using the terminal to execute them offends my sensibilities :) Thanks Si -- http://mail.python.org/mailman/listinfo/python-list
Re: python newbie
En Sat, 03 Nov 2007 09:55:38 -0300, Paul Rubin http://phr.cx@NOSPAM.invalid escribió: Duncan Booth [EMAIL PROTECTED] writes: modules are not special in any way, except that you cannot subclass them. Oops, sorry I got that wrong. Modules are not special in any way, they can have methods as well as functions: I've felt for a long time that you should be able to define __call__ on a module, but that doesn't seem to be allowed, at least if you try it in the obvious way. Notice that you usually define __call__ for a *type*, not for specific object instances. All special methods, like __call__, are searched on the type - not on the instance. And all modules are instances of the same type. For something like that to work, each module should be a *subclass* of moduletype, not an instance. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: __file__ vs __FILE__
En Sat, 03 Nov 2007 10:07:10 -0300, Giampaolo Rodola' [EMAIL PROTECTED] escribió: On 3 Nov, 04:21, klenwell [EMAIL PROTECTED] wrote: In PHP you have the __FILE__ constant which gives you the value of the absolute path of the file you're in (as opposed to the main script file.) This is not really 'one-line' since you have to import two modules first, but it looks nicer...: import sys, os print sys.argv[0] # absolute file name print os.path.dirname(sys.argv[0]) # absolute dir name Note that this returns the location of the *main* script, not the current module, as the OP explicitely asked for. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: difference between IDLE and command line
Jim Hendricks wrote: I have been editing my code in UltraEdit then testing in IDLE by choosing open, then F5. I didn't see an easy way to refresh in IDLE, so each edit I've been closing the file (not IDLE itself), then opening again. Since IDLE does not keep track of what directory I last opened from, this gets tedious, so I decided to run my code from the command line. Tip: IDLE has a recent files list, under the File menu. Use Alt-f Alt- r to access it quickly. Tip #2: You can run a script in IDLE from the command line: IDLE -r script file. This will open an IDLE shell, run the script in it, and afterwards become interactive. Very useful for debugging etc. - Tal reduce(lambda m,x:[m[i]+s[-1] for i,s in enumerate(sorted(m))], [[chr(154-ord(c)) for c in '.-,l.Z95193+179-']]*18)[3] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python IDE
Simon Pickles wrote: Hi, I have recently moved from Windows XP to Ubuntu Gutsy. I need a Python IDE and debugger, but have yet to find one as good as Pyscripter for Windows. Can anyone recommend anything? What are you all using? I use Eric. Works very well for me. http://www.die-offenbachs.de/eric/index.html Morten -- http://mail.python.org/mailman/listinfo/python-list
Re: __file__ vs __FILE__
I'm using Mac OS X, and it get: Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type help, copyright, credits or license for more information. import os os.getcwd() '/Users/jeff' os.path.realpath(os.path.pardir) '/Users' The __file__ construct is fine from within a module and is probably more inline with what the OP was looking for anyways. On Nov 3, 2007, at 7:18 AM, Bjoern Schliessmann wrote: Jeff McNeil wrote: I've used the 'os.path.realpath(os.path.pardir)' construct in a couple of scripts myself. In Windows? Using Linux, this gives me ... I use os.path.dirname(os.path.abspath(__file__)) That ought to work within the interactive interpreter. Why do you also enter that code in the interpreter? If it is in a module, you should always be able to use __file__. Regards, Björn -- BOFH excuse #238: You did wha... oh _dear_ -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python IDE
On Nov 3, 9:11 am, Simon Pickles [EMAIL PROTECTED] wrote: I need a Python IDE and debugger . . . I use vim on both Windows XP and Debian, but I used to use Komodo for big projects. Try the free trial of Komodo http://www.activestate.com/Products/komodo_ide/ It has what you want, and it comes with licenses for both Windows and Linux. rd -- http://mail.python.org/mailman/listinfo/python-list
Re: Is pyparsing really a recursive descent parser?
On Nov 3, 12:33 am, Just Another Victim of the Ambient Morality [EMAIL PROTECTED] wrote: It has recursion in it but that's not sufficient to call it a recursive descent parser any more than having a recursive implementation of the factorial function. The important part is what it recurses through... snip In my opinion, the rule set I mentioned in my original post: grammar = OneOrMore(Word(alphas)) + Literal('end') ...should be translated (internally) to something like this: word = Word(alphas) grammar = Forward() grammar ((word + grammar) | (word + Literal(end))) This allows a recursive search to find the string correct without any need for backtracking, if I understand what you mean by that. Couldn't pyparsing have done something like this? Dear JAVotAM - This was a great post! (Although I'm not sure the comment in the first paragraph was entirely fair - I know the difference between recursive string parsing and recursive multiplication.) You really got me thinking more about how this recursion actually behaves, especially with respect to elements such as OneOrMore. Your original question is really quite common, and up until now, my stock answer has been to use negative lookahead. The expression you posted is the first time I've seen this solution, and it *does* work. I was all set to write a cocky response on why your expression wouldn't work. I've seen it many times before, where people (usually coming from EBNF experience) implement listOfXs = OneOrMore(x) as: listOfXs = Forward() listOfXs ( x + listOfXs | x ) Actually, what they usually write is: listOfXs ( listOfXs + x ) but this sends pyparsing into a recursive tailspin. So I fired up SciTE and copy/pasted your code into the editor and ran it, and it worked just fine - this was a shock! I studied this for a few minutes, and then realized what was happening. First of all, I misread what you posted. You posted this: grammar ((word + grammar) | (word + Literal(end))) which works. I *thought* you posted this: grammar ((word + grammar) | word) + Literal(end) which doesn't work. In fact this behaves the same as your original post, except it iterates over the input string's words recursively, vs. repetition ins a for-loop, as is done by OneOrMore. So going back to your working version, I had to see why it works. Initially, the first term in the MatchFirst (the '|' operator creates MatchFirst instances) is just the same, and by grammar referencing itself, it just goes word by word through the input trying to find a match. I'll try to visualize the steps: levelFirst Second Third end 1 word grammar 2 word grammar 3 word grammar 4word grammar - fails! 4word end - fails! (therefore level 3 grammar fails!) 3 word end-- success!!! grammar has 2 options: to match a word followed by a grammar, or to match a word followed by 'end'. At 4 levels deep into the Forward's recursion, the first option fails, because after parsing end as the initial word, there is no more text to try to match against grammar. Level 4's Forward then also tries to match a word followed by 'end', but this fails for the same reason. So at this point, the 4th level Forward fails to match either of its options, so it throws its exception back up to level 3, indicating that the first alternative, word followed by grammar, failed. Level 3 then moves on to see if word followed by the literal 'end' matches, and it does - success! Here's where I am stuck now. In the original grammar that you posted, which you want to render into this behavior, grammar is defined as: grammar = OneOrMore(Word(alphas)) + Literal('end') Unfortunately, when the OneOrMore gets constructed, it does not have any visibility beyond knowing what is to be repeated. Again, here is the data structure that is being built: - And - OneOrMore - Word(alphas) - Literal('end') Only at the level of the And is there any awareness that the OneOrMore is followed by anything, let alone by something which could be misinterpreted as something matching the OneOrMore's repetition expression. Can you suggest a way I could generalize this, so that OneOrMore stops matching before it gets to 'end'? -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: python newbie
Paul Rubin http://[EMAIL PROTECTED] wrote: Duncan Booth [EMAIL PROTECTED] writes: modules are not special in any way, except that you cannot subclass them. Oops, sorry I got that wrong. Modules are not special in any way, they can have methods as well as functions: I've felt for a long time that you should be able to define __call__ on a module, but that doesn't seem to be allowed, at least if you try it in the obvious way. This isn't perfect (global variables have to be set before hooking the module) but it sort of works: - callable.py --- How to define a callable module import sys, new class CallableModule(new.module): def __call__(self, *args, **kw): self._call_(*args, **kw) def _call_(*args, **kw): A call method print Called with %r args, %r kw % (args, kw) self = CallableModule(__name__, __doc__) self.__dict__.update(sys.modules[__name__].__dict__) sys.modules[__name__] = self -- import callable callable('test') Called with ('test',) args, {} kw callable module 'callable' from 'callable.py' -- http://mail.python.org/mailman/listinfo/python-list
Re: MP3 and ID3 library/module recommendations
I use PyMedia and mutagen. I've found PyMedia to be excellent for creating custom mp3 files from line input and performing frequency/energy analysis. I can't say that I've tried to convert other audio formats to MP3 with it, but I'm sure it's possible. I was able to get a working binary of v1.3.7.3 for win32 and python 2.5 directly from the author, since I have no way to compile it from the source that's posted on the project website. If you need it, let me know. On the other hand, mutagen is a good lightweight utility for extracting and modifying all kinds of audio metadata. On mp3's, that includes track duration, all ID3 info, bitrate, sample rate, etc. It provides an easy dictionary-like interface. It supports a number of audio formats, but I don't believe it has conversion capability. Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Poor python and/or Zope performance on Sparc
On Nov 3, 9:35 am, joa2212 [EMAIL PROTECTED] wrote: Result: Almost even worse. The application is not scaling at all. Every time you start a request it is hanging around on one cpu and is devouring it at about 90-100% load. The other 31 CPUs which are shown in mpstat are bored at 0% load. You are probably not aware of Python's Global Interpeter Lock: http://docs.python.org/api/threads.html. George -- http://mail.python.org/mailman/listinfo/python-list
Re: Copy database with python..
On Nov 2, 2007, at 11:49 AM, Diez B. Roggisch wrote: Abandoned wrote: On Nov 2, 4:19 pm, Paul McNett [EMAIL PROTECTED] wrote: Abandoned wrote: Hi. I want to copy my database but python give me error when i use this command. cursor.execute(pg_dump mydata old.dump) What is the problem ? And how can i copy the database with python ? You are just going to have to give us more to go on. Please post the entire traceback of the error that you see (copy/paste it from your terminal). You can't issue system commands using the cursor's execute() method and expect that to work. execute() is for executing SQL, DML, or DDL, not for doing shell stuff. Try: import os os.system(pg_dump mydata /tmp/old.dump) but I'm not versed in postgressql, so this probably won't work exactly as written. You'd need to run that code from the server hosting the postgresql database. Not true, you can run the dump from any server that can connect to the database server (based on network connectivity and the connection permissions in your pg_hba.conf file). Just be sure to use the -h (host) -p (port) and -U (username) flags when execute pg_dump. Note: The database's size is 200 GB Well, then you may want to make sure you have enough room on the target volume before trying to dump the file! Note that the dump file could conceivably be much larger (or much smaller) than the database itself. If you use the -F c (pg_dump -F -c -f your_dmp.file your_db) option you'll get a compressed dump file which can be as little as 10% (or less) the size of your database. -- pkm ~http://paulmcnett.com Are there any way to copy database without dump or any temp files ? (If there is a temp my harddisk not enough for this operation :( ) If you can stop the database then you can just do a manual copy (using cp, rsync, or whatever) of the entire pg data directory but that will require the same amount of space as the original database. If you're goal is to make a backup, pg_dump is the way to go. Make note, though, pg_dump will only dump one database so if you have more than one database in your postgres cluster then you'll need to use pg_dumpall in which case you don't have the compression (-F c) option. There are other caveats between the two as well. Just be sure to read the documentation. Also, for other postgres questions, you should join one of the postgres mailing lists. Erik Jones Software Developer | Emma® [EMAIL PROTECTED] 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate market in style. Visit us online at http://www.myemma.com -- http://mail.python.org/mailman/listinfo/python-list
jigsae puzzle issue
Hey i am trying to build a puzzle (jigsaw) game. I have most of the code for it written in python. But having an issue with one part. What i want is to give the player the ability to import there own picture and create a jigsaw from the picture with there own designation of the piece size and shape. I am having difficulty with one part of how to let them create the piece and then give it the ability to link the pieces together so the user knows that they have the right two pieces placed together. I want to try and make this a free standing picture that later can have things integrated into it with out much difficulty. -- http://mail.python.org/mailman/listinfo/python-list
Re: Poor python and/or Zope performance on Sparc
On 3 Nov., 17:19, George Sakkis [EMAIL PROTECTED] wrote: On Nov 3, 9:35 am, joa2212 [EMAIL PROTECTED] wrote: Result: Almost even worse. The application is not scaling at all. Every time you start a request it is hanging around on one cpu and is devouring it at about 90-100% load. The other 31 CPUs which are shown in mpstat are bored at 0% load. You are probably not aware of Python's Global Interpeter Lock:http://docs.python.org/api/threads.html. George Hi George, yes, that's right. I wasn't aware of this. If I understand you correctly then we have a problem of implementing threads in the software we are using. But tell me one thing: Why does this software almost runs like a fool on an Intel machine with a single cpu (perhaps dual core?) and slow like a snail when it runs on Sparc? It's exactly the same source code on both platforms. Certainly all relevant packages (python + zope) were recompiled on the sparc. Sorry for my questions, I'm really no software developer. I'm just a little bit helpless because my software vendor can't tell my anything about by concerns. Joe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Poor python and/or Zope performance on Sparc
On Sat, 03 Nov 2007 10:06:12 -0700, joa2212 [EMAIL PROTECTED] wrote: On 3 Nov., 17:19, George Sakkis [EMAIL PROTECTED] wrote: On Nov 3, 9:35 am, joa2212 [EMAIL PROTECTED] wrote: Result: Almost even worse. The application is not scaling at all. Every time you start a request it is hanging around on one cpu and is devouring it at about 90-100% load. The other 31 CPUs which are shown in mpstat are bored at 0% load. You are probably not aware of Python's Global Interpeter Lock:http://docs.python.org/api/threads.html. George Hi George, yes, that's right. I wasn't aware of this. If I understand you correctly then we have a problem of implementing threads in the software we are using. But tell me one thing: Why does this software almost runs like a fool on an Intel machine with a single cpu (perhaps dual core?) and slow like a snail when it runs on Sparc? It's exactly the same source code on both platforms. Certainly all relevant packages (python + zope) were recompiled on the sparc. Sorry for my questions, I'm really no software developer. I'm just a little bit helpless because my software vendor can't tell my anything about by concerns. The Sun machine you have has divided its hardware resources into 32 units. That means that, roughly, each unit is only 1/32nd as fast as the overall system. All of the units together are, roughly, about the speed of the Intel machine you were using before, so one unit alone is 32 times slower. Since Zope is only using 1 unit, it runs 32 times slower, and 31 out of 32 hardware units sit idle. The T1000 isn't a very good machine for general server purposes. It has advantages when running software with a lot of hardware-level parallelism, but Zope isn't such a piece of software. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Can local function access local variables in main program?
Actually I am quite satisfied with and error, which is my expectation. But the implicit global variable access seems quite uncomfortable to me. Why is that necessary? On Nov 3, 3:39 am, Stargaming [EMAIL PROTECTED] wrote: On Sat, 03 Nov 2007 07:18:17 +, Sullivan WxPyQtKinter wrote: I am confused by the following program: def f(): print x x=12345 f() result is: 12345 If python can't discover x in your current scope and you do not bind to it there, it will automatically access that global name x. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python IDE
Simon Pickles wrote: Hi, I have recently moved from Windows XP to Ubuntu Gutsy. I need a Python IDE and debugger, but have yet to find one as good as Pyscripter for Windows. Can anyone recommend anything? What are you all using? Coming from a Visual Studio background, editing text files and using the terminal to execute them offends my sensibilities :) Thanks Si Wingware IDE 101, Ubuntu package at http://wingware.com/downloads. I love it; great for teaching/learning, built-in shell, run programs from within the environment. -- Posted via a free Usenet account from http://www.teranews.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Poor python and/or Zope performance on Sparc
Jean-Paul Calderone [EMAIL PROTECTED] wrote: The T1000 isn't a very good machine for general server purposes. It has advantages when running software with a lot of hardware-level parallelism, but Zope isn't such a piece of software. Zope can scale well on multi-processor machines, but you have to configure it correctly. You need to run multiple instances of Zope all talking to a common Zeo backend. In this case you could try running up to 32 single-threaded zope instances, although you'll need to watch the memory consumption so depending on the application you might not get away with that many. -- http://mail.python.org/mailman/listinfo/python-list
how easily can glob.glob say Unix bash `echo *`
http://wiki.python.org/moin/glob now mentions: The glob module lists names in folders that match Unix shell patterns. If the elemental function emulating Unix bash `echo *` really is missing from the 2.5 Python batteries included, then here's a brief clear way of adding that function to Python. Mind you, to date I've never written an elemental function for Python that I haven't eventually found well-buried somewhere, e.g., os.urandom. P.S. glob.glob bash and glob.glob rm have no hits yet, said Google Groups. -- http://mail.python.org/mailman/listinfo/python-list
opinion - file.readlines blemish
I was just reading about the new file.newlines method that was added per PEP 278. I suspect Guido must have been looking in some other direction when this got added, because it seems unlikely to me that he would have let this get by... Okay, maybe I'm being a little harsh :-) Sorry, I'm picky about this kind of thing. The again, maybe I'm just missing some key point. file.newlines *newlines* If Python was built with the *---with-universal-newlines* option to *configure* (the default) this read-only attribute exists, and for files opened in universal newline read mode it keeps track of the types of newlines encountered while reading the file. The values it can take are |'\r'|, |'\n'|, |'\r\n'|, *None* http://effbot.org/pyref/None.htm (unknown, no newlines read yet) or a tuple containing all the newline types seen, to indicate that multiple newline conventions were encountered. For files not opened in universal newline read mode the value of this attribute will be *None* http://effbot.org/pyref/None.htm. It seems immediately obvious to me that the return value should always be a tuple, consisting of zero or more strings. If built with universal newlines, it should return ('\n',) if a newline was found. Perhaps there was some blurry contemplation that the None return value could identify that *universal-newlines* is enabled, but this is blurry because None could also just mean that no newlines have been read. Besides, it's not a good idea to stuff extra semantics like that. Better would be a separate way to identify *universal-newlines *mode. Ken Seehart -- http://mail.python.org/mailman/listinfo/python-list
Re: Bizarre additional calling overhead.
On Sat, 2007-11-03 at 01:08 -0300, Gabriel Genellina wrote: En Fri, 02 Nov 2007 21:07:19 -0300, Matimus [EMAIL PROTECTED] escribió: On Nov 2, 3:08 pm, Chris Mellon [EMAIL PROTECTED] wrote: def test_func(): ... pass ... import new test_func2 = new.function(test_func.func_code, {}, test_func2) test_func2 function test_func2 at 0x01B8C2F0 test_func function test_func at 0x01B8C270 import timeit tf = timeit.Timer(test_func(), from __main__ import test_func) tf.repeat() [0.2183461704377247, 0.18068215314489791, 0.17978585841498085] tf2 = timeit.Timer(test_func2(), from __main__ import test_func2) tf2.repeat() [0.40015390239890891, 0.35893452879396648, 0.36034628133737456] Why almost twice the calling overhead for a dynamic function? So, I don't have an official explanation for why it takes twice as long, but the only difference between the two functions I could find was that test_func.func_globals was set to globals() and test_func2.func_globals was an empty dict. When I re-created test_func2 with globals set to globals() it ran just as fast as test_func. Yes - and that's a very important difference. Not because it's empty, nor because it's not the same as globals(), but because the builtins as seen by the function are not from the original __builtin__ module. From the Python Reference Manual, section 4.1: The built-in namespace associated with the execution of a code block is actually found by looking up the name __builtins__ in its global namespace; [...] __builtins__ can be set to a user-created dictionary to create a weak form of restricted execution. From the Library Reference, section 28, Restricted Execution: The Python run-time determines whether a particular code block is executing in restricted execution mode based on the identity of the __builtins__ object in its global variables: if this is (the dictionary of) the standard __builtin__ module, the code is deemed to be unrestricted, else it is deemed to be restricted. Section 3.2, when describing frame objects: f_restricted is a flag indicating whether the function is executing in restricted execution mode Let's try to see if this is the case. Getting the f_restricted flag is a bit hard with an empty globals(), so let's pass sys as an argument: py def test_func(sys): ... print restricted, sys._getframe().f_restricted ... py import sys, new py test_func2 = new.function(test_func.func_code, {}, test_fun c2) py test_func(sys) restricted False py test_func2(sys) restricted True So test_func2 is running in restricted mode. That't the reason it is so slow. Even if the restricted mode implementation is now considered unsafe -because new style classes provide many holes to escape from the jail- the checks are still being done. Ok, now let's try to avoid entering restricted mode: py import __builtin__ py test_func3 = new.function(test_func.func_code, {'__builtins_ _':__builtin__}, test_func3) py test_func3(sys) restricted False And now, repeating the timings when __builtins__ is correctly set to the builtin module __builtin__ (!), shows no difference with the original function. So this was the cause of the slow down. The rule is: unless you *actually* want to execute code in restricted mode, pass globals() when building a new function object, or at least, set '__builtins__' to the __builtin__ module Thanks for the very informative and detailed information. After posting I, like the other responders, figured out that it was related to the empty globals dict but I had no idea how that could be happening. -- http://mail.python.org/mailman/listinfo/python-list
Re: Retrieving all open applications ...
applications ... i need to retrieve all currently open applications ... thx for your help ... -Ajay On 10/31/07, Gabriel Genellina [EMAIL PROTECTED] wrote: En Tue, 30 Oct 2007 06:20:10 -0300, Ajay Deshpande [EMAIL PROTECTED] escribió: I need to retrieve all currently open applications using a python program. So my output should be a list of window handles. Is there a module which I can use? applications or windows? You can use the EnumWindows function, from the Windows API, to enumerate all top level windows. See this article from the Microsoft Knowledge Base http://support.microsoft.com/kb/183009 (the example is in VB but I hope you get the idea) Install the pywin32 extensions from Mark Hammond http://pywin32.sourceforge.net and you'll have the EnumWindows function available. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: __file__ vs __FILE__
On Nov 3, 4:18 am, Bjoern Schliessmann usenet- [EMAIL PROTECTED] wrote: Jeff McNeil wrote: I've used the 'os.path.realpath(os.path.pardir)' construct in a couple of scripts myself. In Windows? Using Linux, this gives me ... I use os.path.dirname(os.path.abspath(__file__)) That ought to work within the interactive interpreter. Why do you also enter that code in the interpreter? If it is in a module, you should always be able to use __file__. Regards, Björn -- BOFH excuse #238: You did wha... oh _dear_ I use os.path.dirname(os.path.abspath(__file__)) That makes sense, as it is almost a literal translation of what I'm used to using in PHP. Thanks for pointing this out. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is pyparsing really a recursive descent parser?
On 2007-11-03, Paul McGuire [EMAIL PROTECTED] wrote: On Nov 3, 12:33 am, Just Another Victim of the Ambient Morality [EMAIL PROTECTED] wrote: It has recursion in it but that's not sufficient to call it a recursive descent parser any more than having a recursive implementation of the factorial function. The important part is what it recurses through... snip In my opinion, the rule set I mentioned in my original post: grammar = OneOrMore(Word(alphas)) + Literal('end') ...should be translated (internally) to something like this: word = Word(alphas) grammar = Forward() grammar ((word + grammar) | (word + Literal(end))) This allows a recursive search to find the string correct without any need for backtracking, if I understand what you mean by that. Couldn't pyparsing have done something like this? Dear JAVotAM - This was a great post! (Although I'm not sure the comment in the first paragraph was entirely fair - I know the difference between recursive string parsing and recursive multiplication.) You really got me thinking more about how this recursion actually behaves, especially with respect to elements such as OneOrMore. Your original question is really quite common, and up until now, my stock answer has been to use negative lookahead. The expression you posted is the first time I've seen this solution, and it *does* work. I was all set to write a cocky response on why your expression wouldn't work. I've seen it many times before, where people (usually coming from EBNF experience) implement listOfXs = OneOrMore(x) as: listOfXs = Forward() listOfXs ( x + listOfXs | x ) Actually, what they usually write is: listOfXs ( listOfXs + x ) but this sends pyparsing into a recursive tailspin. So I fired up SciTE and copy/pasted your code into the editor and ran it, and it worked just fine - this was a shock! I studied this for a few minutes, and then realized what was happening. First of all, I misread what you posted. You posted this: grammar ((word + grammar) | (word + Literal(end))) which works. I *thought* you posted this: grammar ((word + grammar) | word) + Literal(end) which doesn't work. In fact this behaves the same as your original post, except it iterates over the input string's words recursively, vs. repetition ins a for-loop, as is done by OneOrMore. So going back to your working version, I had to see why it works. Initially, the first term in the MatchFirst (the '|' operator creates MatchFirst instances) is just the same, and by grammar referencing itself, it just goes word by word through the input trying to find a match. I'll try to visualize the steps: levelFirst Second Third end 1 word grammar 2 word grammar 3 word grammar 4word grammar - fails! 4word end - fails! (therefore level 3 grammar fails!) 3 word end-- success!!! grammar has 2 options: to match a word followed by a grammar, or to match a word followed by 'end'. At 4 levels deep into the Forward's recursion, the first option fails, because after parsing end as the initial word, there is no more text to try to match against grammar. Level 4's Forward then also tries to match a word followed by 'end', but this fails for the same reason. So at this point, the 4th level Forward fails to match either of its options, so it throws its exception back up to level 3, indicating that the first alternative, word followed by grammar, failed. Level 3 then moves on to see if word followed by the literal 'end' matches, and it does - success! Here's where I am stuck now. In the original grammar that you posted, which you want to render into this behavior, grammar is defined as: grammar = OneOrMore(Word(alphas)) + Literal('end') Is there not an ambiguity in the grammar? In EBNF: goal -- WORD { WORD } END WORD is '[a-zA-Z]+' END is 'end' I think it is fine that PyParsing can't guess what the composer of that grammar meant. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
advice for threaded/parallel application
Hello, I am thinking about writing a simple multi-agent robot simulator, but I am stumped before I begin, trying to decide how to structure the program. My goals are the following: 1) the entire simulator should not include much beyond the standard lib. I'm comfortable with the scipy/numpy/matplotlib combo but I don't want to get into having a lot of dependencies. For example, the PyroRobotics which is great, requires gtk (a pain to install on the Mac), it runs in X, etc... Also, for my needs, I want to write non-object-oriented agents as well as, possible, some object-oriented agents. 2) the robot agents need to be as simple as possible. things like: Forward() while RangeSensor()25: pass Rotate(30) etc... 3) the environment allows for multiple agents, operating in parallel My initial thought was to have a multi-threaded app, with a central environment program and the robots as threads. The agents would do their thing, modifying their properties, and the environment would keep track of positions, orientations, etc... Given that some of the robots might be computationally heavy, and the environment almost certainly would be, I wasn't sure about the performance of python threads. I thought maybe using something like Parallel Python, or the subprocess module, or the processing package. I'd hate to make the wrong choice, discovering it only after putting a lot of time into the development. Any advice for this sort of thing? Brian Blais -- Brian Blais [EMAIL PROTECTED] http://web.bryant.edu/~bblais -- http://mail.python.org/mailman/listinfo/python-list
Low-overhead GUI toolkit for Linux w/o X11?
I'm looking for GUI toolkits that work with directly with the Linux frambuffer (no X11). It's an embedded device with limited resources, and getting X out of the picture would be a big plus. The toolkit needs to be free and open-source. So far, I've found two options that will work without X11: 1) QTopia (nee QT/Embedded). I assume that I can probably get PyQT to work with the embedded version of QT? 2) PySDL or PyGame. I'm not really sure what the differences are between those two. The latter seems to be a little more active. Are there any traditional GUI widgets available for these two? I've heard good things about PyFLTK, but it appears to depend on X11 on the Linux platform. Google found me this thread from a few years ago: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f173b27cb6ac84ce/da101ac750380057?lnk=st Which mentions the same two choices and confirms that PyQt at worked at one time with Qt/E (which would lead one to believe it could be made to work with QTopia). That thread also mentions Pico-GUI and Nano-X. Has anybody had any experience using those with Python? Both of those seem to have stalled. Neither has released anything since 2003. -- Grant Edwards grante Yow! .. I at feel... JUGULAR... visi.com -- http://mail.python.org/mailman/listinfo/python-list
how to fill many data strings from socket.recvfrom()
I want to receive 200 udp datagrams. Each into a new data string. But I dont know how to do that, this is wrong: import socket s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.bind((,port)) i = 0 while i200: data[i],addr = s.recvfrom(1024) i = +1 data[i] is illegal. Any suggestion welcome! -- http://mail.python.org/mailman/listinfo/python-list
Re: (MAC) CoreGraphics module???
David C. Ullrich wrote: On Fri, 02 Nov 2007 14:09:25 -0500, Robert Kern [EMAIL PROTECTED] wrote: David C. Ullrich wrote: [...] So CoreGraphics is a builtin in Apple-Python, explaining why I didn't find the relevant CoreGraphics.py anywhere on the hard drive, eh? Okay, which version of OS X do you have? In 10.3 and 10.4 it used to be here: /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-mac/CoreGraphics.py I'm using 10.4. Yesterday I checked that there is indeed a /System/Library/Frameworks/Python.framework but I didn't look any deeper because I already knew that CoreGraphics.py wasn't there. Come to think of it, it could well be that it's there and I didn't find it because Spotlight didn't want to show me things inside /System? I'll check. (I'll check soon - again, I'm at home and the Mac's at the office.) Possibly. The locate command on the terminal is usually more reliable. I notice that in 10.5, it no longer exists, though. [How do I get to the Python I want?] Python-Python installed a couple of symlinks into /usr/local/bin and then put /usr/local/bin in the front of your $PATH environment variable so it gets picked up first on the terminal. For my Python-Python 2.5, I have python python2.5 pythonw pythonw2.5 python-config python2.5-config Remove these and then when you type python at the terminal, you will get /usr/bin/python, which points to the Apple-Python. Thanks. Right this second I have no idea _where_ I should go to remove that, but I can probably find out. It's in .bashrc or somewhere, I bet, No, don't tell me... $ rm /usr/local/bin/python /usr/local/bin/python2.5 ... -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: python newbie
Duncan Booth [EMAIL PROTECTED] writes: This isn't perfect (global variables have to be set before hooking the module) but it sort of works: - callable.py --- How to define a callable module ... Oh neat, thanks, I'll have to file that one away, and use it now and then. -- http://mail.python.org/mailman/listinfo/python-list
Re: Low-overhead GUI toolkit for Linux w/o X11?
Grant Edwards [EMAIL PROTECTED] writes: I'm looking for GUI toolkits that work with directly with the Linux frambuffer (no X11). It's an embedded device with limited resources, and getting X out of the picture would be a big plus. Sounds like a reasonably modern embedded system since traditionally neither X (nor Python) would likely have even been plausible in such environments. Depending on the higher level GUI functionality you require and how tight the resources really are, you might want to consider investigating pure drawing libraries and then implement any missing GUI elements (widgets and mouse handling) you need yourself. When I was looking for an embedded graphics library for a prior platform (ELAN 486, 2MB flash, 6MB RAM) under DOS, we took a look at these: * GRX (http://grx.gnu.de/index.html) * Allegro (http://alleg.sourceforge.net/) We ended up using GRX, primarily because it was the simplest to develop a custom video driver for to match our platform, along with having a simpler core. We were under DOS but also used it with a later generation of the platform under Linux. Both libraries support operation over the framebuffer in Linux. Our app was in C++ (Python wasn't an option), and we implemented our own buttons and text widgets (in our case we never needed any scrolling widgets). There aren't any Python wrappers for GRX, but the library is straight C which should be easy to wrap (manually or with something like SWIG). No built-in widget support at all (some sample button processing code in a demo module), but easy enough to implement your own if your needs are modest. Although we didn't end up using it, Allegro is more fully featured (actually with some non-GUI cruft too since it targets games), and also appears to have two work-in-progress Python bindings. Some basic widget support in dialog processing routines. -- David -- http://mail.python.org/mailman/listinfo/python-list
problem with iteration
Hello, I managed to write some code in order to do what I wanted: Inject code in the right place, in some html files. I developed the program using small functions, one at the time in order to see how they work. When I tried to put these pieces of code together I got this error: TypeError: iteration over non-sequence Here is the code snippet that has the issue -- def injectCode(path, statcode): for root, dir, files in os.walk(path, topdown=True): for name in files: html_files = re.search(html, name, flags=0) if html_files == None: print No html files found in your path. else: for oldfile in html_files: -- HERE IS THE ERROR [rest of code here] I'm learning through practice and this is my first program. The error may seem easy for you. However except from the explanation I'd like to know how can I handle situations like the one above. I tought that itering was valid there :-( Regards, atma -- http://mail.python.org/mailman/listinfo/python-list
Re: Low-overhead GUI toolkit for Linux w/o X11?
David Bolen [EMAIL PROTECTED] writes: When I was looking for an embedded graphics library for a prior platform (ELAN 486, 2MB flash, 6MB RAM) under DOS, we took a look at these: * GRX (http://grx.gnu.de/index.html) (...) There aren't any Python wrappers for GRX, but the library is straight C which should be easy to wrap (manually or with something like SWIG). No built-in widget support at all (some sample button processing code in a demo module), but easy enough to implement your own if your needs are modest. I had forgotten, since we didn't use it, but there is an external mGui library (http://web.tiscalinet.it/morello/MGui/index.html) that can layer on top of GRX to provide higher level functionality. Of course, it would also have to be wrapped for use from Python. -- David -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with iteration
On Nov 3, 8:58 pm, Panagiotis Atmatzidis [EMAIL PROTECTED] wrote: Hello, I managed to write some code in order to do what I wanted: Inject code in the right place, in some html files. I developed the program using small functions, one at the time in order to see how they work. When I tried to put these pieces of code together I got this error: TypeError: iteration over non-sequence Here is the code snippet that has the issue -- def injectCode(path, statcode): for root, dir, files in os.walk(path, topdown=True): for name in files: html_files = re.search(html, name, flags=0) if html_files == None: print No html files found in your path. else: for oldfile in html_files: -- HERE IS THE ERROR [rest of code here] First step in debugging is to look at the error, and work out what's going on. 'iteration over non-sequence' suggests that 'html_files' isn't a sequence. If it were my program and I didn't understand, I might add 'print html_files' before the offending line to see what it is. That would have given something like: _sre.SRE_Match object at 0x86608 Not particularly helpful, but 'sre' and 'Match' suggests something to do with regular expressions. Given the variable name, you obviously expected a list of files, so you could look at where html_files is created (with a re.match call) to see why your expectation differs from what happened. Perhaps you could add more print statements to the loops to see what values 'files' and 'name' take. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list
Re: python newbie
On Nov 3, 8:35 pm, Paul Rubin http://[EMAIL PROTECTED] wrote: Duncan Booth [EMAIL PROTECTED] writes: This isn't perfect (global variables have to be set before hooking the module) but it sort of works: - callable.py --- How to define a callable module ... Oh neat, thanks, I'll have to file that one away, and use it now and then. I'm intrigued - when would you want a callable module? -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list
Re: how to fill many data strings from socket.recvfrom()
data[i] is illegal. Any suggestion welcome! Either initialize data before: data=[0]*200 before while or (better): ... i=0 data=[] for i in range(200): d,addr= s.recvfrom(1024) data.append(d) -- http://mail.python.org/mailman/listinfo/python-list
Thread structures BUG?
Hello, I create lots of threads that run a script and I have a problem when a thread is created with the same threadId that existed before. When a new thread is started I use this code to enter the interpreter: // create a thread state object for this thread PyEval_AcquireLock(); threadState = PyThreadState_New(mainInterpreterState); PyThreadState_Swap(threadState); and when the thread finishes: PyThreadState_Swap(NULL); PyThreadState_Clear(info); // delete my thread state object PyThreadState_Delete(info); PyEval_ReleaseLock(); Everything works smoothly until a thread id is re-used. I've been testing what is happening and the problem is that PyGILState_GetThisThreadState() returns a PyThreadState for the reused thread id. I changed my code to call PyGILState_GetThisThreadState() before creating the PyThreadState. But if I try to use the returned PyThreadState (that shouldn't exist because I've already deleted) I got an error when trying to access the interpreter dictionary. The workaround that I found is to keep all PyThreadState structures without calling PyThreadState_Clear / PyThreadState_Delete. When a new thread is created I call PyGILState_GetThisThreadState(). If it returns something I reuse the structure. In this way, my code works. Thanks, Pablo Yabo -- http://www.nektra.com -- http://mail.python.org/mailman/listinfo/python-list
Re: python newbie
Paul Hankin [EMAIL PROTECTED] writes: I'm intrigued - when would you want a callable module? I think it would be nice to be able to say import StringIO buf = StringIO('hello') instead of import StringIO buf = StringIO.StringIO('hello') -- http://mail.python.org/mailman/listinfo/python-list
Re: Can local function access local variables in main program?
Stargaming wrote: You can make this work using the `global` statement:: def foo(): ... global x ... print x ... x = 0 Is there any way to disable global for x? Something like that: x = 12345 def foo(): ... global x ... print x ... noglobal(x) # ??? ... x = 0# now this is local x foo() 12345 print x 12345 -- In pariete - manus et crus cerebrumque -- http://mail.python.org/mailman/listinfo/python-list
Re: Is pyparsing really a recursive descent parser?
Paul McGuire [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Nov 3, 12:33 am, Just Another Victim of the Ambient Morality [EMAIL PROTECTED] wrote: It has recursion in it but that's not sufficient to call it a recursive descent parser any more than having a recursive implementation of the factorial function. The important part is what it recurses through... snip In my opinion, the rule set I mentioned in my original post: grammar = OneOrMore(Word(alphas)) + Literal('end') ...should be translated (internally) to something like this: word = Word(alphas) grammar = Forward() grammar ((word + grammar) | (word + Literal(end))) This allows a recursive search to find the string correct without any need for backtracking, if I understand what you mean by that. Couldn't pyparsing have done something like this? Dear JAVotAM - This was a great post! (Although I'm not sure the comment in the first paragraph was entirely fair - I know the difference between recursive string parsing and recursive multiplication.) I often use hyperbole to emphasize a point. I honestly mean no offense. That comment wasn't even meant to be fair, I was hoping to be provocative... You really got me thinking more about how this recursion actually behaves, especially with respect to elements such as OneOrMore. Your original question is really quite common, and up until now, my stock answer has been to use negative lookahead. The expression you posted is the first time I've seen this solution, and it *does* work. I'm glad I got you thinking! I'd hate to be another newbie with another of a thousand questions answered in the FAQ Hey, are you the author of pyparsing? I was all set to write a cocky response on why your expression wouldn't work. I've seen it many times before, where people (usually coming from EBNF experience) implement listOfXs = OneOrMore(x) as: listOfXs = Forward() listOfXs ( x + listOfXs | x ) Actually, what they usually write is: listOfXs ( listOfXs + x ) but this sends pyparsing into a recursive tailspin. So I fired up SciTE and copy/pasted your code into the editor and ran it, and it worked just fine - this was a shock! I studied this for a few minutes, and then realized what was happening. First of all, I misread what you posted. You posted this: grammar ((word + grammar) | (word + Literal(end))) which works. I *thought* you posted this: grammar ((word + grammar) | word) + Literal(end) which doesn't work. In fact this behaves the same as your original post, except it iterates over the input string's words recursively, vs. repetition ins a for-loop, as is done by OneOrMore. I'm grateful that you actually tested my code before posting your cocky response! So going back to your working version, I had to see why it works. Initially, the first term in the MatchFirst (the '|' operator creates MatchFirst instances) is just the same, and by grammar referencing itself, it just goes word by word through the input trying to find a match. I'll try to visualize the steps: levelFirst Second Third end 1 word grammar 2 word grammar 3 word grammar 4word grammar - fails! 4word end - fails! (therefore level 3 grammar fails!) 3 word end-- success!!! grammar has 2 options: to match a word followed by a grammar, or to match a word followed by 'end'. At 4 levels deep into the Forward's recursion, the first option fails, because after parsing end as the initial word, there is no more text to try to match against grammar. Level 4's Forward then also tries to match a word followed by 'end', but this fails for the same reason. So at this point, the 4th level Forward fails to match either of its options, so it throws its exception back up to level 3, indicating that the first alternative, word followed by grammar, failed. Level 3 then moves on to see if word followed by the literal 'end' matches, and it does - success! This is, literally, what it's doing. I'm not exactly a programming whiz so I think of it a little more abstractly. In pyparsing's implementation, it recurses through the first rule, OneOrMore, then iteratively moves to the next rule, only to fail. So, obviously that rule must be part of the recursion if we're not to use backtracking or lookaheads. If it's part of the recursion, it has to be the terminal case. We know that the OneOrMore rule is necessarily followed by the literal, so we can safely conclude that the terminal case will necessarily be followed by the literal, hence the production mentioned... Here's where I am stuck now. In the original grammar that you posted, which you want to render into this behavior, grammar is defined as: grammar = OneOrMore(Word(alphas)) + Literal('end')
Re: python at command prompt
Ton van Vliet [EMAIL PROTECTED] wrote: There's could also be an issue with entering 'python' at the command line, and not 'python.exe'. Once the PATH is setup correctly, try to enter 'python.exe', and check whether that works. IMHO, to get any 'program-name' (without the .exe extension) to work, one needs to: 1. register the executable with windows (doesn't work for python) or 2. make sure the the PATHEXT environment variable is set correctly, and includes the .EXE extension (on my w2k system it looks like: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH) You're confusing two things here. Executables (.exe) are always available, and do not need to be registered to be run without the extension. It is possible to have Windows execute abc.py when you type abc, and that DOES require registering the .py extension and adding .py to the PATHEXT environment variable. A very useful thing to do, by the way. I have many command line tools for which I have forgotten whether they are batch files, small executables, or Python scripts. And that's how it should be. -- Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Low-overhead GUI toolkit for Linux w/o X11?
On 2007-11-03, David Bolen [EMAIL PROTECTED] wrote: Grant Edwards [EMAIL PROTECTED] writes: I'm looking for GUI toolkits that work with directly with the Linux frambuffer (no X11). It's an embedded device with limited resources, and getting X out of the picture would be a big plus. Sounds like a reasonably modern embedded system since traditionally neither X (nor Python) would likely have even been plausible in such environments. Yes, it's modern enough to run Linux/X11 -- horsepower-wise it's sort of in the PDA class of devices. wxWidgets has been tried, but it's pretty sluggish. Hence the search for something a littler lighter weight. Using Python is probably going to be a little bit of a stretch, but using open-source libraries and something like Python for the application langauge seems to be an important part of the business model. Depending on the higher level GUI functionality you require That's still a bit up in the air. Routines to render text would be nice, as would sprite graphics. I don't think text entry or much in the way of windowing is required. and how tight the resources really are, you might want to consider investigating pure drawing libraries and then implement any missing GUI elements (widgets and mouse handling) you need yourself. There is no mouse. I'm not sure how many widgets are required. Probably not very many. When I was looking for an embedded graphics library for a prior platform (ELAN 486, 2MB flash, 6MB RAM) under DOS, we took a look at these: * GRX (http://grx.gnu.de/index.html) * Allegro (http://alleg.sourceforge.net/) We ended up using GRX, primarily because it was the simplest to develop a custom video driver for to match our platform, along with having a simpler core. We were under DOS but also used it with a later generation of the platform under Linux. Both libraries support operation over the framebuffer in Linux. Our app was in C++ (Python wasn't an option), and we implemented our own buttons and text widgets (in our case we never needed any scrolling widgets). There aren't any Python wrappers for GRX, but the library is straight C which should be easy to wrap (manually or with something like SWIG). No built-in widget support at all (some sample button processing code in a demo module), but easy enough to implement your own if your needs are modest. Although we didn't end up using it, Allegro is more fully featured (actually with some non-GUI cruft too since it targets games), and also appears to have two work-in-progress Python bindings. Some basic widget support in dialog processing routines. Thanks for the pointers. -- Grant -- http://mail.python.org/mailman/listinfo/python-list
Re: Can local function access local variables in main program?
On Nov 3, 2007, at 5:32 PM, Pawel wrote: Stargaming wrote: You can make this work using the `global` statement:: def foo(): ... global x ... print x ... x = 0 Is there any way to disable global for x? Something like that: x = 12345 def foo(): ... global x ... print x ... noglobal(x) # ??? ... x = 0# now this is local x foo() 12345 print x 12345 Why would you need to do that? It would be confusing. Just use a different variable name for the local. Erik Jones Software Developer | Emma® [EMAIL PROTECTED] 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate market in style. Visit us online at http://www.myemma.com -- http://mail.python.org/mailman/listinfo/python-list
bsddb in python 2.5.1
Have a rather big problem with bsddb I can't figure out. I upgraded an Ubuntu machine from 7.05 to 7.10 which upgraded python to 2.5.1 I run a local website that uses bsddb, and suddenly I get a version mismatch error with bsddb and I can't access my database anymore I noticed in the 2.5.1 release notes: - fixed a bug with bsddb.DB.stat: the flags and txn keyword arguments were transposed. - Added support for linking the bsddb module against BerkeleyDB 4.5.x. http://www.python.org/download/releases/2.5.1/NEWS.txt I know that when you upgrade Berkeley DB you're supposed to go through steps solving this problem,but I wasn't expecting an upgrade. I've tried to use different versions bsddb3, 4.4 and 4.5, (instead of bsddb that comes with python 2.5.1) with different versions of Berkeley DB installs (4.5 and 4.4 - built from source into /usr/local). But this isn't working. I can't seem a way to figure out how to recover my data. Please help. : ( -- http://mail.python.org/mailman/listinfo/python-list
beautiful girls will help you,why?check it out
beautiful girls will help you,why?check it out http://groups.google.com/group/all-good-things/web/beautiful-girls-and-ladies -- http://mail.python.org/mailman/listinfo/python-list
VC Toolkit 2003
My uploaded torrent at TPB: http://thepiratebay.org/tor/3871785/Visual_Basic_Toolkit_Setup -- http://mail.python.org/mailman/listinfo/python-list
Re: Is pyparsing really a recursive descent parser?
Neil Cerutti [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On 2007-11-03, Paul McGuire [EMAIL PROTECTED] wrote: On Nov 3, 12:33 am, Just Another Victim of the Ambient Morality [EMAIL PROTECTED] wrote: It has recursion in it but that's not sufficient to call it a recursive descent parser any more than having a recursive implementation of the factorial function. The important part is what it recurses through... snip In my opinion, the rule set I mentioned in my original post: grammar = OneOrMore(Word(alphas)) + Literal('end') ...should be translated (internally) to something like this: word = Word(alphas) grammar = Forward() grammar ((word + grammar) | (word + Literal(end))) This allows a recursive search to find the string correct without any need for backtracking, if I understand what you mean by that. Couldn't pyparsing have done something like this? Dear JAVotAM - This was a great post! (Although I'm not sure the comment in the first paragraph was entirely fair - I know the difference between recursive string parsing and recursive multiplication.) You really got me thinking more about how this recursion actually behaves, especially with respect to elements such as OneOrMore. Your original question is really quite common, and up until now, my stock answer has been to use negative lookahead. The expression you posted is the first time I've seen this solution, and it *does* work. Is there not an ambiguity in the grammar? In EBNF: goal -- WORD { WORD } END WORD is '[a-zA-Z]+' END is 'end' I think it is fine that PyParsing can't guess what the composer of that grammar meant. First, I don't know if that constitutes an ambiguity in the grammar. 'end' is a word but it's unambiguous that this grammar must end in a literal 'end'. You could interpret the input as just a sequence of words or you could interpret it as a sequence of words terminated by the word 'end'. One interpretation conforms to the grammar while the other doesn't. You would assume that the interpretation that agrees with the grammar would be the preferable choice and so should the program... Secondly, even if it is an ambiguity... so what? pyparsing's current behaviour is to return a parse error, pretending that the string can't be parsed. Ideally, perhaps it should alert you to the ambiguity but, surely, it's better to return _a_ valid parsing than to pretend that the string can't be parsed at all... -- http://mail.python.org/mailman/listinfo/python-list
Re: how to fill many data strings from socket.recvfrom()
lgwe [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I want to receive 200 udp datagrams. Each into a new data string. But I dont know how to do that, this is wrong: import socket s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.bind((,port)) i = 0 while i200: data[i],addr = s.recvfrom(1024) i = +1 data[i] is illegal. Any suggestion welcome! import socket s=socket(socket.AF_INET,socket.SOCK_DGRAM) s.bind(('',5000)) data=[] for i in range(200): tmp,addr = s.recvfrom(1024) data.append(tmp) -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Python IDE
This is a discussion on the Ubuntu forums-something like 51 pages worth. Even though you are using Gutsy, you want to take a look at KDevelop. It will install without problems even though it is KDE. A lot of people use Geany or Eclipse also. Anyway, you can page through as much of this thread as you like. http://ubuntuforums.org/showthread.php?t=6762 -- http://mail.python.org/mailman/listinfo/python-list
Re: Low-overhead GUI toolkit for Linux w/o X11?
Grant Edwards wrote: Yes, it's modern enough to run Linux/X11 -- horsepower-wise it's sort of in the PDA class of devices. wxWidgets has been tried, but it's pretty sluggish. Hence the search for something a littler lighter weight. Erm, wxWidgets is implemented in C++ and wxPython is just a wrapper. I don't think the sluggishness comes from wxWidgets. PyQt and PySDL are AFAIK not much less weight. Regards, Björn -- BOFH excuse #245: The Borg tried to assimilate your system. Resistance is futile. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can local function access local variables in main program?
Pawel wrote: Is there any way to disable global for x? Something like that: x = 12345 def foo(): ... global x ... print x ... noglobal(x) # ??? ... x = 0# now this is local x Not really. Why don't you choose meaningful variable names? You practically save nothing by using fewer names. Regards, Björn -- BOFH excuse #423: It's not RFC-822 compliant. -- http://mail.python.org/mailman/listinfo/python-list
Re: __file__ vs __FILE__
klenwell wrote: Bjoern Schliessmann wrote: I use os.path.dirname(os.path.abspath(__file__)) That makes sense, as it is almost a literal translation of what I'm used to using in PHP. Thanks for pointing this out. You're welcome, happy coding :) Regards, Björn -- BOFH excuse #286: Telecommunications is downgrading. -- http://mail.python.org/mailman/listinfo/python-list
Re: Poor python and/or Zope performance on Sparc
joa2212 wrote: We have a Sun T1000 with 8 cores and 8 GB of RAM. First, I installed Solaris 10 because I know this OS better than Debian Linux. Result: poor Performance. After that I decided to migrate to debian: Do you know the architecture of this machine? It's extremely streamlined for data throughput (IO) at the expense of computational ability. In particular: - it runs at a relatively small clock speed (1 GHz - 1.4 GHz) - it's terrible for floating-point calculations because there is only one FPU shared by all 32 logical processors While it will be screamingly fast for serving static content, and pretty decent for light database jobs, this not an optimal platform for dynamic web applications, especially for Python since the language's so dynamic and it doesn't support SMP. Since it's so optimized for a certain purpose, you can freely consider it a special-purpose machine, rather than a general-purpose one. Even if you manage to get Zope to spawn parallel request handlers (probably via something like fastcgi), if the web application is CPU-intensive you won't be happy with its performance (for CPU-intensive tasks you probably don't want to spawn more than 8 handlers, since that's the number of physical cores in the CPU). signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Low-overhead GUI toolkit for Linux w/o X11?
On Sat Nov 3 20:45:54 CET 2007, Grant Edwards wrote: I'm looking for GUI toolkits that work with directly with the Linux frambuffer (no X11). It's an embedded device with limited resources, and getting X out of the picture would be a big plus. The toolkit needs to be free and open-source. So far, I've found two options that will work without X11: 1) QTopia (nee QT/Embedded). I assume that I can probably get PyQT to work with the embedded version of QT? Qtopia Core (formerly known as Qt/Embedded) should be fairly painless to get working, though the embedded-specific features aren't supported by a plain PyQt4 build. However, it is possible to get bindings for it up and running - I've done it twice for different versions of Qtopia Core http://www.diotavelli.net/PyQtWiki/PyQt4_on_the_Qtopia_Greenphone so it should be possible to get something working for the latest version. You don't really have to worry too much about having all the bells and whistles wrapped for use from Python, anyway. 2) PySDL or PyGame. I'm not really sure what the differences are between those two. The latter seems to be a little more active. Are there any traditional GUI widgets available for these two? PyGame is definitely more visible than PySDL. You might find something you can use in the list of libraries for PyGame: http://www.pygame.org/tags/libraries There's also a list of gui tagged projects: http://www.pygame.org/tags/gui Google found me this thread from a few years ago: [...] Which mentions the same two choices and confirms that PyQt at worked at one time with Qt/E (which would lead one to believe it could be made to work with QTopia). I guess I should be pushing my patches for PyQt4 back upstream, or at least publishing them somewhere. I suppose it would also be useful if I looked at making them work with a recent version of PyQt4 and made sure that any new widgets in Qtopia Core 4.3 are handled by the configuration system. This lets you exclude features you don't need in order to reduce library sizes. If you're interested in using PyQt4, I'll add an item for these changes near the top of my to do list. If not, I'll probably get around to doing it, but it might not happen soon. David -- http://mail.python.org/mailman/listinfo/python-list
Python good for data mining?
I'm starting a project in data mining, and I'm considering Python and Java as possible platforms. I'm conserned by performance. Most benchmarks report that Java is about 10-15 times faster than Python, and my own experiments confirms this. I could imagine this to become a problem for very large datasets. How good is the integration with MySQL in Python? What about user interfaces? How easy is it to use Tkinter for developing a user interface without an IDE? And with an IDE? (which IDE?) What if I were to use my Python libraries with a web site written in PHP, Perl or Java - how do I intergrate with Python? I really like Python for a number of reasons, and would like to avoid Java. Sorry - lot of questions here - but I look forward to your replies! -- http://mail.python.org/mailman/listinfo/python-list
Re: Low-overhead GUI toolkit for Linux w/o X11?
On 2007-11-04, Bjoern Schliessmann [EMAIL PROTECTED] wrote: Grant Edwards wrote: Yes, it's modern enough to run Linux/X11 -- horsepower-wise it's sort of in the PDA class of devices. wxWidgets has been tried, but it's pretty sluggish. Hence the search for something a littler lighter weight. Erm, wxWidgets is implemented in C++ Are you saying C++ software can't be large and slow? and wxPython is just a wrapper. Yes, I know. If we though Python was the problem, I wouldn't be asking about other toolkits that had Python bindings. I don't think the sluggishness comes from wxWidgets. wxWidgets and GTK+ are both pretty large, and X11 is huge. PyQt and PySDL are AFAIK not much less weight. They don't use X11. That's a _lot_ less weight. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Python IDE
On 3 nov, 15:11, Simon Pickles [EMAIL PROTECTED] wrote: Hi, I have recently moved from Windows XP to Ubuntu Gutsy. I need a Python IDE and debugger, but have yet to find one as good as Pyscripter for Windows. Can anyone recommend anything? What are you all using? Coming from a Visual Studio background, editing text files and using the terminal to execute them offends my sensibilities :) Thanks Si SPE is developped on and works well with Ubuntu Gutsy. It includes a debugger and gui builers. Get it from subversion: http://pythonide.blogspot.com/2007/02/how-to-download-latest-spe-from_26.html Stani -- http://photobatch.stani.be http://pythonide.stani.be -- http://mail.python.org/mailman/listinfo/python-list
Re: Is pyparsing really a recursive descent parser?
On 2007-11-04, Just Another Victim of the Ambient Morality [EMAIL PROTECTED] wrote: Neil Cerutti [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On 2007-11-03, Paul McGuire [EMAIL PROTECTED] wrote: On Nov 3, 12:33 am, Just Another Victim of the Ambient Morality [EMAIL PROTECTED] wrote: It has recursion in it but that's not sufficient to call it a recursive descent parser any more than having a recursive implementation of the factorial function. The important part is what it recurses through... snip In my opinion, the rule set I mentioned in my original post: grammar = OneOrMore(Word(alphas)) + Literal('end') ...should be translated (internally) to something like this: word = Word(alphas) grammar = Forward() grammar ((word + grammar) | (word + Literal(end))) This allows a recursive search to find the string correct without any need for backtracking, if I understand what you mean by that. Couldn't pyparsing have done something like this? Dear JAVotAM - This was a great post! (Although I'm not sure the comment in the first paragraph was entirely fair - I know the difference between recursive string parsing and recursive multiplication.) You really got me thinking more about how this recursion actually behaves, especially with respect to elements such as OneOrMore. Your original question is really quite common, and up until now, my stock answer has been to use negative lookahead. The expression you posted is the first time I've seen this solution, and it *does* work. Is there not an ambiguity in the grammar? In EBNF: goal -- WORD { WORD } END WORD is '[a-zA-Z]+' END is 'end' I think it is fine that PyParsing can't guess what the composer of that grammar meant. First, I don't know if that constitutes an ambiguity in the grammar. 'end' is a word but it's unambiguous that this grammar must end in a literal 'end'. You could interpret the input as just a sequence of words or you could interpret it as a sequence of words terminated by the word 'end'. Yeah. If it were a regex, it would be: '[ab]+b'. That is a fine regex, because a regex is generally just a recognizer; the ambiguity doesn't have to do with recognizing the language. But PyParsing is parser. The ambiguity is in deciding what's a Word(alphas) and what's an 'end'. One interpretation conforms to the grammar while the other doesn't. You would assume that the interpretation that agrees with the grammar would be the preferable choice and so should the program. Secondly, even if it is an ambiguity... so what? pyparsing's current behaviour is to return a parse error, pretending that the string can't be parsed. Ideally, perhaps it should alert you to the ambiguity but, surely, it's better to return _a_ valid parsing than to pretend that the string can't be parsed at all... I wouldn't characterize it as pretending. How would you parse: hello end hello end WORD END WORD END and WORD WORD WORD END are both valid interpretations, according to the grammar. As soon as you remove the ambiguity from the grammar, PyParsing starts to work correctly. Consider writing a recursive decent parser by hand to parse the language '[ab]+b'. goal -- ab_list 'b' ab_list -- 'a' list_tail ab_list -- 'b' list_tail list_tail -- 'a' list_tail list_tail -- 'b' list_tail list_tail -- null The above has the exact same bug (and probably some others--I'm sorry unable to test it just now) as the PyParsing solution. The error is in the grammar. It might be fixed by specifying that 'b' must be followed by EOF, and then it could be coded by using more than one character of lookahead. class ParseError(Exception): pass class Parser: def __init__(self, s): self.s = s self.i = 0 self.c = self.s[self.i] def match(self, c): if self.c != c: raise ParseError('expected %s got %s' % (c, self.c)) self.i += 1 if self.i == len(self.s): raise ParseError('unexpected EOF') self.c = self.s[self.i] def goal(self): self.ab_list() self.match('b') def ab_list(self): if self.c in 'ab': self.match(self.c) self.list_tail() else: raise ParseError('expected list of a or b, got %s' % self.c) def list_tail(self): if self.c in 'ab': self.match(self.c) self.list_tail() else: raise ParseError('expected a list of a or b, got %s' % self.c) Parser('aaab').goal() Traceback (most recent call last): File py.py, line 37, in ? Parser('aaab').goal() File py.py, line 20, in goal self.ab_list() File py.py, line 26, in ab_list self.list_tail() File py.py, line 33, in list_tail self.list_tail() File py.py, line 33, in list_tail self.list_tail() File py.py, line 32, in list_tail self.match(self.c) File py.py, line 16, in match raise ParseError('unexpected EOF') __main__.ParseError: unexpected EOF It's not a coincidence that is has the same bug as the
Re: Low-overhead GUI toolkit for Linux w/o X11?
On 2007-11-04, David Boddie [EMAIL PROTECTED] wrote: 1) QTopia (nee QT/Embedded). I assume that I can probably get PyQT to work with the embedded version of QT? Qtopia Core (formerly known as Qt/Embedded) should be fairly painless to get working, though the embedded-specific features aren't supported by a plain PyQt4 build. However, it is possible to get bindings for it up and running - I've done it twice for different versions of Qtopia Core http://www.diotavelli.net/PyQtWiki/PyQt4_on_the_Qtopia_Greenphone so it should be possible to get something working for the latest version. That's good to hear. You don't really have to worry too much about having all the bells and whistles wrapped for use from Python, anyway. Right, Python has it's own versions of a lot of the extra stuff provided by a framework like Qt. 2) PySDL or PyGame. I'm not really sure what the differences are between those two. The latter seems to be a little more active. Are there any traditional GUI widgets available for these two? PyGame is definitely more visible than PySDL. You might find something you can use in the list of libraries for PyGame: http://www.pygame.org/tags/libraries There's also a list of gui tagged projects: http://www.pygame.org/tags/gui Cool. Hadn't found that yet. Which mentions the same two choices and confirms that PyQt at worked at one time with Qt/E (which would lead one to believe it could be made to work with QTopia). I guess I should be pushing my patches for PyQt4 back upstream, or at least publishing them somewhere. I suppose it would also be useful if I looked at making them work with a recent version of PyQt4 and made sure that any new widgets in Qtopia Core 4.3 are handled by the configuration system. This lets you exclude features you don't need in order to reduce library sizes. If you're interested in using PyQt4, I'll add an item for these changes near the top of my to do list. If not, I'll probably get around to doing it, but it might not happen soon. I think we're definitely going to try to evaluate Qtopia on our platform to see if it's any quicker and smaller than wxWidgets/GTK+/X11. I guess that evaluation doesn't need to use Python -- in theory we sould be able to compare performance of equivalent C/C++ apps running on wxWidgets/GTK+/X11 and on QTopia. -- Grant -- http://mail.python.org/mailman/listinfo/python-list
Re: Low-overhead GUI toolkit for Linux w/o X11?
On Sun Nov 4 03:22:27 CET 2007, Grant Edwards wrote: I think we're definitely going to try to evaluate Qtopia on our platform to see if it's any quicker and smaller than wxWidgets/GTK+/X11. I guess that evaluation doesn't need to use Python -- in theory we sould be able to compare performance of equivalent C/C++ apps running on wxWidgets/GTK+/X11 and on QTopia. Good luck with that. Just remember to read the guide to configuring features in Qtopia Core so you don't build in things you don't need: http://doc.trolltech.com/4.3/qtopiacore-features.html The overview page might also be useful to you: http://doc.trolltech.com/4.3/qtopiacore.html David -- http://mail.python.org/mailman/listinfo/python-list
Re: Python good for data mining?
Jens wrote: I'm starting a project in data mining, and I'm considering Python and Java as possible platforms. I'm concerned by performance. Most benchmarks report that Java is about 10-15 times faster than Python, and my own experiments confirms this. I could imagine this to become a problem for very large datasets. If most of the processing is done with SQL calls, this shouldn't be an issue. I've known a couple of people at Sydney University who were using Python for data mining. I think they were using sqlite3 and MySQL. How good is the integration with MySQL in Python? Never tried it, but a quick google reveals a number of approaches you could try - the MySQLdb module, MySQL for Python, etc. What about user interfaces? How easy is it to use Tkinter for developing a user interface without an IDE? And with an IDE? (which IDE?) WxPython was recommended to me when I was learning how to create a GUI. It has more features than Tkinter and a more native look and feel across platforms. With WxPython it was fairly easy to create a multi-pane, tabbed interface for a couple of programs, without using an IDE. The demos/tutorials were fantastic. What if I were to use my Python libraries with a web site written in PHP, Perl or Java - how do I integrate with Python? Possibly the simplest way would be python .cgi files. The cgi and cgitb modules allow form data to be read fairly easily. Cookies are also fairly simple. For a more complicated but more customisable approach, you could look in to the BaseHTTPServer module or a socket listener of some sort, running that alongside the webserver publicly or privately. Publicly you'd have links from the rest of your php/whatever pages to the python server. Privately the php/perl/java backend would request data from the local python server before feeding the results back through the main server (apache?) to the client. -- http://mail.python.org/mailman/listinfo/python-list
how to iterate through each set
I am begginer in learning Python language. My assignment is to iterate through each set and display results. this is text of assignment: Bill and Ted are taking a road trip. But the odometer in their car is broken, so they don't know how many miles they have driven. Fortunately, Bill has a working stopwatch, so they can record their speed and the total time they have driven. Unfortunately, their record keeping strategy is a little odd, so they need help computing the total distance driven. You are to write a program to do this computation: Speed in miles per hour Total elapsed time in hours 20 2 30 6 10 7 this means they drove 2 hours at 20 miles per hour, then 6-2=4 hours at 30 miles per hour, then 7-6=1 hour at 10 miles per hour. The distance driven is then (2)(20) + (4)(30) + (1)(10) = 40 + 120 + 10 = 170 miles. Note that the total elapsed time is always since the beginning of the trip, not since the previous entry in their log. You will implement a function speed in module speed.py that will help Bill and Ted compute the distance they traveled on several road trips. The input will come from file speed.in and consists of one or more data sets where each data set represents a separate road trip. Each set starts with a line containing an integer n, 1 ≤ n ≤ 10, followed by n pairs of values, one pair per line. The first value in a pair, s, is the speed in miles per hour and the second value, t, is the total elapsed time. Both s and t are integers, 1 ≤ s ≤ 90 and 1 ≤ t ≤ 12. The values for t are always in strictly increasing order. A value of -1 for n signals the end of the input. For each input set, output on the screen the distance driven, followed by a space, followed by the word miles. The output for input file speed.in should be: 170 miles 180 miles 90 miles this is speed.in file used for input: 3 20 2 30 6 10 7 2 60 1 30 5 -1 Here is my code: def speed(): infile = open('speed.in', 'r') line = infile.readline() read = int(line) print line i = 0 t0 = 0 v = 0 while iread: line = infile.readline() list = line.split() s = int(list[0]) t1 = int(list[1]) t = t1- t0 v += s*t i+=1 t0 = t1 print v It works only for first set. How should I implement another solution that would move program to read next set? I think I should implement nested while look, with first that reads until -1 and under it another while loop that reads n times sets. But I have no idea how. Can you help me? -- http://mail.python.org/mailman/listinfo/python-list
Re: how to iterate through each set
Tom_chicollegeboy wrote: snip! Here is my code: def speed(): infile = open('speed.in', 'r') line = infile.readline() read = int(line) print line i = 0 t0 = 0 v = 0 while iread: line = infile.readline() list = line.split() s = int(list[0]) t1 = int(list[1]) t = t1- t0 v += s*t i+=1 t0 = t1 print v It works only for first set. How should I implement another solution that would move program to read next set? I think I should implement nested while look, with first that reads until -1 and under it another while loop that reads n times sets. But I have no idea how. Can you help me? Clues: 1.) Your program works for one block. As you suggested you now need to loop over some of your code until you reach an end condition. 2.) The end condition has been given to you already in the text and the file. 3.) This can be done with two more lines of code. One line to add a loop of some sort, checking for the end condition; and one line which brings you closer to the end condition after each block, and prepares you for the next block. I hope this has given you enough to go on without confusing you or giving you the answer outright. Now a few general pointers unrelated to your assignment: 1.) list is a keyword in python. Don't call your variables list. 2.) You've left the file open at the end of your program. Yes, Python will close it once the program has finished, but it's good practice to close it yourself as soon as you've finished with it. This won't be a problem in this assignment, but it may be in later assignments. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to iterate through each set
On Nov 4, 12:18 am, Cameron Walsh [EMAIL PROTECTED] wrote: Tom_chicollegeboy wrote: snip! Here is my code: def speed(): infile = open('speed.in', 'r') line = infile.readline() read = int(line) print line i = 0 t0 = 0 v = 0 while iread: line = infile.readline() list = line.split() s = int(list[0]) t1 = int(list[1]) t = t1- t0 v += s*t i+=1 t0 = t1 print v It works only for first set. How should I implement another solution that would move program to read next set? I think I should implement nested while look, with first that reads until -1 and under it another while loop that reads n times sets. But I have no idea how. Can you help me? Clues: 1.) Your program works for one block. As you suggested you now need to loop over some of your code until you reach an end condition. 2.) The end condition has been given to you already in the text and the file. 3.) This can be done with two more lines of code. One line to add a loop of some sort, checking for the end condition; and one line which brings you closer to the end condition after each block, and prepares you for the next block. I hope this has given you enough to go on without confusing you or giving you the answer outright. Now a few general pointers unrelated to your assignment: 1.) list is a keyword in python. Don't call your variables list. 2.) You've left the file open at the end of your program. Yes, Python will close it once the program has finished, but it's good practice to close it yourself as soon as you've finished with it. This won't be a problem in this assignment, but it may be in later assignments.- Hide quoted text - - Show quoted text - thanks. Python actually allows to replace its built-in functions with code defined by user inside line. I do not think list() is one of they keyword like if or while. For example, that can be done with reverse(). The answer what I am looking is how to make python continue to go to next block until -1. I am not asking for code, only what algorithm should do. But thank you anyway. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to iterate through each set
On Nov 4, 12:47 am, Dennis Lee Bieber [EMAIL PROTECTED] wrote: On Sat, 03 Nov 2007 21:30:10 -0700, Tom_chicollegeboy [EMAIL PROTECTED] declaimed the following in comp.lang.python: It works only for first set. How should I implement another solution that would move program to read next set? I think I should implement nested while look, with first that reads until -1 and under it another while loop that reads n times sets. But I have no idea how. Can you help me? Homework, huh? So I need to avoid a working solution... Personally, based upon the nature of the data file, I'd base the entire algorithm on a control break which is signified by a line with a single term, and ignore the count value of that term. I'd have to ignore the first control break as there is no output at that time. That can be done by initially setting the total mileage to None (not to 0). On a control break (len(input.split()) == 1): if total mileage is NOT None, output results; set total mileage and elapsed time to 0. On a data line (len(input.split()) == 2): total mileage = total mileage + speed * (current time - elapsed time); elapsed time = current time. Exit on EOF. This algorithm will function even with erroneous input: 4 == only three actual values follow 20 2 30 6 10 7 2 60 1 30 5 -1 Calling the function speed is misleading too -- the /input/ is speed and time, but the output wanted is mileage. With the following data: -=-=-=-=-=-=-=- 4 20 2 30 6 10 7 2 60 1 30 5 -1 10 1 25 1 5 10 -=-=-=-=-=-=-=-=- A quick program produces the following output (NOTE: I added a LOT of ouput statements so you can see the logic -- but I won't show the actual code). initialize total None, elapsed 0, trip count 0 open data file loop over lines in input file, exit on null line input line is: [4] number of values in the line: 1 one value, control break no trip data read before this control break resetting total mileage 0, elapsed 0, incrementing trip count 1 input line is: [20, 2] number of values in the line: 2 elapsed miles: 40 input line is: [30, 6] number of values in the line: 2 elapsed miles: 160 input line is: [10, 7] number of values in the line: 2 elapsed miles: 170 input line is: [2] number of values in the line: 1 one value, control break trip 1: 170 miles resetting total mileage 0, elapsed 0, incrementing trip count 2 input line is: [60, 1] number of values in the line: 2 elapsed miles: 60 input line is: [30, 5] number of values in the line: 2 elapsed miles: 180 input line is: [-1] number of values in the line: 1 one value, control break trip 2: 180 miles resetting total mileage 0, elapsed 0, incrementing trip count 3 input line is: [10, 1] number of values in the line: 2 elapsed miles: 10 input line is: [25, 1] number of values in the line: 2 elapsed miles: 10 input line is: [5, 10] number of values in the line: 2 elapsed miles: 55 No terminating control break found Unfinished trip is: trip 3: 55 miles By the way -- YOUR sample input data has ONLY TWO TRIPS -- so how can the correct output be THREE trips? -- WulfraedDennis Lee Bieber KD6MOG [EMAIL PROTECTED] [EMAIL PROTECTED] HTTP://wlfraed.home.netcom.com/ (Bestiaria Support Staff: [EMAIL PROTECTED]) HTTP://www.bestiaria.com/ very helpful hints. thank you very much -- http://mail.python.org/mailman/listinfo/python-list
Re: Low-overhead GUI toolkit for Linux w/o X11?
Grant Edwards [EMAIL PROTECTED] writes: There is no mouse. I'm not sure how many widgets are required. Probably not very many. Back in the old days there were some lightweight toolkits for doing text mode GUI's using ANSI graphic characters for MS-DOS. I did a few of them. You could do quite usable and attractive gui's that way, as long as you didn't require too much bling. -- http://mail.python.org/mailman/listinfo/python-list
[issue1372] zlibmodule.c: int overflow in PyZlib_decompress
Peter Weseloh added the comment: You are right. The format should be 'l'. I overlooked that. In my case the optional 'buf_size' parameter of 'decompress' is not used anyhow. Shall I change the patch accordingly? It work well for me and I now checked the code of PyArg_ParseTuple (Python/getargs.c) to see what happens. As far as I understand, the given pointer is casted to a pointer to int if the format is 'i' (line 630) . On a 64 bit machine this leads to a downcast from a (64 bit) long to a (32 bit) int, which is OK AFAIK, but I could be wrong. Thanks for pointing that out, Peter 2007/11/2, Guido van Rossum [EMAIL PROTECTED]: Guido van Rossum added the comment: I trust that there's a problem, but this can't be right -- the address of r_strlen is passed to PyArg_ParseTuple corresponding to an 'i' format letter. That will never do. -- assignee: - nnorwitz nosy: +gvanrossum, nnorwitz __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1372 __ Added file: http://bugs.python.org/file8681/unnamed __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1372 __You are right. The format should be #39;l#39;. I overlooked that. In my case the optional #39;buf_size#39; parameter of #39;decompress#39; is not used anyhow.brShall I change the patch accordingly?brbrIt work well for me and I now checked the code of PyArg_ParseTuple (Python/getargs.c) to see what happens. As far as I understand, the given pointer is casted to a pointer to int if the format is #39;i#39; (linenbsp; 630) . On a 64 bit machine this leads to a downcast from a (64 bit) long to a (32 bit) int, which is OK AFAIK, but I could be wrong. brbrThanks for pointing that out,brPeterbrdivspan class=gmail_quote2007/11/2, Guido van Rossum lt;a href=mailto:[EMAIL PROTECTED][EMAIL PROTECTED]/agt;:/spanblockquote class=gmail_quote style=border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex; brGuido van Rossum added the comment:brbrI trust that there#39;s a problem, but this can#39;t be right -- the addressbrof r_strlen is passed to PyArg_ParseTuple corresponding to an #39;i#39; formatbrletter.nbsp;nbsp;That will never do. brbr--brassignee:nbsp;nbsp;-gt; nnorwitzbrnosy: +gvanrossum, nnorwitzbrbr__brTracker lt;a href=mailto:[EMAIL PROTECTED][EMAIL PROTECTED]/agt;brlt;a href=http://bugs.python.org/issue1372; http://bugs.python.org/issue1372/agt;br__br/blockquote/divbr ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1376] uu module catches a wrong exception type
Guido van Rossum added the comment: You misunderstand. The try/except is there in case os.stat isn't defined or its result doesn't have a st_mode attribute. If the stat operation fails due to a problem with the file, there's not much point in proceeding since the subsequent open() call would fail the same way. -- nosy: +gvanrossum resolution: - invalid status: open - closed __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1376 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1378] fromfd() and dup() for _socket on WIndows
New submission from roudkerk: The patch adds support for _socket.fromfd() and _socket.socket.dup() on Windows. It uses the Win32 DuplicateHandle() function. The patch is to socketmodule.c an test_socket.py. -- files: socket_fromfd.patch messages: 57084 nosy: roudkerk severity: normal status: open title: fromfd() and dup() for _socket on WIndows type: behavior versions: Python 2.5 Added file: http://bugs.python.org/file8682/socket_fromfd.patch __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1378 __ socket_fromfd.patch Description: Binary data ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1378] fromfd() and dup() for _socket on WIndows
Changes by Martin v. Löwis: -- keywords: +patch __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1378 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1379] reloading imported modules sometimes fail with 'parent not in sys.modules' error
Changes by Martin v. Löwis: -- keywords: +patch __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1379 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1380] fix for test_asynchat and test_asyncore on pep3137 branch
New submission from Adam Hupp: The attached patch resolves test failues in test_asynchat and test_asyncore. The asynchat failure was due to interpolating a byte string into a unicode string using %s. This resulted in a b'' byte representation in the final string. The fix is to use string constants instead of byte constants. The result is encoded to bytes later on. The asyncore failure was due to an explicit isinstance(data, bytes) check on the result of recv. The actual type in this case was buffer. I've removed the check since the next line calls data.replace(b'\n', b'') This all should fail for anything thats not a buffer or bytes. -- components: Library (Lib), Tests files: pep3137-asynfix.patch messages: 57086 nosy: hupp severity: normal status: open title: fix for test_asynchat and test_asyncore on pep3137 branch type: behavior versions: Python 3.0 Added file: http://bugs.python.org/file8684/pep3137-asynfix.patch __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1380 __ pep3137-asynfix.patch Description: Binary data ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1380] fix for test_asynchat and test_asyncore on pep3137 branch
Christian Heimes added the comment: Applied in r58831 Thanks! -- keywords: +patch, py3k nosy: +tiran resolution: - fixed status: open - closed __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1380 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1381] cmath is numerically unsound
New submission from Andreas Kloeckner: This here basically says it all: import cmath;[cmath.asinh(i*1e-17).real for i in range(0,20)] [4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16, 4.4408920985006257e-16] The boost.math toolkit at [2] is an implementation that does better in the above (real-only) aspect. [2] http://freespace.virgin.net/boost.regex/toolkit/html/index.html Tim Peters remarks in [1] that basically all of cmath is unsound. http://mail.python.org/pipermail/python-bugs-list/2001-February/004126.html I just wanted to make sure that this issue remains on the radar. -- components: Library (Lib) messages: 57088 nosy: inducer severity: normal status: open title: cmath is numerically unsound type: behavior versions: Python 2.5 __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1381 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1381] cmath is numerically unsound
Martin v. Löwis added the comment: Can you propose a patch? -- nosy: +loewis __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1381 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1381] cmath is numerically unsound
Andreas Kloeckner added the comment: On Samstag 03 November 2007, Martin v. Löwis wrote: Martin v. Löwis added the comment: Can you propose a patch? Other than point at how boost.math does things, I don't have the time to work on this right now, sorry. Andreas __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1381 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1372] zlibmodule.c: int overflow in PyZlib_decompress
Changes by Guido van Rossum: Removed file: http://bugs.python.org/file8681/unnamed __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1372 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1372] zlibmodule.c: int overflow in PyZlib_decompress
Guido van Rossum added the comment: The correct format for a Py_ssize_t is 'n' (at least in the trunk, I don't have the 2.5 branch handy but I imagine it's the same). We can figure out the patch from here. __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1372 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1381] cmath is numerically unsound
Alan McIntyre added the comment: I have to review a few complex math topics for some of my current course work, so I wouldn't mind taking a look into this. I can't promise I'll have the time required to make all of cmath correct (assuming it's as unsound as claimed), but I'll do what I can. -- nosy: +alanmcintyre __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1381 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com