Re: [Tutor] eval and exec
I'm having trouble understanding the difference between eval and exec. eval evaluates an *expression* - that is something that returns a value. exec executes a piece of code, it need not return a value. eval is slightly safer than exec (but not much). Some examples: print 'hello' # use exec for this 6+7-9/3# use eval for this myfunction(42) # use eval for this to make eval useful you need to assign the result to a variable: res = eval('6+7-9/3') but exec is just executed on its own: exec('print hello') Both are extremely dangerous functions from a security and maintenance/reliability pouint of view and should be used very rarely. Was there anything more specific you wanted to know? HTH Alan G. ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] eval and exec
Brian van den Broek said unto the world upon 2004-12-04 04:28: Marilyn Davis said unto the world upon 2004-12-04 01:37: Hello Tutors, I'm having trouble understanding the difference between eval and exec. Can anyone explain it to me please? Marilyn Davis Hi Marilyn, does this help? SNIP Darn. I left a few things that might help: exec(a = 2 + 40) exec(print a) 42 eval('a') 42 As before, exec(a = 2 + 40) runs the code a = 2 + 40, making 'a' point to 42. Thus, exec(print a) is synonymous with: print a *in the interpreter* eval('a') also gives 42. This is because, *in the interpreter* a 42 But, run this script: exec('a=42') exec('print a') exec(print eval('a') == eval('21 * 2')) eval('a') a OUTPUT: === RESTART === 42 True *In a script*, a doesn't produce any output at all. This script does print 'True' because of the third line. It reads: Run the sting print eval('a') == eval('21 * 2') as code. So, print the expression you get by putting an '==' between the results of evaluating the expressions a and 21 * 2. Thus, print an expression equivalent to 42 == 42. And its almost 5am and I've begun to worry I'm muddying the waters, rather than helping. It is to be hoped that someone will clean up any messes I have made. (Ken? Danny? . . . .) Best, brian vdB ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Global presets ?
You are on the right track. Put your common definitions in a configuration module like this: # Config.py arch_data_dir='/home/dave/mygg/gg1.3/arch_data' data_dir='/home/dave/mygg/gg1.3/data' Then in client code, import Config. When you use the names defined in Config you have to prefix them with the module name like this: import Config print Config.data_dir Alternately you can use either of these forms: # Get a couple of names from Config into our global namespace from Config import arch_data_dir, data_dir or this: # Get *all* names defined in Config into our global namespace from Config import * to make the bare names available in the client. Kent Dave S wrote: Hi there, I have some common data directories, like /home/dave/mygg/gg1.3/logs /home/dave/mygg/gg1.3/data /home/dave/mygg/gg1.3/datacore /home/dave/mygg/gg1.3/arch_data which increasing numbers of scripts are accessing. At the begining of each script I end up putting in declarations like arch_data_dir='/home/dave/mygg/gg1.3/arch_data' data_dir='/home/dave/mygg/gg1.3/data' over over. This is OK until I want to move a directory Somewhere I read about importing a script to define common globals for all the scripts that import it. I tried this, and failed - the variable was only valid for the module, to be expected really :) Can anyone make a suggestion howto set up common global presets. Cheers Dave ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Global presets ?
Thanks Guys, They are both good ways of getting round my problem, I appreciate your input will have a play. Cheers Dave :-) :-) :-) :-) ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple RPN calculator
I didn't get the attachment, can you try again? Thanks, Kent Just Incase wrote: Hi Tutors, I am new to programming and so don't know anything much, yet. I am having problem with implementing a simple RPN calculator in python. I have tried editing some other programs I have been referenced to earlier and I was able to play around with hoping to get something out of it but the problem I have is that I don't know how to make it request for input(s) of say a simple math like 1 2 3 4 5 + - * /. Help please with any suggestions or any other better and easier way of implementing a RPN calculator. Thank you, Justice The following is what I have: Do you Yahoo!? The all-new My Yahoo! http://my.yahoo.com What will yours do? ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
[Tutor] OT: test
sorry it seems like my email address is mangled in my earlier post. resending new message with address in sig. -- Using PC-Pine 4.61 email: erimendz_at_bluebottle.com reply to: erimendz_at_fastmail.fm ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Address book sort of
Couldn't tell if this got sent, so I'm re-sending. Apologies for duplicates: Well, one option is to use pickle (or cPickle, preferrably) to dump the python objects to a file: from cPickle import load, dump def save(fname,addressbook): file = open(filename,'w') dump(addressbook,file) file.close() return def read(fname): file = open(filename) addressbook = load(file) file.close() return addressbook The advantage of pickle is that you don't have to decide on a text format for your data -- it just dumps and then reloads the python code. You can waste a lot of time deciding on a text format, implementing the readers/writers, etc. Rick --- Eri Mendz [EMAIL PROTECTED]@bluebottle.com wrote: Dear Tutor, I like to know what is the proper procedure (is algorithmn the right term?) in creating data in a program, write it to file, close the app then retrieve the data when run again. Basically, I'm trying to simulate a simple address book (well not really for the datas are just names for now) and so far have created the basic menu interface. It is console base so forget gui. I ask user input and store it in a list. There are menus to change, delete the data, and to save the data list in file. I use cPickle for this and have verified the file is created by checking in my $PWD. I want to retrieve that data when program is run again. What to add in my code? I thought not to post the code but explain it as above. What i want: when program is run again, the saved data is loaded when user selects option 1 below. Of course the first time it is run, the list is empty. def print_options(): print ''' Options: [1] - Print content of list [2] - Add name to list [3] - Delete name from list [4] - Change name in list [5] - Save list to file [P] - Print this menu [Q] - Quit ''' -- Regards, Eri Mendz Using PC-Pine 4.61 -- Using PC-Pine 4.61 ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor = Rick Muller [EMAIL PROTECTED] __ Do you Yahoo!? Yahoo! Mail - Find what you need with new enhanced search. http://info.mail.yahoo.com/mail_250 ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Global presets ?
Alan Gauld wrote: have you considered making the root directory an environment variable? That way you can read the value (os.getenv) at the start of the script. And if you ever need to move the structure you can simply change the environment value. It also means different users can use their own structures by defining their own environment value... # File myvars.py value1 = 42 value2 = 'spam' Got ya so far .. # # File: prog1.py import myvars localvar = myvars.value1 myvars.value2 = 'Alan' Never thought of setting 'myvars.value2 = 'Alan'' I guess this would just set the variable in the myvars namespace since it could not change myvars.py itself. ## # File prog2.py import myvars newvar = myvars.value2 With you ... print myvars.value1 - 27 Have I misunderstood, should this not be 42 ? Typo or me not understanding ? ## Does that help? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
[Tutor] Broblem with exiting a Tkinter app
Hi all , I got 2 questions for you guys. The fist question: I wrote small Tkinter app while laerning about the Radiobutton widget, and I added a Quit button, like this: bb=Button(root, text=Quit, fg=BLUE, command=root.quit).pack() When I pressed the button the app crashed and I got an error message ( program is not responding ) from windows. I tried to add a frame to the program and then exit the frame, like this: bb=Button(f, text=Quit, fg=BLUE, command=f.quit).pack() But the result is the same... Here is the full source code of the app: from Tkinter import * import sys root=Tk() f=Frame(root) text=Label(root, text=how old are you?).pack() v = IntVar(root) Radiobutton(f, text=less than 13, variable=v, value=1).pack(side=LEFT) Radiobutton(f, text=13-20, variable=v, value=2).pack(side=LEFT) Radiobutton(f, text=20-40, variable=v, value=3).pack(side=LEFT) Radiobutton(f, text=40+, variable=v, value=4).pack(side=LEFT) bb=Button(f, text=Quit, fg=BLUE, command=f.quit).pack() f.pack() root.mainloop() The second question: I dont understand how to get the input fron the radio buttons... It doesnt returns any value, so how can the app know what the user chose? Thanks!! ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accuracy of time.sleep()
[Dave S [EMAIL PROTECTED]] OK I may be pushing it, ;-) Yup wink. I need a script to sleep from any point to 8:05AM when in needs to re-start. So I calculate the number of seconds with the following def secs_till_805(): # Returns the number of seconds till 8:05AM secs_5min=5*60 secs_24hr=24*60*60 secs_8hr=(8*60*60)+secs_5min secs_8hr_24hr=secs_24hr-secs_8hr hours=int(strftime('%H')) mins=int(strftime('%M')) secs=int(strftime('%S')) Ouch. Never try to pick apart the current time by computing it more than once. For example, if the time at the start of that block is just a fraction of a second before 9AM, it's quite possible you'll end up with hours==8 and mins==secs==0 (because the time is 8:59:59 at the time you do the %H business, and but it's 9:00:00 by the time you get to %M). That would throw you off by an hour. The same kind of thing can happen a little before the (any) minute changes too. sec_left=secs_24hr-((hours*60*60)+(mins*60)+secs) # If we are before 8:05, then ... if sec_leftsecs_8hr_24hr: return sec_left-secs_8hr_24hr # If we are after 8:05, then ... return sec_left+secs_8hr Here's a different way, computing current time only once, and using the datetime module to do all the fiddly work: def seconds_until(h, m=0, s=0): from datetime import datetime, time, timedelta target_time = time(h, m, s) now = datetime.now() target = datetime.combine(now.date(), target_time) if target now: target += timedelta(days=1) diff = target - now return diff.seconds + diff.microseconds / 1e6 This returns seconds as a float, which is good (Python's time.sleep() can make sense of floats, and sleep for fractional seconds). Then I ... sleep(secs_till_805()) With the above, you'd do time.sleep(seconds_until(8, 5)) instead. I expected the script to re-start 2-3 seconds after 8:05, python reloading after a long sleep etc, what I get is the script restarting at 08:04.55, earlier ??? You'll probably never know why for sure. Python calls platform C library gimmicks to sleep, which in turn invoke operating system facilities. Understanding the whole story would require that you understand everything all of those do. [later] It must be cummulative error over 10s of thousands of seconds. Maybe. Its a bodge ( cron or at are better) but I suppose I could calculate seconds to 8:05 sleep(seconds*0.95), re calculate secs to 8:05 sleep(seconds) which should reduce the error to almost zip. That's also a good idea in order to avoid surprises due to crossing daylight time boundaries (assuming you mean 8:05 according to the local wall clock). Here's a function building on the above: def sleep_until(h, m=0, s=0): from time import sleep while True: delay = seconds_until(h, m, s) if delay 10.0: sleep(delay) return else: sleep(delay / 2) That is, it cuts the sleep time in half repeatedly, until less than 10 seconds remain. It can sleep for hours at a time, but as the target time approaches it wakes up more frequently. This should keep the program loaded in memory as the target time gets near. ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] eval and exec
On Sat, Dec 04, 2004, Alan Gauld wrote: I'm having trouble understanding the difference between eval and exec. eval evaluates an *expression* - that is something that returns a value. ... Both are extremely dangerous functions from a security and maintenance/reliability pouint of view and should be used very rarely. True enough, but useful upon occassion. In particular I've had a question on the back burner for a while. Suppose I have a dictionary of database instances, dbtables, keyed on table name, and I want a general way of creating variables with the name of the table so I'm not accessing the dictionary. Would something like this work: # dbtables is already built for table in dbtables.keys(): exec(%s = dbtables['%s'] % (table, table)) Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ My brother sent me a postcard the other day with this big satellite photo of the entire earth on it. On the back it said: ``Wish you were here''. -- Steven Wright ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Broblem with exiting a Tkinter app
On Sat, 04 Dec 2004 14:38:06 -0500, Kent Johnson [EMAIL PROTECTED] wrote: Mark Kels wrote: Hi all , I got 2 questions for you guys. The fist question: I wrote small Tkinter app while laerning about the Radiobutton widget, and I added a Quit button, like this: bb=Button(root, text=Quit, fg=BLUE, command=root.quit).pack() When I pressed the button the app crashed and I got an error message ( program is not responding ) from windows. I tried to add a frame to the program and then exit the frame, like this: bb=Button(f, text=Quit, fg=BLUE, command=f.quit).pack() But the result is the same... Here is the full source code of the app: from Tkinter import * import sys root=Tk() f=Frame(root) text=Label(root, text=how old are you?).pack() v = IntVar(root) Radiobutton(f, text=less than 13, variable=v, value=1).pack(side=LEFT) Radiobutton(f, text=13-20, variable=v, value=2).pack(side=LEFT) Radiobutton(f, text=20-40, variable=v, value=3).pack(side=LEFT) Radiobutton(f, text=40+, variable=v, value=4).pack(side=LEFT) bb=Button(f, text=Quit, fg=BLUE, command=f.quit).pack() f.pack() root.mainloop() This program works fine for me on Win2K. How are you running the program? The second question: I dont understand how to get the input fron the radio buttons... It doesnt returns any value, so how can the app know what the user chose? Read the value from the variable associated with the buttons - v. For example if you define def quit(): print 'You chose button', v.get() f.quit() and change the command on bb to command=quit, the program will print the selection value on exit. (You have to define quit before bb or you will get a NameError.) Kent Thanks!! ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor Thats weird... Suddenly the program started to work fine :-) ! Thank you very much for your time. ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple RPN calculator
I am new to programming and so don't know anything much, yet. I am having problem with implementing a simple RPN calculator in python. I'm not surprised. While an RPN vcalculator is one of the easier calculators to build its not exactly trivial. It sounds like the kind of thing an ambitious (or optimistic?) teacher might set for homework... Would I nbe right? to make it request for input(s) of say a simple math like 1 2 3 4 5 + - * /. Look at raw_input() But if you are that much of a beginner you need to take several steps back and try one of the tutorials, they all cover raw_input fairly early on... And finally doesn't RPN put the operators first? Or is it me thats getting confused fromtoo much Lisping recently?... Help please with any suggestions or any other better and easier way of implementing a RPN calculator. Python is a fine place to start building RPN calculators. But thee are so many available that I van't help suspecting homewoprk here, and we can only offer limited guidance in that case. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accuracy of time.sleep()
It must be cummulative error over 10s of thousands of seconds. Just so, and depends on howm many other processes are running, how busy the CPU is etc. bodge ( cron or at are better) but I suppose I could calculate seconds to 8:05 sleep(seconds*0.95), re calculate secs to 8:05 sleep(seconds) which should reduce the error to almost zip. Thats the approach I suggest in my otther email :-) Alan G ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hello.py: line 1: print: command not found
Max, Thanks for your reply. I have already tried to set my shebang to /usr/bin/env python. But for everyone's benefit. I've tried it again, and the same behavior persists. As another confirmation that this is not a file permission problem, I should say that I can run hello.py as root, and get the expected result. I can also run it as normal user, from /usr/lib/python and get the proper behavior. It is from /home/user/hello.py that this error persists. I included below the attribute flags from ls-l. Thanks again for your help, any ideas are appreciated. Cullen file attributes [EMAIL PROTECTED]:~ ls -l hello.py -rwxrwxrwx 1 nooseisloose users 42 2004-12-04 18:36 hello.py /file attributes On Dec 5, 2004, at 00:53, Cullen Newsom wrote: Hello List, Here is my Error: hello.py: line 1: print: command not found Here is my cat hello.py: cat hello.py [EMAIL PROTECTED]:~ cat hello.py #!/usr/bin/python print Hello, world! [EMAIL PROTECTED]:~ /cat hello.py I know this is a Linux question (or SuSE question) as much as a python question, but I do not think there is a more appropriate place to ask this question, and hopefully it will help save someone some time and frustration, especially since a person new to Python might well believe it to be a problem with Python. Anyone know the proper thing to set, or change? Thanks. Cullen How are you running your script? Are you doing a basic python Hello.py, or have you set Hello.py to +x and are you relying on the first line to tell the script where the Python interpreter is? If it's answer #2, you should try replacing your first line with #!/usr/bin/env python , and see what happens. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine? __ Do you Yahoo!? Yahoo! Mail - now with 250MB free storage. Learn more. http://info.mail.yahoo.com/mail_250 ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor