RE: PEP 3131: Supporting Non-ASCII Identifiers
Let me guess - the next step will be to restrict the identifiers to be at most 6 characters long. -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Stefan Behnel Sent: Monday, May 14, 2007 2:53 PM To: python-list@python.org Subject: Re: PEP 3131: Supporting Non-ASCII Identifiers Marc 'BlackJack' Rintsch schrieb: > In <[EMAIL PROTECTED]>, Michel Claveau > wrote: > >> And Il1 O0 ? > > Hm, we should ban digits from identifier names. :-) Ah, good idea - and capital letters also. After all, they are rare enough in English to just plain ignore their existance. Stefan :) -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: Checking if string inside quotes?
Thanks, but it is a little more complicated than that, the string could be deep in quotes. The problem is in string substitution. Suppose I have a dictionary with MY_IP : "172.18.51.33" I need to replace all instances of MY_IP with "172.18.51.33" in the file. It is easy in cases such as: if (MY_IP == "127.0.0.1"): But suppose I encounter:" ("(size==23) and (MY_IP==127.0.0.1)") In this case I do not want: ("(size==23) and ("172.18.51.33"==127.0.0.1)") but: ("(size==23) and (172.18.51.33==127.0.0.1)") without the internal quotes. How can I do this? I presumed that I would have to check to see if the string was already in quotes and if so remove the quotes. But not sure how to do that? Or is there an easier way? Thanks in advance: Michael Yanowitz -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of [EMAIL PROTECTED] Sent: Wednesday, May 09, 2007 5:12 PM To: python-list@python.org Subject: Re: Checking if string inside quotes? On May 9, 1:39 pm, "Michael Yanowitz" <[EMAIL PROTECTED]> wrote: > Hello: > >If I have a long string (such as a Python file). > I search for a sub-string in that string and find it. > Is there a way to determine if that found sub-string is > inside single-quotes or double-quotes or not inside any quotes? > If so how? > > Thanks in advance: > Michael Yanowitz I think the .find() method returns the index of the found string. You could check one char before and then one char after the length of the string to see. I don't use regular expressions much, but I'm sure that's a more elegant approach. This will work. You'll get in index error if you find the string at the very end of the file. s = """ foo "bar" """ findme = "foo" index = s.find(findme) if s[index-1] == "'" and s[index+len(findme)] == "'": print "single quoted" elif s[index-1] == "\"" and s[index+len(findme)] == "\"": print "double quoted" else: print "unquoted" ~Sean -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Checking if string inside quotes?
Hello: If I have a long string (such as a Python file). I search for a sub-string in that string and find it. Is there a way to determine if that found sub-string is inside single-quotes or double-quotes or not inside any quotes? If so how? Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
RE: Breaking up Strings correctly:
-Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Adam Atlas Sent: Monday, April 09, 2007 11:28 PM To: python-list@python.org Subject: Re: Breaking up Strings correctly: On Apr 9, 8:19 am, "Michael Yanowitz" <[EMAIL PROTECTED]> wrote: > Hello: > >I have been searching for an easy solution, and hopefully one > has already been written, so I don't want to reinvent the wheel: Pyparsing is indeed a fine package, but if Paul gets to plug his module, then so do I! :) I have a package called ZestyParser... a lot of it is inspired by Pyparsing, actually, but I'm going in a different direction in many areas. (One major goal is to be crazily dynamic and flexible on the inside. And it hasn't failed me thus far; I've used it to easily parse grammars that would make lex and yacc scream in horror.) Here's how I'd do it... from ZestyParser import * from ZestyParser.Helpers import * varName = Token(r'\$(\w+)', group=1) varVal = QuoteHelper() | Int sp = Skip(Token(r'\s*')) comparison = sp.pad(varName + CompositeToken([RawToken(sym) for sym in ('=','<','>','>=','<=','!=')]) + varVal) #Maybe I should "borrow" PyParsing's OneOf idea :) expr = ExpressionHelper(( comparison, (RawToken('(') + Only(_top_) + RawToken(')')), oper('NOT', ops=UNARY), oper('AND'), oper('OR'), )) Now you can scan for `expr` and get a return value like [[['IP', '=', '127.1.2.3'], ['AX', '<', 15]], [['IP', '=', '127.1.2.4'], ['AY', '! =', 0]]] (for the example you gave). Note that this example uses several features that won't be available until the next release, but it's coming soon. So Michael, though you'd still be able to parse this with the current version, the code wouldn't look as nice as this or the Pyparsing version. Maybe just add it to your watchlist. :) - Adam -- Thanks for your and Gerard's and Gabriel's responses. I guess what I was looking for was something simpler than parsing. I may actually use some of what you posted. But I am hoping that if given a string such as: '((($IP = "127.1.2.3") AND ($AX < 15)) OR (($IP = "127.1.2.4") AND ($AY != 0)))' something like split(), where I can pass it something like [' AND ', ' OR ', ' XOR '] will split the string by AND, OR, or XOR. BUT split it up in such a way to preserve the parentheses order, so that it will split on the outermost parenthesis. So that the above string becomes: ['OR', '(($IP = "127.1.2.3") AND ($AX < 15))', '(($IP = "127.1.2.4") AND ($AY != 0))'] No need to do this recursively, I can repeat the process, however if I wish on each string in the list and get: ['OR', ['AND', '($IP = "127.1.2.3")', '($AX < 15)'], ['AND', '($IP = "127.1.2.4")', '($AY != 0)']] Can this be done without parsers? Perhaps with some variation of re or split. Has something like this already been written? Thanks in advance: -- http://mail.python.org/mailman/listinfo/python-list
Breaking up Strings correctly:
Hello: I have been searching for an easy solution, and hopefully one has already been written, so I don't want to reinvent the wheel: Suppose I have a string of expressions such as: "((($IP = "127.1.2.3") AND ($AX < 15)) OR (($IP = "127.1.2.4") AND ($AY != 0))) I would like to split up into something like: [ "OR", "(($IP = "127.1.2.3") AND ($AX < 15))", "(($IP = "127.1.2.4") AND ($AY != 0))" ] which I may then decide to or not to further split into: [ "OR", ["AND", "($IP = "127.1.2.3")", "($AX < 15)"], ["AND", "(($IP = "127.1.2.4")", ($AY != 0))"] ] Is there an easy way to do this? I tried using regular expressions, re, but I don't think it is recursive enough. I really want to break it up from: (E1 AND_or_OR E2) and make that int [AND_or_OR, E1, E2] and apply the same to E1 and E2 recursively until E1[0] != '(' But the main problem I am running to is, how do I split this up by outer parentheseis. So that I get the proper '(' and ')' to split this upper correctly? Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
RE: division by 7 efficiently ???
I think it is off by 1 in small numbers, off by a little more with large numbers: >>> def div7 (N): ...return (N>>3) + ((N-7*(N>>3))>>3) ... >>> div7 (70) 9 >>> div7 (77) 10 >>> div7 (700) 98 >>> div7 (7) 0 >>> div7 (10) 1 >>> div7 (14) 1 >>> div7 (21) 2 >>> div7 (700) 98 >>> div7 (7000) 984 Michael Yanowitz -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Krypto Sent: Thursday, February 01, 2007 3:25 PM To: python-list@python.org Subject: Re: division by 7 efficiently ??? The correct answer as told to me by a person is (N>>3) + ((N-7*(N>>3))>>3) The above term always gives division by 7 -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: Is there a better way to implement this:
Thanks. I suppose I could have used time.sleep(seconds) here. I did it in 0.01 because in an earlier verion, I did something else between the sleeps. I guess I am looking for something portable (both Windows and Linux) where I can abort a function after a certain time limit expires. -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Benjamin Niemann Sent: Monday, January 22, 2007 11:19 AM To: python-list@python.org Subject: Re: Is there a better way to implement this: Michael Yanowitz wrote: > Hello: > >I wrote the code below (much irrelevant code removed). > This doesn't quite work. What I wanted it to do was > a) Execute function ftimed, which takes a function and a timeout > in seconds. > b) This will also execute function abort() as a thread. > This function just runs for the specified > number of seconds and returns. > However, before it returns, throws an exception. > c) If test() is still running when abort() is > finished, ftimed() should catch the exception and > return. > > It is catching the exception, however it continues running the function. > Why does it continue and not return? The exception is raised in the thread that executes the abort() function. The exception does not get caught and terminates this thread. The other (main) thread is unaffected - exceptions are local to a thread and there is currently no (portable) way to raise an exception in another thread. > What am I missing, or is there a better way to > implement this (having ftimed() return when the > abort-timer time is exceeded? You may use the signal.alarm() function, if you are on a UNIXoid system and you have only a signle time-out at a time (e.g. not nested). > import time, thread, sys > > thread_finished = "MAX RUN TIME EXCEEDED!" > > def abort (seconds): > start_time = time.time() > while ((time.time() - start_time) < seconds): > time.sleep(0.01) any reason for not using time.sleep(seconds) here? I suppose I could have, but in earlier versions > print "script run time exceeded max_run_time of", seconds, "seconds." > raise thread_finished > return > > > def test(): > i = 0 > while (True): >time.sleep(1) >print "HELLO", i >i+=1 > > > def ftimed (func, seconds): > thread.start_new_thread (abort, (seconds,)) > > try: > func() > except thread_finished: > print "Timeout" > return > > ftimed (test, 30) > print "Script finished" -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Is there a better way to implement this:
Hello: I wrote the code below (much irrelevant code removed). This doesn't quite work. What I wanted it to do was a) Execute function ftimed, which takes a function and a timeout in seconds. b) This will also execute function abort() as a thread. This function just runs for the specified number of seconds and returns. However, before it returns, throws an exception. c) If test() is still running when abort() is finished, ftimed() should catch the exception and return. It is catching the exception, however it continues running the function. Why does it continue and not return? What am I missing, or is there a better way to implement this (having ftimed() return when the abort-timer time is exceeded? import time, thread, sys thread_finished = "MAX RUN TIME EXCEEDED!" def abort (seconds): start_time = time.time() while ((time.time() - start_time) < seconds): time.sleep(0.01) print "script run time exceeded max_run_time of", seconds, "seconds." raise thread_finished return def test(): i = 0 while (True): time.sleep(1) print "HELLO", i i+=1 def ftimed (func, seconds): thread.start_new_thread (abort, (seconds,)) try: func() except thread_finished: print "Timeout" return ftimed (test, 30) print "Script finished" It presently generates the following output: $ python ./testthread.py HELLO 0 HELLO 1 HELLO 2 HELLO 3 HELLO 4 HELLO 5 HELLO 6 HELLO 7 HELLO 8 HELLO 9 HELLO 10 HELLO 11 HELLO 12 HELLO 13 HELLO 14 HELLO 15 HELLO 16 HELLO 17 HELLO 18 HELLO 19 HELLO 20 HELLO 21 HELLO 22 HELLO 23 HELLO 24 HELLO 25 HELLO 26 HELLO 27 HELLO 28 HELLO 29 script run time exceeded max_run_time of 30 seconds. Unhandled exception in thread started by Traceback (most recent call last): File "./testthread.py", line 10, in abort raise thread_finished MAX RUN TIME EXCEEDED! HELLO 30 HELLO 31 HELLO 32 Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
RE: Can a Tkinter GUI check for abort script:
-Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of hg Sent: Tuesday, December 19, 2006 9:44 AM To: python-list@python.org Subject: Re: Can a Tkinter GUI check for abort script: Michael Yanowitz wrote: > Hello: > >I have successfully implemented a Tkinter GUI which has > this (simplified here for explanation): > +-+ > | filename: [./test3.py] | > | | > | [Run Script] | > +-+ > >But, now what I would like to do while the script is > running, is replace the "Run Script" with "Abort Script". > > +-+ > | filename: [./test3.py] | > | | > | [Abort Script] | > +-+ > >So, every tenth of a seconds or ??? better time, I > would like to 'return' to the GUI and check if the > "Abort Script" button has been pressed. >How do I do this? Or is there a better way to > implement this? > > Thanks in advance: > Michael Yanowitz It depends: As you cannot "kill" a thread in Python, you need some mechanism to stop your script another way (is that a python script or a .sh / .bat ? ... from what you're writing, it seems you're calling some external entity which just might launch a bunch of processes) So do you or not control the inner workings of that external script ? If you don't, then "killing" might be the way as posted / clearly the methord will change from environment to environment. hg -- Yeah, it is a Python script, which I preprocess and then load using __import__(script_filename) So when I preprocess it, I can add/remove codelines and possibly add control of the GUI - the original Python scripts will not know anything about the GUI. Thanks: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
RE: Can a Tkinter GUI check for abort script:
No. test3.py (for example) is just plain Python code that sends and receives socket data from another machine. It does (or could) contain loops that last a long time, repeating the read or write operations to and from the socket. This grabs the CPU. What I am hoping for is a function call I can make, without knowing any of the GUI objects, I can call from test3.py (or while test3.py is running) which will refresh the GUI and check for activity such as button presses on the GUI itself. For example, if I just call sleep(), will it do this? Thanks in advance: Michael Yanowitz -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Mohammad Tayseer Sent: Monday, December 18, 2006 11:28 AM To: python-list@python.org Subject: RE: Can a Tkinter GUI check for abort script: I don't know why this happen. do you call mainloop() inside the test3.py?? you shouldn't Michael Yanowitz <[EMAIL PROTECTED]> wrote: > Presently what happens is that the script takes over and all the buttons on > the GUI disappear > as the GUI is not given any cpu time to refresh or check if any activity in > the dialog. __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
RE: Can a Tkinter GUI check for abort script:
Thank you (and Thanks to Hendrik). Both good ideas. I will need to do those or something similar too. But what I really want to know is what I need to do when pressing the "Run Script" button, so that I 'return' to the GUI every once in a while, like every 100 milliseconds to check if the "Abort Script" button is pressed. Presently what happens is that the script takes over and all the buttons on the GUI disappear as the GUI is not given any cpu time to refresh or check if any activity in the dialog. Thanks in advance: Michael Yanowitz -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Mohammad Tayseer Sent: Monday, December 18, 2006 10:40 AM To: python-list@python.org Subject: Re: Can a Tkinter GUI check for abort script: To view a button & hide the other, call .pack_forget() on the button you want to hide & pack() on the button you want to show test3.py should contains a main() function that returns the new window. if you press 'Abort script' button you should call new_window.destroy(), pack_forget() the current button & pack() the 'run script' button __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Can a Tkinter GUI check for abort script:
Hello: I have successfully implemented a Tkinter GUI which has this (simplified here for explanation): +-+ | filename: [./test3.py] | | | | [Run Script] | +-+ But, now what I would like to do while the script is running, is replace the "Run Script" with "Abort Script". +-+ | filename: [./test3.py] | | | | [Abort Script] | +-+ So, every tenth of a seconds or ??? better time, I would like to 'return' to the GUI and check if the "Abort Script" button has been pressed. How do I do this? Or is there a better way to implement this? Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
Best way to split up lines - RE: About the 79 character line recommendation
Hello: I too don't like large lines. However in the following case, and multi-level indentations, I find it unavoidable. Here is one huge statement I haven't been able to split onto multiple lines. What would be the best way to split the following line (Python doesn't like me to split it up between the comma-separated parameters): top, ip1, ip2, ip3, ip4, messageCounter, ackRequired, dataType, utc1, utc2, utc3, utc4, utc5, utc6, utc7, utc8, utc9, utc10, utc11, utc12, st1, st2, st3, st4, st5, st6, numberOfLabels, dataWord = struct.unpack("!H4BH20BHI", strMessage) Thanks in advance: Michael Yanowitz -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Ramon Diaz-Uriarte Sent: Wednesday, December 06, 2006 5:12 PM To: Steve Bergman Cc: python-list@python.org Subject: Re: About the 79 character line recommendation On 5 Dec 2006 13:28:22 -0800, Steve Bergman <[EMAIL PROTECTED]> wrote: (...) > > I'm finding 100 to be a nice balance. It forces me not to be lazy and > allow really long lines, but allows me to format so as to make the > meaning most clear. > But if you use some advanced editors (such as Emacs) that easily allow you to see/edit the same file in two buffers side by side, then going beyond 80 chars is often a bad idea, specially if you use a laptop. (And, of course, there is the eternal issue of doing a simple "a2ps" to print some code; longer than 80 and you often have hard to read pages). Best, R. -- Ramon Diaz-Uriarte Statistical Computing Team Structural Biology and Biocomputing Programme Spanish National Cancer Centre (CNIO) http://ligarto.org/rdiaz -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: String Replace only if whole word?
>Michael Yanowitz wrote: >> Hello: >> >> I am hoping someone knows if there is an easier way to do this or someone >> already implemented something that does this, rather than reinventing the >> wheel: >> I have been using the string.replace(from_string, to_string, len(string)) >> to replace names in a file with their IP address. >> For example, I have definitions file, that looks something like: >> 10.1.3.4 LANDING_GEAR >> 20.11.222.4 ALTIMETER_100 >> 172.18.50.138 SIB >> 172.18.50.138 LAPTOP >> 172.18.51.32 WIN2000 >> 127.0.0.1 LOCALHOST >> >> and I have a text file (a Python script) that has these names in the file. >> In most cases the string.replace() command works great. But there is one >> instance which it fails: >> Suppose I had in the file: >> if (LAPTOP_IS_UP()): >>It would replace the string with: >> if ("172.18.50.138"_IS_UP()): >> >>Is there any easy way to avoid this, only replace if a whole word >> matches? >> I probably need something which determines when a word ends, and I will >> define >> a word as containing only 'A'-'Z','a'-'z','0'-'9','_' . As long as the >> string >> contains more of the word digits after the match, don't replace? >> >> Thanks in advance: >> Michael Yanowitz > >You need regular expressions for this. Use the re module. >http://docs.python.org/lib/module-re.html > >from the docs: > >re.sub(pattern, repl, string[, count]) >Return the string obtained by replacing the leftmost non-overlapping >occurrences of pattern in string by the replacement repl. > >Your pattern would be "[^A-Za-z0-9_]word[^A-Za-z0-9_]" > >[^xy] is approximately not in ('x', 'y') > >-- >Juho Schultz Thanks. This works great except for one thing: The character after the replacement is deleted, so that if I have send_data (LAPTOP, test_string) it would replace it with: send_data (10.1.3.4 test_string) (ignoring that the 10.1.3.4 is not quoted). The comma is missing. Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
String Replace only if whole word?
Hello: I am hoping someone knows if there is an easier way to do this or someone already implemented something that does this, rather than reinventing the wheel: I have been using the string.replace(from_string, to_string, len(string)) to replace names in a file with their IP address. For example, I have definitions file, that looks something like: 10.1.3.4 LANDING_GEAR 20.11.222.4 ALTIMETER_100 172.18.50.138 SIB 172.18.50.138 LAPTOP 172.18.51.32 WIN2000 127.0.0.1 LOCALHOST and I have a text file (a Python script) that has these names in the file. In most cases the string.replace() command works great. But there is one instance which it fails: Suppose I had in the file: if (LAPTOP_IS_UP()): It would replace the string with: if ("172.18.50.138"_IS_UP()): Is there any easy way to avoid this, only replace if a whole word matches? I probably need something which determines when a word ends, and I will define a word as containing only 'A'-'Z','a'-'z','0'-'9','_' . As long as the string contains more of the word digits after the match, don't replace? Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
255 argument limit?
Hello: It appears that there is a 255 argument limit in Python 2.4.3? >>> packed_data = struct.pack("260i", 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21 ,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46, 47,4 8,49,50,1,1,1,1,1,1,1,1,1,60,1,2,3,4,5,6,7,8,9,70,1,2,3,4,5,6,7,8,9,80,1,2,3 ,4,5 ,6,7,8,9,90,1,2,3,4,5,6,7,8,9,100,1,2,3,4,5,6,7,8,9,110,1,2,3,4,5,6,7,8,9,12 0,1, 2,3,4,5,6,7,8,9,130,1,2,3,4,5,6,7,8,9,140,1,2,3,4,5,6,7,8,9,150,1,2,3,4,5,6, 7,8, 9,160,1,2,3,4,5,6,7,8,9,170,1,2,3,4,5,6,7,8,9,180,1,2,3,4,5,6,7,8,9,190,1,2, 3,4, 5,6,7,8,9,200,1,2,3,4,5,6,7,8,9,210,1,2,3,4,5,6,7,8,9,220,1,2,3,4,5,6,7,8,9, 230, 1,2,3,4,5,6,7,8,9,240,1,2,3,4,5,6,7,8,9,250,1,2,3,4,5,6,7,8,9) SyntaxError: more than 255 arguments Is there a way to increase this limit? (This is just a made up example, I would not normally do this). Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
Defining our own types?
Hello: I know this will probably turn about to be another dumb question and I know I have asked a few really dumb ones lately on this list, but I am hoping otherwise this time: suppose I type: ip = 123.45.67.89 (no quotes) - is it possible (maybe by catching an exception), to have this automatically converted to an ip address and maybe have the exception convert this into: ip = make_ip_address (123, 45, 67, 89) Or even better, if possible. Can I define my own type IP = BYTE + '.' + BYTE + '.' + BYTE + '.' + BYTE BYTE = in range(256) and have Python over-ride its rules so that if I type in a number followed by a dot followed by number followed by a dot followed by a number followed by a dot and another number, it can call make_ip_address() on the value? Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
Make Object Oriented?
Hello: Are there any tools to convert non-object-oriented code into object-oriented code? If not, perhaps something that I can pass in two (or more) classes and will create a base-class and simplify the passed in classed to be derived from the base class? Ideally this would be Python but if not, C-to-C++ would be ok? Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
Negative division bug?
Hello: Just wondering if this is a bug, is this as designed, or do I have to import math or something to make it correct: I was just screwing around. and found: >>> -1/100 -1 Shouldn't it be zero? 1/100 returns 0 but -1/ANY_POSITIVE_INTEGER_NUMBER returns -1 >>> -10/3 -4 It behaves correct for positive numbers, but for negative integers it seems to subtract one from the expected result. Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
RE: Static Variables in Python?
-Original Message- From: Cliff Wells [mailto:[EMAIL PROTECTED] Sent: Monday, July 31, 2006 4:55 PM To: Michael Yanowitz Cc: python-list@python.org Subject: Re: Static Variables in Python? On Mon, 2006-07-31 at 15:21 -0400, Michael Yanowitz wrote: > Is it possible to have a static variable in Python - > a local variable in a function that retains its value. > > For example, suppose I have: > > def set_bit (bit_index, bit_value): >static bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >bits [bit_index] = bit_value > >print "\tBit Array:" >int i >while (i < len(bits): > print bits[i], >print '\n' > > >I realize this can be implemented by making bits global, but can > this be done by making it private only internal to set_bit()? I don't > want bits to be reinitialized each time. It must retain the set values > for the next time it is called. BTW, I'm assuming this example was contrived. In real life, I wonder why you'd ever want to use anything besides: bits = [ 0 ] * 16 bits [ 4 ] = 1 print "Bit Array:" print ' '.join ( bits ) Having a "set_bit" function seems redundant when the language syntax directly supports what you are trying to do. Regards, Cliff -- Thanks everyone for your help. Yes I know it is contrived. Well it is as over-simplified version of what I really want. And yes, I do realize after sending it about the infinite loop in the printing. I tried too quickly to come up with a good example without testing it first. I like the class idea, however I realize that the class object itself has to be global. I will look into the decorators - something which I have avoided until now. I tried creating a class, but got an error: # * class BitsClass * class BitsClass (object): def __init__(self, num_bits): self.bits=[] for i in range(num_bits): self.bits.append(0) def set(self, bit_index, value): self.bits[bit_index] = value return self.bits def get(self, bit_index): if ((bit_index >= 0) and (bit_index < len(self.bits))): return self.bits[bit_index] else: return scenario_globals.ERROR_ def display(self): i = 0 while (i < len(self.bits)): print self.bits[i], i += 1 print '\n', global the_bits the_bits = BitsClass(16) # inside another function I have: global the_bits the_bits.set(index, value) but I get back: Traceback (most recent call last): ... File "scenario_sync.py", line 245, in get_discrete_data the_bits.set(index, value) AttributeError: 'DiscreteBits' object has no attribute 'set' There is I was also disappointed, I was hoping I could use BitsClass.print() instead of BitsClass.display(). Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
Static Variables in Python?
Is it possible to have a static variable in Python - a local variable in a function that retains its value. For example, suppose I have: def set_bit (bit_index, bit_value): static bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] bits [bit_index] = bit_value print "\tBit Array:" int i while (i < len(bits): print bits[i], print '\n' I realize this can be implemented by making bits global, but can this be done by making it private only internal to set_bit()? I don't want bits to be reinitialized each time. It must retain the set values for the next time it is called. Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
RE: Splitting a float into bytes:
-Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Simon Forman Sent: Wednesday, July 26, 2006 2:56 PM To: python-list@python.org Subject: Re: Splitting a float into bytes: Michael Yanowitz wrote: > Hello: > > For some reason I can't figure out how to split > a 4-byte (for instance) float number (such as 3.14159265359) > into its 4-bytes so I can send it via a socket to another > computer. > For integers, it is easy, I can get the 4 bytes by anding like: > byte1 = int_val & 0x00FF > byte2 = int_val & 0xFF00 > byte3 = int_val & 0x00FF > byte4 = int_val & 0xFF00 > But if I try to do that with floats I get: > >>> pi & 0xFF > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand type(s) for &: 'float' and 'int' > > Is there some easy way to get what the bytes of the float are? > > Thanks in advance: > Michael Yanowitz The struct module. (It also works for ints. ;-) ) http://docs.python.org/lib/module-struct.html HTH, ~Simon Thanks, but maybe I am missing something. If I use pack, doesn't it have to be unpacked at the other end to make sense? The data will be picked up on some other computer by some other application probably written in C or C++. Would it have to be rewritten to unpack the data? Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
Splitting a float into bytes:
Hello: For some reason I can't figure out how to split a 4-byte (for instance) float number (such as 3.14159265359) into its 4-bytes so I can send it via a socket to another computer. For integers, it is easy, I can get the 4 bytes by anding like: byte1 = int_val & 0x00FF byte2 = int_val & 0xFF00 byte3 = int_val & 0x00FF byte4 = int_val & 0xFF00 But if I try to do that with floats I get: >>> pi & 0xFF Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for &: 'float' and 'int' Is there some easy way to get what the bytes of the float are? Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
Functions, Operators, and Overloading?
Hello: Maybe I am missing something, but from what I've seen, it is not possible to overload functions in Python. That is I can't have a def func1 (int1, string1): and a def func1 (int1, int3, string1, string2): without the second func1 overwriting the first. However, operators can be overloaded. So can I define a new operator? If so, can I define func1 as an operator? (on the side, I have always wanted to define the ++ operator as +=1. Is that possible?) Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
Last used directory?
Hello: Is there a global or some trick I can use to have Python remember the last directory visited? What I mean is suppose I have this function: def get_filename(): """ Returns a filename selected from a Tkinter File Selection Dialog """ strFilename = tkFileDialog.askopenfilename(initialdir='.', filetypes=[('Python files','*.py'), ('All Files','*.*')]) return strFilename but instead of having initialdir='.' (current directory), I would like it set to the last visited directory, which can be from a previous run or even a previous day. Is that possible? If so how? Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
RE: Detecting 64bit vs. 32bit Linux
The one thing I observed (just an observation) is that: a) on 32-bit machines: sizeof(int) = 32 sizeof(long) = 32 b) on 64-bit machines: sizeof(int) = 32 sizeof(long) = 64 This in C and Python. Thanks in advance: Michael Yanowitz -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Lawrence D'Oliveiro Sent: Monday, July 10, 2006 3:11 AM To: python-list@python.org Subject: Re: Detecting 64bit vs. 32bit Linux In article <[EMAIL PROTECTED]>, dwelch91 <[EMAIL PROTECTED]> wrote: >I need to detect whether the operating system I am running on (not the >Python version) is 64bit or 32bit. One requirement is that I need to >include support for non-Intel/AMD architectures. The standard C way would be to check sizeof(void *). -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: SWIG problems with gcc and Cygwin?
Thanks. It now works for me in Cygwin. I would never have guessed to write it as a dll. Michael Yanowitz -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Norman Vine Sent: Tuesday, June 27, 2006 4:21 PM To: python-list@python.org Subject: Re: SWIG problems with gcc and Cygwin? "Michael Yanowitz"wrote > > >I am just trying out SWIG, but quickly ran into problems. > Using Cygwin gcc, I tried the following: > > 3)ran in cygwin: swig -i python example.i try 'swig -python example.i' > 4)Attempted to run on cygwin: ld -shared example.o example_wrap.o -o > _example.so try $ gcc -I/usr/include/python2.4 -L/lib/python2.4/config --shared example.c example_wrap.c -lpython2.4 -o _example.dll $ python Python 2.4.1 (#1, May 27 2005, 18:02:40) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> from example import * >>> get_time() 'Tue Jun 27 16:17:41 2006\n' HTH Norman -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: SWIG problems with gcc and Cygwin?
-Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Steve Holden Sent: Tuesday, June 27, 2006 2:55 AM To: python-list@python.org Subject: Re: SWIG problems with gcc and Cygwin? Michael Yanowitz wrote: > No response yet. The SWIG test works fine in Linux no problems. > However, I still have the problem in Cygwin. > Also, not sure if related but I do have a win32 Python 2.4.3 and > Cygwin Python 2.4.1. Not sure if there are any conflicts. Any advice > in making these two co-exist? > The only C/C++ compiler I have presently is Cygwin gcc. > I wouldn't claim to be an expert but it looks like you are missing libraries. Shouldn't you at least be loading -l c to get functions defined in libc? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden Possibly. I thought of that, but Linux doesn't require that I link in the C Library. Maybe Cygwin does or maybe a parameter is needed in gcc to do that automatically. The sample program (in http://www.swig.org/tutorial.html ) does not mention this. Thanks: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
RE: SWIG problems with gcc and Cygwin?
No response yet. The SWIG test works fine in Linux no problems. However, I still have the problem in Cygwin. Also, not sure if related but I do have a win32 Python 2.4.3 and Cygwin Python 2.4.1. Not sure if there are any conflicts. Any advice in making these two co-exist? The only C/C++ compiler I have presently is Cygwin gcc. Thanks in advance: Michael Yanowitz -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Michael Yanowitz Sent: Tuesday, June 20, 2006 3:39 PM To: python-list@python.org Subject: SWIG problems with gcc and Cygwin? Hello: I am just trying out SWIG, but quickly ran into problems. Using Cygwin gcc, I tried the following: 1) Created example.c (as given on http://www.swig.org/tutorial.html ) /* File : example.c */ #include double My_variable = 3.0; int fact(int n) { if (n <= 1) return 1; else return n*fact(n-1); } int my_mod(int x, int y) { return (x%y); } char *get_time() { time_t ltime; time(<ime); return ctime(<ime); } 2) Create interface file, example.i /* example.i */ %module example %{ /* Put header files here or function declarations like below */ extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); %} extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); 3)ran in cygwin: swig -i python example.i 4)Attempted to run on cygwin: ld -shared example.o example_wrap.o -o _example.so But got back many errors: example.o:example.c:(.text+0x55): undefined reference to `time' example.o:example.c:(.text+0x60): undefined reference to `ctime' example_wrap.o:example_wrap.c:(.text+0x9c): undefined reference to `strlen' example_wrap.o:example_wrap.c:(.text+0x12c): undefined reference to `strlen' example_wrap.o:example_wrap.c:(.text+0x1dd): undefined reference to `strcmp' example_wrap.o:example_wrap.c:(.text+0x494): undefined reference to `strcmp' example_wrap.o:example_wrap.c:(.text+0x748): undefined reference to `strlen' example_wrap.o:example_wrap.c:(.text+0x779): undefined reference to `strcpy' example_wrap.o:example_wrap.c:(.text+0x7a5): undefined reference to `strcmp' example_wrap.o:example_wrap.c:(.text+0x805): undefined reference to `strlen' example_wrap.o:example_wrap.c:(.text+0x877): undefined reference to `strncpy' example_wrap.o:example_wrap.c:(.text+0x8ab): undefined reference to `strcmp' example_wrap.o:example_wrap.c:(.text+0x8c9): undefined reference to `memset' example_wrap.o:example_wrap.c:(.text+0x948): undefined reference to `fputs' example_wrap.o:example_wrap.c:(.text+0x95d): undefined reference to `fputs' example_wrap.o:example_wrap.c:(.text+0x970): undefined reference to `fputs' example_wrap.o:example_wrap.c:(.text+0x9db): undefined reference to `PyString_Fr omFormat' example_wrap.o:example_wrap.c:(.text+0xa3a): undefined reference to `PyString_Fr omString' example_wrap.o:example_wrap.c:(.text+0xa68): undefined reference to `PyLong_From VoidPtr' example_wrap.o:example_wrap.c:(.text+0xa83): undefined reference to `PyTuple_New etc... Any idea what I am doing wrong or omitted? Of course when I then try to go into python and import example, I get: >>> import example Traceback (most recent call last): File "", line 1, in ? File "example.py", line 5, in ? import _example ImportError: No module named _example Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
SWIG problems with gcc and Cygwin?
Hello: I am just trying out SWIG, but quickly ran into problems. Using Cygwin gcc, I tried the following: 1) Created example.c (as given on http://www.swig.org/tutorial.html ) /* File : example.c */ #include double My_variable = 3.0; int fact(int n) { if (n <= 1) return 1; else return n*fact(n-1); } int my_mod(int x, int y) { return (x%y); } char *get_time() { time_t ltime; time(<ime); return ctime(<ime); } 2) Create interface file, example.i /* example.i */ %module example %{ /* Put header files here or function declarations like below */ extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); %} extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); 3)ran in cygwin: swig -i python example.i 4)Attempted to run on cygwin: ld -shared example.o example_wrap.o -o _example.so But got back many errors: example.o:example.c:(.text+0x55): undefined reference to `time' example.o:example.c:(.text+0x60): undefined reference to `ctime' example_wrap.o:example_wrap.c:(.text+0x9c): undefined reference to `strlen' example_wrap.o:example_wrap.c:(.text+0x12c): undefined reference to `strlen' example_wrap.o:example_wrap.c:(.text+0x1dd): undefined reference to `strcmp' example_wrap.o:example_wrap.c:(.text+0x494): undefined reference to `strcmp' example_wrap.o:example_wrap.c:(.text+0x748): undefined reference to `strlen' example_wrap.o:example_wrap.c:(.text+0x779): undefined reference to `strcpy' example_wrap.o:example_wrap.c:(.text+0x7a5): undefined reference to `strcmp' example_wrap.o:example_wrap.c:(.text+0x805): undefined reference to `strlen' example_wrap.o:example_wrap.c:(.text+0x877): undefined reference to `strncpy' example_wrap.o:example_wrap.c:(.text+0x8ab): undefined reference to `strcmp' example_wrap.o:example_wrap.c:(.text+0x8c9): undefined reference to `memset' example_wrap.o:example_wrap.c:(.text+0x948): undefined reference to `fputs' example_wrap.o:example_wrap.c:(.text+0x95d): undefined reference to `fputs' example_wrap.o:example_wrap.c:(.text+0x970): undefined reference to `fputs' example_wrap.o:example_wrap.c:(.text+0x9db): undefined reference to `PyString_Fr omFormat' example_wrap.o:example_wrap.c:(.text+0xa3a): undefined reference to `PyString_Fr omString' example_wrap.o:example_wrap.c:(.text+0xa68): undefined reference to `PyLong_From VoidPtr' example_wrap.o:example_wrap.c:(.text+0xa83): undefined reference to `PyTuple_New etc... Any idea what I am doing wrong or omitted? Of course when I then try to go into python and import example, I get: >>> import example Traceback (most recent call last): File "", line 1, in ? File "example.py", line 5, in ? import _example ImportError: No module named _example Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
RE: .py and running in Windows:
Thanks. XP looks to be the same as 2000. Works as expected now. Thank You. Not sure what this 'thread' issue is. I never specified a thread. I think perhaps though because I did open another message in this mailing list (to get the correct email address to send to), but I deleted all its contents i put it under that other thread, however there is no indication of a thread in Outlook email. I am sorry if it came up in another thread that was not my intention. -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Iain King Sent: Tuesday, June 13, 2006 9:48 AM To: python-list@python.org Subject: Re: .py and running in Windows: Andrew Gwozdziewycz wrote: > You'll have better results posting this to it's own thread. > He certainly should have, but since I've read it here anyway: > On Jun 13, 2006, at 9:29 AM, Michael Yanowitz wrote: > > > Hello: > > > > Presently in my Windows 2000 system, when I double-click on a > > .py file (open it) it automatically runs it in Python. I would > > like to change that behavour. That is fine for .pyc file, but > > for .py files, I would either like to have it run in Python but > > return to the Python shell prompt when finished rather than > > exit the shell. How do I do that? > > Or would it cause a problem (so that Python no longer works) if > > I change the default .py extension to open in an editor rather > > than execute it if I open it? > > In an explorer window, go to Tools->Folder Options Go to the File Types tab, find the PY extension, then click on Advanced* Select the 'open' action, and click Edit... change the 'Application used to perform action', inserting a '-i' between the exe and the first parameter. For example, I changed mine to: "C:\Python\python.exe" -i "%1" %* The exact line will depend on where your python.exe is. OK all the dialogs you've opened, then double click a .py file to test it. *I'm using WinXP, so the exact name of some of the buttons may be different for you. Iain -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
.py and running in Windows:
Hello: Presently in my Windows 2000 system, when I double-click on a .py file (open it) it automatically runs it in Python. I would like to change that behavour. That is fine for .pyc file, but for .py files, I would either like to have it run in Python but return to the Python shell prompt when finished rather than exit the shell. How do I do that? Or would it cause a problem (so that Python no longer works) if I change the default .py extension to open in an editor rather than execute it if I open it? Thanks: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
RE: Tkinter - changing existing Dialog?
Thanks. That is what I was looking for. The configure command (as you and John pointed out), should do what I need. The first response of starting a new thread was not what I was looking for. Michael Yanowitz -Original Message- In article <[EMAIL PROTECTED]>, Michael Yanowitz <[EMAIL PROTECTED]> wrote: >Hello: > > > I have a Tkinter GUI Dialog with many buttons and labels and text >widgets. >What I would like to do is, can I: > >1) Disable/deactivate/hide a button, text widget that is already drawn (and > of course the opposite enable/activate/show it)? . . . import Tkinter root = Tkinter.Tk() def actions(): print "Someone pushed the button." b.configure(state = Tkinter.DISABLED) b = Tkinter.Button(root, text = "Push me", command = actions) b.pack() root.mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Tkinter - changing existing Dialog?
Hello: I have a Tkinter GUI Dialog with many buttons and labels and text widgets. What I would like to do is, can I: 1) Disable/deactivate/hide a button, text widget that is already drawn (and of course the opposite enable/activate/show it)? 2) Change the text of a label or button that is already drawn? based on actions taken by the user. Can it be done without destroying the present dialog or the objects in it and creating a new one? Sorry for what probably is such a trivial and basic question. I just can't find the answer or know what the technical term for what I want to do is to search for it myself. Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
RE: how to change sys.path?
Is there something like a .pythoninitrc which can run whenever we start Python that can load a file with many sys.path.append(), etc? If not is there some way to modify the Python shell constructor and destructor? Thanks in advance: Michael yanowitz -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of per9000 Sent: Thursday, May 25, 2006 4:07 AM To: python-list@python.org Subject: Re: how to change sys.path? also se topic named 'problem(s) with import from parent dir: "from ../brave.py import sir_robin" ' I use this every day now: sys.path.append("../../py_scripts") best wishes, Per -- http://mail.python.org/mailman/listinfo/python-list
Python Version Testing Tool?
Hello: Is there a version testing tool available for Python such that I can check to see if my code will still run in versions 2.2, 2.3, 2.4.3, and 1.1 (for example) (or whatever) without having to install all these different versions on my computer? Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
RE: Tkinter Dialog Management problems:
> Hello: > >Below I have included a stripped down version of the GUI I am working > on. > It contains 2 dialog boxes - one main and one settings. It has the > following > problems, probably all related, that I am hoping someone knows what I am > doing wrong: > > 1) Pressing the Settings.. Button multiple times, brings up many > instances >of the Settings Panel. I just want it to bring up one. Is there an > easy >way to do that? In fact, the two windows you created are not dialogs; they're just windows. To turn a window into an actual "dialog", i.e basically to make it modal, you have to do the following operations (supposing your dialog window is named dlg and your main window in named root): ## Ensure only window can receive user events dlg.grab_set() ## Force Dialog to stay on top of main window dlg.transient(root) ## Wait for dialog to be destroyed root.wait_window(dlg) > 2) Pressing the Done button in the Settings Panel, just erases the Done > button >(and any other widgets in the Panel). It does not dismiss the Panel. > Pressing >the X button does work. What callback is that? Can I make the Done > button > call >that instead? How? This is not the way it works. In fact, what you did wrong is something that has been around for years in some Tkinter tutorial(s): you made your classes inherit from Frame. This is a Bad Idea: a Frame is not a window, but only a generic container. There are 2 classes for windows: Tk for the main window and Toplevel for all others. They both also act as containers, so you can do in them everything you do in Frames. So make your ScriptDialog inherit from Tk, your SettingsDialog inherit from Toplevel, remove all explicit creations of Tkinter.Tk or Tkinter.Toplevel and instantiate your classes instead. Then calling destroy on either on the dialogs will actually close the window. > 3) Pressing the Done button from the Main Panel has no effect? Why not? > It > used >to work (self.quit()). Again, I would like to call whatever is called > when the >X button (top Right corner) is pressed. This should work. BTW, your "done" method is not needed: creating the Button with command=self.quit works without problem. Thanks. That helped alot. However it leaves a couple very minor problems which I think I can live with. 1) It brings up an empty additional 'main window'. I have tried using the Tkinter.NoDefaultRoot() option, but run into other problems with other things not defined. NameError: global name '_default_root' is not defined Exception exceptions.AttributeError: "IntVar instance has no attribute '_tk'" in > ignored 2) By deriving the 'dialog' from Tk, existing calls to self.pack() no longer are valid, but they don't appear to be necessary. My only 'Tkinter tutorial' is what is included in Orielly's "Programming Python". Still looking for a good tutorial. I am not clear what the difference between Tk() and Toplevel() are. They seem totally interchangeable. -- http://mail.python.org/mailman/listinfo/python-list
Tkinter Dialog Management problems:
Hello: Below I have included a stripped down version of the GUI I am working on. It contains 2 dialog boxes - one main and one settings. It has the following problems, probably all related, that I am hoping someone knows what I am doing wrong: 1) Pressing the Settings.. Button multiple times, brings up many instances of the Settings Panel. I just want it to bring up one. Is there an easy way to do that? 2) Pressing the Done button in the Settings Panel, just erases the Done button (and any other widgets in the Panel). It does not dismiss the Panel. Pressing the X button does work. What callback is that? Can I make the Done button call that instead? How? 3) Pressing the Done button from the Main Panel has no effect? Why not? It used to work (self.quit()). Again, I would like to call whatever is called when the X button (top Right corner) is pressed. Thanks in advance: """ TkInter Test """ #** Imports * import os import sys import Tkinter from Tkinter import Tk, Frame, Button, Label, Entry, Scrollbar from Tkinter import Text, Checkbutton, IntVar import tkFileDialog from tkMessageBox import askyesno, showerror # *** runScript() * def runScript (strFilename): """ Executes Python script file """ if (VERBOSE): print strFilename, "is being imported" fileText = "" try: fptr = open (strFilename, 'r') fileText = fptr.read() fptr.close() except Exception, (errno): print "Exception in import of file:", strFilename, "- Errno = ", errno print (sys.exc_info()) showerror ('Error', 'Problem importing file - see console for details') else: fname = [strFilename[:-3].split('/')[-1]] for f in fname: __import__(f) # *** getGUIFilename *** def getGUIFilename(): """ returns a tkInter File Selection Dialog """ strFilename = tkFileDialog.askopenfilename(initialdir='.', filetypes=[('Python files','*.py'), ('All Files','*.*')]) return strFilename # *** ScenarioPlayerDialog class * class ScriptDialog(Frame): """ Script Dialog GUI class """ def __init__(self, parent=None): """ Script GUI class constructor """ Frame.__init__(self, parent) self.pack() self.commandRow = Frame(self) self.commandLabel = Label(self.commandRow, width=14, text="Python Command:") self.commandEnt = Entry(self.commandRow) self.commandRow.pack(side=Tkinter.TOP, fill=Tkinter.X) self.commandLabel.pack(side=Tkinter.LEFT) self.commandEnt.pack(side=Tkinter.RIGHT, expand=Tkinter.YES, fill=Tkinter.X) self.commandEnt.delete('0', Tkinter.END) self.commandEnt.pack(side=Tkinter.TOP, fill=Tkinter.X) buttonRow3 = Frame(self) doneBtn = Button(buttonRow3, text='Done', command=self.done) doneBtn.pack(side=Tkinter.RIGHT) buttonRow3.pack(side=Tkinter.BOTTOM, expand=Tkinter.YES, fill=Tkinter.X) buttonRow2 = Frame(self) runBtn = Button(buttonRow2, text='Run Script', command=self.playScript) runBtn.pack(side=Tkinter.LEFT) buttonRow2.pack(side=Tkinter.BOTTOM, expand=Tkinter.YES, fill=Tkinter.X) buttonRow1 = Frame(self) executeBtn = Button(buttonRow1, text='Execute Command') executeBtn.pack(side=Tkinter.LEFT) settingsBtn = Button(buttonRow1, text='Settings...', command=self.editSettings) settingsBtn.pack(side=Tkinter.LEFT) self.verbose = Tkinter.IntVar() Checkbutton(self,text="Verbose",variable=self.verbose, command=self.setVerbosity).pack(side=Tkinter.RIGHT) buttonRow1.pack(side=Tkinter.BOTTOM, expand=Tkinter.YES, fill=Tkinter.X) self.pack(expand=Tkinter.YES, fill=Tkinter.BOTH) self.theParent = parent def setVerbosity(self): """ Callback called when the 'Verbose' RadioButton is pressed """ global VERBOSE VERBOSE = self.verbose.get() def playScript(self): """ Callback called when the 'Run Script' button is pressed """ sFilename = getGUIFilename() if (VERBOSE): print "Running script file: ", sFilename runScript (sFilename) def editScript(self): """ Callback called when the 'Edit Script' button is pressed """ sFilename = getGUIFilename() editScript (sFilename) def executeCommand(self): """ Callback called when the 'Execute Command' button is pressed """ strCommand = self.commandEnt.get() if (VERBOSE): print strCommand, "is being executed" e
Shadow Detection?
Hello: Many times, people are warning things like "Don't use 'str' as a variable name as it will shadow the built in str function." Is there some way to determine if a string is already defined in some higher scope? Maybe something like if isdefined ('str'): print 'str is already defined, please choose another name' If not, would it be easy to write this? Thanks in advance: -- http://mail.python.org/mailman/listinfo/python-list
PYTHONPATH vs PATH?
Hello: Someone on my team tried out installing my Python code and found that setting PYTHONPATH does not work, but setting PATH environment variable works the way PYTHONPATH should. Is that how it supposed to be, or is that a bug or feature? -Original Message- (parts deleted) Subject: question on Python for windows I ran into trouble getting our software to work with the debuggers based on the user guide (updated after the CDROM). PYTHONPATH=.;..;DIRECTORY-CONTAINING-scenarios.py Where DIRECTORY-CONTAINING-PYTHON-SCRIPTS.py is the directory containing the Python scripts . this actually is the PATH, not PYTHONPATH, and is correct if you installed the Python scripts to the Python scripts folder, and then start up from the Python scripts folder, which I would say is normally not going to be the case. I installed our software to C:\sp I installed Python to E:\Python24 (the default is the same folder on C drive, I just changed the drive letter) when I installed the additional 3 packages they knew where Python was already and all I did was pick the default choices. but, the trouble was that the PYTHONPATH using . and .. does not find the Python scripts folder if you are in C:\sp I used this to make it work (based on Python in E:\Python24 and in C:\sp) set PATH=%PATH%;E:\Python24;E:\Python24\Scripts now I start in my C:\sp folder (where the config.txt file is) and everything works fine I did try just setting PYTHONPATH but it is actually PATH that matters. If you don't include the Python base and Scripts folders in the PATH it does not work. I verified that not setting PYTHONPATH but just set PATH to include the Python base and scripts folders does work. Thanks in advance: -- http://mail.python.org/mailman/listinfo/python-list
Python function returns:
I am still new to Python but have used it for the last 2+ months. One thing I'm still not used to is that functions parameters can't change as expected. For example in C, I can have status = get_network_info (strIpAddress, &strHostname, &nPortNumber) where this fictitious function returns a status, but also returns modified values for a hostname and a port number. In Python, there does not seem to be an easy way to have functions return multiple values except it can return a list such as: strHostname, nPortNumber, status = get_network_info (strIpAddress, strHostname, nPortNumber) Am I missing something obvious? Is there a better, or more standard way to return values from functions? Thanks in advance: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
PyLint results?
Hello: I ran the new pylint and my code and I had a few questions on why those are warnings or what I can do to fix them: 1) W: 0: Too many lines in module (1587) Why is 1587 considered too many lines? Would there be necessarily be an advantage to split it up into 2 or 3 files? Can I up the limit? 2) C: 0: Missing required attribute "__revision__" What is this? Is that for CVS? I don't use CVS (we use SVN). I have not seen any sample code which includes this tag yet. But if I include __revision 1.0 somewhere in the code it will remove that warning? 3) W:230:readDiscreteData: Using the global statement What is wrong with using the global statement? I know the use of Globals should be discouraged, but often they can't be avoided. Suppose I have a constant. In C or C++, I could just use a #define and it would be known throughout the whole file. In Python, there isn't a similar construct, so rather than creating a large parameter list, of constants, I like to use globals. 4) W:261:getDiscreteData: Catch "Exception" What is wrong with that? 5) R:547:readDiscreteData: Too many branches (28/12) Python doesn't have the switch/case statements that C/C++ have. So I could have a large block if/elif/else statements. Is there any way to avoid that? 6) R:722:waitDiscretes: Too many local variables (38/15) That's new to me. What is wrong with too many local variables? Can anything be done to improve that besides having too many globals? 7) W:933:sendStringToSocket: Redefining name 'nPortNumber' from outer scope (line What is wrong with using the same variable name in a function that is used by its caller? 8) W:995:sendStringToSocket: Used builtin function 'map' Is that a problem? Plus many other warnings about my naming convention or unused variables which I will ignore at this time. I did find it to be a very useful too any how in cleaning up my code. I raised my code rate from about -8 to about +7. Thanks: Michael Yanowitz -- http://mail.python.org/mailman/listinfo/python-list
RE: proposed Python logo
How about having something from Monty Python in the logo rather than something snakelike. Python was named after Monty Python and not the snake. Snakes also don't appear friendly to me. I used to have rats as pets. Snakes are murderers of rats. Which I do find strange that there is a rat on the cover of "Learning Python" by Oreilly but a Python snake on the "Progamming Python" by Oreilly book. I think something from Monty Python (I haven't watched it recently to know what would be ideal) would be more appropriate than an ugly reptile which is usually associated with evil and our reason for leaving the Garden of Eden. (Take me serious or not, I don't care, this is just my opinion, but with a little humor.) Thanks in advance: -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Ant Sent: Friday, April 21, 2006 6:31 AM To: python-list@python.org Subject: Re: proposed Python logo Sorry dude, but it looks like a hairdryer! Imagine it at 16x16 pixels or smaller, and it'll look like little more than a circle with two sticks. The current image scales well. I think that the current logo is fine. Much more professional than the old image. The + formation is positive enough, and it has a yin-yang feel to it which to me conjures up the image of balance, not divisiveness. JM2PW I would like to see a Python Logo -- http://mail.python.org/mailman/listinfo/python-list
RE: Python2CPP ?
> First of all: why do you want to translate pythont to C++? > > Anyway, this has a C back-end: > http://www.pypy.org > > Szabi Thanks. I want to translate from Python to C++ for a few reasons: 1) Curiosity. I would like to see how well the translation goes. 2) Efficiency. It is alot quicker to code something in Python. If I can write it in Python and auto-convert it to C++. I would save time coding. 3) Education. I would learn more about Python, C++, their similarities and differences. 4) Other. Just want to know how well Language translators work these days. I have seen Fortran2C and Pascal2C translators in the past. Would like to see how well these work with Python. Thanks in advance: -- http://mail.python.org/mailman/listinfo/python-list
Python2CPP ?
Hello: One topic that has always interested me are the Language translators. Are there any that convert between Python and C++ or Python and Java? I remember seeing one that converts from Python to or from Perl but couldn't find it on a quick google search. I did find a Python2C http://sourceforge.net/projects/p2c/ and I found: http://www.strout.net/python/ai/python2c.py which are obviously incomplete. I know there have been many discussions recently regarding C and C++. I am (or is it - was?) a C/C++ programmer for over 15 years. Just started with Python as we need to write come quick code in script form which can be generated and run through an interpreter. If not could there be a converter from Python to/from Language X and from Language X to/from C or C++? In another thread mentioning a decompiler. Perhaps Python to Assembly and Assembly 2 C? Thanks in advance: -- http://mail.python.org/mailman/listinfo/python-list
RE: "The World's Most Maintainable Programming Language"
-Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Peter Hansen Sent: Thursday, April 06, 2006 8:47 AM To: python-list@python.org Subject: Re: "The World's Most Maintainable Programming Language" Mirco Wahab wrote: > Hi Ralf >>So we should rename Python into Cottonmouth >>to get more attention. > > No, always take some word that relates to > something more or less 'feminine', its about > 96% of young males who sit hours on programming > over their beloved 'languages' ;-) > > Pythia? (http://en.wikipedia.org/wiki/Pythia) I guess that would make our motto "Pythia: now you're programming with ethylene." -Peter At-least Pythetic isn't a word (yet). -- http://mail.python.org/mailman/listinfo/python-list
tuple syntax ',' (ending in comma?)
Hello: I am still relatively new to Python. I am confused by the syntax for tuples. I had: thread.start_new_thread(read_data_thread, (strDataFilename)) and got back the following error: File "scene.py", line 256, in readData thread.start_new_thread(read_data_thread, (strDataFilename)) TypeError: 2nd arg must be a tuple The way I fixed this error was I added an extra , (comma) to the tuple: thread.start_new_thread(read_data_thread, (strDataFilename,)) I am just confused by the syntax. I am used to a comma meaning that there should be another parameter after the comma and if no additional parameter the comma would not be necessary. Thanks in advance: -- http://mail.python.org/mailman/listinfo/python-list
RE: Remove integer from float number
Sorry about the Top Posting that I did before. It is just the style I am used to using, and I didn't realize that it was different here. I won't do it again. -- http://mail.python.org/mailman/listinfo/python-list
RE: Remove integer from float number
Sorry, got it backwards: def printDecimal(number): if (number >= 0): print number - int(number) else: print int(number) - number -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Michael Yanowitz Sent: Thursday, March 23, 2006 5:21 PM To: python-list@python.org Subject: RE: Remove integer from float number how about this solution: def printDecimal(number): if (number < 0): print number - int(number) else: print int(number) - number -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Grant Edwards Sent: Thursday, March 23, 2006 5:11 PM To: python-list@python.org Subject: Re: Remove integer from float number On 2006-03-23, Arne Ludwig <[EMAIL PROTECTED]> wrote: > With that terse description and the subject line I would interpret the > OP like so: > >>>> print re.sub(".*\.",".","0.666") > .666 >>>> print re.sub(".*\.",".","123.666") > .666 Or if you're allergic to regular expressions: >>> print "." + "0.666".split(".")[-1] .666 >>> print "." + "123.666".split(".")[-1] .666 >>> -- Grant Edwards grante Yow! Yow! It's a hole at all the way to downtown visi.comBurbank! -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: Remove integer from float number
how about this solution: def printDecimal(number): if (number < 0): print number - int(number) else: print int(number) - number -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Grant Edwards Sent: Thursday, March 23, 2006 5:11 PM To: python-list@python.org Subject: Re: Remove integer from float number On 2006-03-23, Arne Ludwig <[EMAIL PROTECTED]> wrote: > With that terse description and the subject line I would interpret the > OP like so: > print re.sub(".*\.",".","0.666") > .666 print re.sub(".*\.",".","123.666") > .666 Or if you're allergic to regular expressions: >>> print "." + "0.666".split(".")[-1] .666 >>> print "." + "123.666".split(".")[-1] .666 >>> -- Grant Edwards grante Yow! Yow! It's a hole at all the way to downtown visi.comBurbank! -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: struct size confusion:
Thanks for your and everyone else's feedback. I got it to work now by prefixing the PACK_FORMAT with "!". I previously thought I could only use the "!' with the unpack. I still don't fully understand the byte allignment stuff (I am sure I will get it eventually), but I am content that it is working now. -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Fredrik Lundh Sent: Wednesday, March 22, 2006 9:28 AM To: python-list@python.org Subject: Re: struct size confusion: Michael Yanowitz wrote: >I am relatively new to Python and this is my first post on > this mailing list. > >I am confused as to why I am getting size differences in the following > cases: > > >>> print struct.calcsize("I") > 4 > >>> print struct.calcsize("H") > 2 > >>> print struct.calcsize("HI") > 8 > >>> print struct.calcsize("IH") > 6 > >Why is it 8 bytes in the third case and why would it be only 6 bytes > in the last case if it is 8 in the previous? because modern platforms tend to use an alignment equal to the size of the item; 2-byte objects are stored at even addresses, 4-byte objects are stored at addresses that are multiples of four, etc. in other words, HI is stored as 2 bytes H data plus 2 bytes padding plus four bytes I data, while IH is four bytes I data, no padding, and 2 bytes H data. >I tried specifying big endian and little endian and they both have > the same results. are you sure? (see below) > I suspect, there is some kind of padding involved, but it does not > seem to be done consistently or in a recognizable method. the alignment options are described in the library reference: http://docs.python.org/lib/module-struct.html default is native byte order, native padding: >>> struct.calcsize("IH") 6 >>> struct.calcsize("HI") 8 to specify other byte orders, use a prefix character. this also disables padding. e.g. >>> struct.calcsize("!IH") 6 >>> struct.calcsize("!HI") 6 -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
struct size confusion:
Hello: I am relatively new to Python and this is my first post on this mailing list. I am confused as to why I am getting size differences in the following cases: >>> print struct.calcsize("I") 4 >>> print struct.calcsize("H") 2 >>> print struct.calcsize("HI") 8 >>> print struct.calcsize("IH") 6 Why is it 8 bytes in the third case and why would it be only 6 bytes in the last case if it is 8 in the previous? I tried specifying big endian and little endian and they both have the same results. I suspect, there is some kind of padding involved, but it does not seem to be done consistently or in a recognizable method. I will be reading shorts and longs sent from C into Python through a socket. Suppose I know I am getting 34 bytes, and the last 6 bytes are a 2-byte word followed by a 4-byte int, how can I be assured that it will be in that format? In a test, I am sending data in this format: PACK_FORMAT = "HHHI" which is 34 bytes However, when I receive the data, I am using the format: UNPACK_FORMAT = "!HHHHI" which has the extra H in the second to last position to make them compatible, but that makes it 36 bytes. I am trying to come up with some explanation as to where the extra 2 bytes come from. Thanks in advance: -- http://mail.python.org/mailman/listinfo/python-list