Re: [Tutor] information
Nice to have you around! This list is to help with any problem you may be having with the language and how to solve certain problems. So, if you have specific questions, please do post them. And be warned, no one here would like to do any homework for you. Enjoy you stay Dom - Original Message - From: issa karambal To: tutor@python.org Sent: Wednesday, September 06, 2006 10:47 AM Subject: [Tutor] information himy name is ISSA, from Chad, I am learning python, I want to have on tutor to help me to understand this good language of programmationplease, I am looking for the good answer from youregards and thanks Yahoo! Messenger with Voice. Make PC-to-Phone Calls to the US (and 30+ countries) for 2¢/min or less. ___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how do I find where my program is installed?
hello, I created an executable using py2exe and innosetup for windows. I need to figure out where the user has installed my program so that I can direct the program to the installation files that it needs to run. The location of the installation files - I assume you mean some kind of config file? - should not be hard coded in that way, much better to store the files in a flexible location and use an environment variable or registry setting to point to it. when this file type is double clicked my application is launched. when this happens my program thinks the working directory is the directory where that registered file was located... Interesting, I didn't know Windows would do that. the working directory back to the installation directory... but where is this? If the current working directory is not set to the home location of your program but rather to the target file then I don't know! Another good reason for setting an environment variable or registry entry. However the sys module contains two functions that might help: exec_prefix() and executable() Not sure how they play with py2exe however. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for a few commands
Replying to the List The trick is to know either that Fred works at Pythonware, or that his nickname is the effbot... :-) http://effbot.org/downloads/ Sorry, neither are intuitively obvious... but he has lots of goodies on his site, worth perusing the list. And Fred's code is usually of a very high standard - ie it just works! Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld - Original Message - From: Chris Hengge [EMAIL PROTECTED] To: Alan Gauld [EMAIL PROTECTED] Sent: Thursday, September 07, 2006 5:25 AM Subject: Re: Looking for a few commands Where is Fred's site? lol... I've been looking for it and not finding anything like this. Finally Fred Lundh has a console library that tries to pull all this together into a single platform independant module, but its not a standard library module(yet) and you have to download it from Fred's site. Frankly if I need to do detailed screen manipulation in Python I usually just bite the bullet and build a GUI - its easier. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Running DOS jobs in batch
Hi I am trying to write a PYTHON script that automates the running of an application program MX200510.EXE under XP Pro via a DOS window. This file is in directory C:\Program Files\CMG\IMEX\2005.10\EXE The command line arguments are MX200510.EXE -f temp.dat -wd C:\Projects\Vitol\New business\Octon\simulation\full field model\0608 My Python script is as follows: # # Test Python script to submit IMEX jobs # import os # # Start of MAIN program # # Initialisation work_dir=r'C:\Projects\Vitol\New business\Octon\simulation\full field model\0608' imex_dir=r'C:\Program Files\CMG\IMEX\2005.10\EXE' imex_fil='temp.dat' imex_args=('mx200510.exe','-f',imex_fil,'-wd',''+work_dir+'') nscen=2 # Check IMEX directory and files exist os.chdir(imex_dir) L=os.listdir(imex_dir) for item in L: print item # Change directory to working directory os.chdir(work_dir) # Loop over N scenarios for n in range(1,nscen): # Spawn IMEX job and wait for completion os.spawnv(os.P_WAIT, imex_dir, imex_args) The output from this script is ck9700.dll libguide40.dll mx200510.exe mx200510en.chm mx200510sp.chm Traceback (most recent call last): File C:/Projects/Vitol/New business/Octon/simulation/full field model/0608/test_imex.py, line 39, in -toplevel- os.spawnv(os.P_WAIT, imex_dir, imex_args) OSError: [Errno 2] No such file or directory I tried following the ARGS into the os module using the debugger but this did not help much, presumably because OS is precompiled. Not sure which file or directory Python is unhappy about - LISTDIR shows that the EXE file and path exist so presumably it's something in the way I set up the argument list. All suggestions gratefully received! Thanks Alun Griffiths ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Thread forever ?
Dear Tutors, ### from threading import Thread import sys import time # This thread would read lines from a # barcode scanner class ComThread(Thread): def __init__(self): Thread.__init__(self) def run(self): while 1: time.sleep(2) print time.ctime() com = ComThread() com.start() # Main loop for handling the keyboard while 1: s = raw_input() if s == '': continue elif s in 'qQ': # may I com.Terminate() here sys.exit() # when I goes out here # the comthread is just running. else: try: num = int(s) print 'mod qty=%d' % num except: pass # When this program leaves from the while loop, it doesn't terminate the comreader thread. It can be terminated with the 'X' at the topright corner, but it seems to be not the best way. Yours sincerely, __ Janos Juhasz ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Some questions about my yen-USD.py
I've just finished a script for converting Yen to USD, and vice-versa. A simple, even silly thing to do (a friend asked me to write it for him--probably just to humor me), but I have tried to build in some bells and whistles. In doing so, some questions arose. If some of you Tutors could take look at my script, yen-USD.py, I'd greatly appreciate it. http://www.rcblue.com/Python/yen-USD.txt My questions: (1) Have I handled possible user-errors OK? (2) Is my roundingN() function OK? Is there a better way to write it? Will the line n = round(float(n)*(10**rounding))/(10**rounding) get me into trouble with the flakiness of float(n)? In testing I didn't find any problems, but .. (3) Is there a better name for roundingN()? I don't like it, but can't think of a better one. (4) I wanted to call closingMessage() in main(), but in some cases, if it's in main() it gets 2 successive calls. I can't figure out why. Would IDLE's debugger be of use here? (I've never used it before.) I haven't been able to find up-to-date IDLE help. Thanks, Dick Moores ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for a few commands
Thanks for the details, I see several code bits I'll have to play with. I got the screen clearing bit no problem, thanks for that one. I'm still not used to being able to just use c libraries. I don't actually have a need to draw the cursor all over the screen for any practical application either personal or work, but I've got a bit of a fascination with linux terminals being able to draw progress bars or busy animations and figured I'd have a little fun. :] I came across curses which looks to be included in activepython so that might be of some use for my linux programming. Thanks again. On Thu, 2006-09-07 at 08:44 +0100, Alan Gauld wrote: Replying to the List The trick is to know either that Fred works at Pythonware, or that his nickname is the effbot... :-) http://effbot.org/downloads/ Sorry, neither are intuitively obvious... but he has lots of goodies on his site, worth perusing the list. And Fred's code is usually of a very high standard - ie it just works! Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld - Original Message - From: Chris Hengge [EMAIL PROTECTED] To: Alan Gauld [EMAIL PROTECTED] Sent: Thursday, September 07, 2006 5:25 AM Subject: Re: Looking for a few commands Where is Fred's site? lol... I've been looking for it and not finding anything like this. Finally Fred Lundh has a console library that tries to pull all this together into a single platform independant module, but its not a standard library module(yet) and you have to download it from Fred's site. Frankly if I need to do detailed screen manipulation in Python I usually just bite the bullet and build a GUI - its easier. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for a few commands
I got the screen clearing bit no problem, thanks for that one. I'm still not used to being able to just use c libraries. Even the C libraries are non standard - they aren't part of the ANSI C definition. Its just that C libraries for the PC know what the hardware will look like so they can provide screen manipulation routines. But that code will be completely non-portable to any other computing platform. And even between C vendors the screen calls can be completely different. For example my MIX compiler uses cls() to clear the screen, My Borland one uses ClrScr() and I think that Microsoft Visual C uses something else again. Similarly for positioning the cursor, MIX uses curscol(), cursrow() whereas the Borland one uses gotoXY() - I think, its been a while! a fascination with linux terminals being able to draw progress bars or busy animations and figured I'd have a little fun. :] I came across curses which looks to be included in activepython so that might be of some use for my linux programming. There is an old curses module for DOS somewhere but I never got it working and it didn't implement all the functions.. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running DOS jobs in batch
Etrade Griffiths wrote: Hi I am trying to write a PYTHON script that automates the running of an application program MX200510.EXE under XP Pro via a DOS window. This file is in directory C:\Program Files\CMG\IMEX\2005.10\EXE The command line arguments are MX200510.EXE -f temp.dat -wd C:\Projects\Vitol\New business\Octon\simulation\full field model\0608 My Python script is as follows: # # Test Python script to submit IMEX jobs # import os # # Start of MAIN program # # Initialisation work_dir=r'C:\Projects\Vitol\New business\Octon\simulation\full field model\0608' imex_dir=r'C:\Program Files\CMG\IMEX\2005.10\EXE' imex_fil='temp.dat' imex_args=('mx200510.exe','-f',imex_fil,'-wd',''+work_dir+'') nscen=2 # Check IMEX directory and files exist os.chdir(imex_dir) L=os.listdir(imex_dir) for item in L: print item # Change directory to working directory os.chdir(work_dir) # Loop over N scenarios for n in range(1,nscen): # Spawn IMEX job and wait for completion os.spawnv(os.P_WAIT, imex_dir, imex_args) I think the second arg to spawnv() should be the name of the program to run (MX200510.EXE), not the path to the dir containing MX200510.EXE. The parameter is named path but if you look at the examples in the doc it is just the name. Kent The output from this script is ck9700.dll libguide40.dll mx200510.exe mx200510en.chm mx200510sp.chm Traceback (most recent call last): File C:/Projects/Vitol/New business/Octon/simulation/full field model/0608/test_imex.py, line 39, in -toplevel- os.spawnv(os.P_WAIT, imex_dir, imex_args) OSError: [Errno 2] No such file or directory ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Thread forever ?
János Juhász wrote: Dear Tutors, ### from threading import Thread import sys import time # This thread would read lines from a # barcode scanner class ComThread(Thread): def __init__(self): Thread.__init__(self) If you call self.setDaemon() here you will mark the thread as a daemon thread and it will not block the exit of the program. def run(self): while 1: time.sleep(2) print time.ctime() com = ComThread() com.start() # Main loop for handling the keyboard while 1: s = raw_input() if s == '': continue elif s in 'qQ': # may I com.Terminate() here sys.exit() # when I goes out here # the comthread is just running. else: try: num = int(s) print 'mod qty=%d' % num except: pass # When this program leaves from the while loop, it doesn't terminate the comreader thread. setDaemon() is the simplest way, as noted above. You could also have the main loop set a flag that the thread loop checks; if the flag is set the thread loop exits. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] ABout distinquishing elements in a string/regular expr
Hi tutors, I am currently working on a project that identifies languages of html documents, using Python, of course. Just wondering, given a string: str = html title this is french 77 992 / aaabbbccc /html what is the python expression for: 1. r = return_anything_that's_within (str), i.e. it should give html, aaabbbccc, html 2. r = remove_all_numbers(str), (what is the python expression for 'is_int') i.e. it removes 77 and 992 3. dif = listA_minus_listB(str, r), i.e. should return ['77', '992'], using the above 'r' value. thank you for your time! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ABout distinquishing elements in a string/regular expr
Xiao Yu Michael Yang wrote: Hi tutors, I am currently working on a project that identifies languages of html documents, using Python, of course. You might be interested in http://chardet.feedparser.org/ which seems to work directly on HTML. Just wondering, given a string: str = html title this is french 77 992 / aaabbbccc /html Note that str is the name of the built-in string type and not a good choice for a variable name. what is the python expression for: 1. r = return_anything_that's_within (str), i.e. it should give html, aaabbbccc, html You can do this with a regular expression: In [1]: s = html title this is french 77 992 / aaabbbccc /html In [2]: import re In [3]: re.findall('.*?', s) Out[3]: ['html', 'aaabbbccc', '/html'] If you are trying to strip the tags from the HTML, try one of these: http://www.oluyede.org/blog/2006/02/13/html-stripper/ http://www.aminus.org/rbre/python/cleanhtml.py 2. r = remove_all_numbers(str), (what is the python expression for 'is_int') i.e. it removes 77 and 992 What should r look like here? Is it the string s with digits removed, or some kind of list? s.isdigit() will test if s is a string containing all digits. 3. dif = listA_minus_listB(str, r), i.e. should return ['77', '992'], using the above 'r' value. You seem to be confused about strings vs lists. s is a string, not a list. If you have two lists a and b and you want a new list containing everything in a not in b, use a list comprehension: [ aa for aa in a if aa not in b ] If what you are looking for is all the number strings from s, you can use a regular expression again: In [4]: re.findall(r'\d+', s) Out[4]: ['77', '992'] Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for a few commands
Chris Hengge wrote: Thanks for the details, I see several code bits I'll have to play with. I got the screen clearing bit no problem, thanks for that one. I'm still not used to being able to just use c libraries. The ctypes module lets you call functions in shared libraries. It is standard in Python 2.5 or available from http://starship.python.net/crew/theller/ctypes/ I don't actually have a need to draw the cursor all over the screen for any practical application either personal or work, but I've got a bit of a fascination with linux terminals being able to draw progress bars or busy animations and figured I'd have a little fun. :] I came across curses which looks to be included in activepython so that might be of some use for my linux programming. Here is a progress bar: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/299207 You also might look at urwid though it doesn't seem to run on Windows: http://excess.org/urwid/ Unfortunately I don't think there is a console library that works on both Windows and Linux. For portable (and more functional) UIs you are better off learning Tkinter or wxPython. Kent Thanks again. On Thu, 2006-09-07 at 08:44 +0100, Alan Gauld wrote: Replying to the List The trick is to know either that Fred works at Pythonware, or that his nickname is the effbot... :-) http://effbot.org/downloads/ Sorry, neither are intuitively obvious... but he has lots of goodies on his site, worth perusing the list. And Fred's code is usually of a very high standard - ie it just works! Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld - Original Message - From: Chris Hengge [EMAIL PROTECTED] To: Alan Gauld [EMAIL PROTECTED] Sent: Thursday, September 07, 2006 5:25 AM Subject: Re: Looking for a few commands Where is Fred's site? lol... I've been looking for it and not finding anything like this. Finally Fred Lundh has a console library that tries to pull all this together into a single platform independant module, but its not a standard library module(yet) and you have to download it from Fred's site. Frankly if I need to do detailed screen manipulation in Python I usually just bite the bullet and build a GUI - its easier. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running DOS jobs in batch
Thanks for that Kent. I did imex_exe=r'C:\Program Files\CMG\IMEX\2005.10\EXE\mx200510.exe' imex_args=('mx200510.exe','-f',imex_fil,'-wd',''+work_dir+'') for n in range(1,nscen): os.spawnv(os.P_WAIT, imex_exe, imex_args) and it seems to work. Not sure why I need to provide the name of the application twice though: the lib pages for spawn* say In either case, the arguments to the child process must start with the name of the command being run but hey, it works! Thanks again Alun ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Some questions about my yen-USD.py
Dick Moores rdm at rcblue.com writes: (1) Have I handled possible user-errors OK? I've tested it a bit and it seems to be quite robust. (2) Is my roundingN() function OK? Is there a better way to write it? Will the line n = round(float(n)*(10**rounding))/(10**rounding) Using format strings is easier I think. %.2f % 2.34234 will give '2.34'. get me into trouble with the flakiness of float(n)? In testing I didn't find any problems, but .. Nah. Float accuracy is only a problem if you need around lots of significant digits (16 or so). (4) I wanted to call closingMessage() in main(), but in some cases, if it's in main() it gets 2 successive calls. I can't figure out why. Would IDLE's debugger be of use here? (I've never used it before.) I haven't been able to find up-to-date IDLE help. I think the main loop could be improved. 1) Python idiom is to *not* always call main(), because that makes it impossible to use functions from your module in a different program: importing the module would start running the converter, while you might only be interested in reusing getRate(). It's better to put the following code at the bottom instead: if __name__ == __main__: # if module is running standalone (not imported) main() 2) If the application is used extensively, you'll exceed the maximum recursion depth, because what the application does is essentially this (if the user chooses to continue): main calls again calls main calls again calls... ad infinitum This is called recursion - main essentially calls itself. You can test what happens by disabling the entire main loop up to again() as well as the raw_input line in again(). Python will quickly give up with: File yen.py, line 164, in again main() File yen.py, line 184, in main again() RuntimeError: maximum recursion depth exceeded It's better to have a main() which does something like this: - get the conversion rate and store it in some (global?) variable (instead of asking for it every time) - start a while True loop: -- get the rate , currency and amount -- calculate and print result -- ask the user whether to do it again and stop loop if answer is No 3) The function again() uses an internal variable called 'again'. This is not good coding practice (confusing). 3b) Note that this is a variable local to the again() function, so you cannot use it in the main() anyway: again() if again: break if again actually checks if there is something called 'again' with a non-zero/non-empty/non-None/True value. Your function is such a thing, so the if condition always evaluates as True. (Tip: try print again before the if again, you'll see something like function again at 0x00B04670). This is of course related to recursion problem above. Improved version would be: def again(): answer = raw_input('Another?') return answer in 'yY' # evaluates to True if the user pressed 'y' or 'Y' def main(): # stuff while True: # stuff if not again(): closingMessage() return None Notice that this code is also easier to read than the original, because it's a literal translation of you intention: if the user doesn't want to run it again, say goodbye and stop. 4) Function names are important and should be chosen in such a way that they are not confusing. Most of them are OK, but commas() is non-descripting and printResult() is confusing - it doesn't just print, it actually calculates. A third party interested in reusing your calculation routine wouldn't expect the printResult to be the culprit. 5) Checks like if currency in 'USD' work, but are a bit unstable. It works in this case because Yen and USD have no letters in common, so input of 'y', 'e' or 'n' all lead to 'Yen', while 'u', 's' and 'd' go to 'USD'. Imagine you'd extend your program to also handle 'AUD', 'EUR', 'CAD' and 'SEK'. The 'e' would now lead to Yen instead of EUR. 6) I would trim down the the checks in checkAmount: - there is no need to use continue in that loop, because the loop will continue anyway. 'continue' is only useful if there is some code later in the loop that you want to skip. - separate checks for negative and zero values seem pointless. Either handle 0 as any other number (gives result 0), or put a single check on amount = 0 and inform the user that a number larger than 0 is required. Here's a modified version: def getAmount(currency): while True: useramount = raw_input('Amount: ').lower().strip() if useramount in 'qx': return useramount try: amount = float(useramount) except ValueError: continue # we want to skip the code below if amount = 0: print Amount must be more than 0. else: return amount Using multiple returns in a single function is sometimes frowned upon; but then again, so are break and continue :).
Re: [Tutor] python mysql question
Patricia patriciap.gu at gmail.com writes: I have to store and retrieve text files from a database table and the size of each file is about 500k. Can someone give me an idea on how to do this? You might want to have a look at this: http://sourceforge.net/projects/mysql-python Yours, Andrei ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python mysql question
On Thu, 2006-09-07 at 02:42 +, Patricia wrote: Hi, I have to store and retrieve text files from a database table and the size of each file is about 500k. Can someone give me an idea on how to do this? Thanks, Patricia http://dustman.net/andy/python/python-and-mysql Provides some background for the MySQLdb module. This should get you started. The next reference provides more background, but may not be needed. http://www.python.org/dev/peps/pep-0249/ This describes how the Python DB modules behave. Hopefully, that gets you started. We can help with more specific questions as they arise. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Thread forever
Dear Kent, thanks your comment. When this program leaves from the while loop, it doesn't terminate the comreader thread. If you call self.setDaemon() here you will mark the thread as a daemon thread and it will not block the exit of the program. It works well. Yours sincerely, __ Janos Juhasz ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python mysql question
I have to store and retrieve text files from a database table and the size of each file is about 500k. Can someone give me an idea on how to do this? Thanks, Patricia http://dustman.net/andy/python/python-and-mysql Provides some background for the MySQLdb module. This should get you started. The next reference provides more background, but may not be needed. And just as a heads up: you'll probably need to configure your database tables to use TEXT or LONGTEXT columns, since 500k texts are definitely larger than the 255-char limit imposed by varchars. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Some questions about my yen-USD.py
Hi Dick, I'm looking at the last part of the main() function: # def main(): while True: ... again() if again: break # This looks a little suspicious. What does the again() function do, and is it supposed to return a value? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Some questions about my yen-USD.py
Dnia czwartek, 7 września 2006 14:37, Andrei napisał: get me into trouble with the flakiness of float(n)? In testing I didn't find any problems, but .. Nah. Float accuracy is only a problem if you need around lots of significant digits (16 or so). I wouldn't bet. Such a simple thing as 0.1 can't be represented correctly on Float... That's what 'decimal' is for. See that: 0.1 + 0.1 + 0.1 - 0.3 5.5511151231257827e-17 from decimal import Decimal Decimal(0.1)+ Decimal(0.1)+ Decimal(0.1)-Decimal(0.3) Decimal(0.0) For more see: http://docs.python.org/lib/module-decimal.html -- Pawel Kraszewski http://www.kraszewscy.net ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running DOS jobs in batch
imex_exe=r'C:\Program Files\CMG\IMEX\2005.10\EXE\mx200510.exe' imex_args=('mx200510.exe','-f',imex_fil,'-wd',''+work_dir+'') for n in range(1,nscen): os.spawnv(os.P_WAIT, imex_exe, imex_args) and it seems to work. Not sure why I need to provide the name of the application twice though: the lib pages for spawn* say In either case, the arguments to the child process must start with the name of the command being run but hey, it works! Glad it works. But you probably should be using the new Subprocess module for this kind of thing... It is supposed to supercede popen/spawn etc Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tempfile and webbrowser
Hello, Here is another problem: Considering this programm: import os, tempfile a = tempfile.mkstemp() f= open(a[1],'w') f.write(foo) f.close() print f.name # here some code to do some things with f os.unlink(f.name) The output is: Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. ## working on region in file c:/DOCUME~1/Yves/LOCALS~1/Temp/python-1408y8u... c:\docume~1\yves\locals~1\temp\tmp8fr4-9 Traceback (most recent call last): File stdin, line 1, in ? File c:/DOCUME~1/Yves/LOCALS~1/Temp/python-1408y8u, line 8, in ? os.unlink(f.name) OSError: [Errno 13] Permission denied: 'c:\\docume~1\\yves\\locals~1\\temp\\tmp8fr4-9' The file deletion (os.unlink(f.name)) does not work on Windows (it works on Ubuntu with Python 2.4, though). So, is there a way to get this os.unlink(f.name) to work on Windows? -- Yves Egrix ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how do I find where my program is installed?
snip way. so I need to tell my program to set the working directory back to the installation directory... but where is this? Here's what I do in my py2exe app: installDir = os.path.dirname(os.path.abspath(sys.argv[0])) and take a look at this link: http://www.py2exe.org/index.cgi/WhereAmI HTH, Bill ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how do I find where my program is installed?
Thanks Bill, I read the link you sent, and I am not sure what they mean by "You cannot rely on __file__, because __file__ is not there in the py2exed main-script." can't I use _file_ in my application though? This is what I just added to my application and it seems to do the trick... is there an exception that I am not aware of?using your method, what do you do with 'installDir' in py2exe?thanks for the help. [EMAIL PROTECTED] wrote: way. so I need to tell my program to set the working directory back to the installation directory... but where is this?Here's what I do in my py2exe app:installDir = os.path.dirname(os.path.abspath(sys.argv[0]))and take a look at this link:http://www.py2exe.org/index.cgi/WhereAmIHTH,Bill Do you Yahoo!? Get on board. You're invited to try the new Yahoo! Mail.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Some questions about my yen-USD.py
At 07:16 AM 9/7/2006, Danny Yoo wrote: Hi Dick, I'm looking at the last part of the main() function: # def main(): while True: ... again() if again: break # This looks a little suspicious. What does the again() function do, and is it supposed to return a value? I've just seen all the answers to my original post. Thank you all. For now, just to answer Danny's question: Danny, Yes. It will return anything other than y, Y, etc., in answer to the prompt, \n\nDo you want to do another calculation? Y/N: . This will cause a break out of the while loop and call closingMesssage(). Too convoluted, I'm sure, but it does work. Dick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how do I find where my program is installed?
[Jeff] I read the link you sent, and I am not sure what they mean by You cannot rely on __file__, because __file__ is not there in the py2exed main-script. can't I use _file_ in my application though? This is what I just added to my application and it seems to do the trick... is there an exception that I am not aware of? [Bill] Apparently, py2exe does something (when it freezes the script), which makes __file__ break or at least makes it unreliable. What that something is, I have know idea. Someone else on the list may know... [Jeff] using your method, what do you do with 'installDir' in py2exe? [Bill] The documentation for my program lives in a sub-directory of the program directory. Example: C:\Program Files\FilePrinter\documentation But the 'program directory' could be anywhere the user felt like installing it, so... when a user wants to open the docs, they click on a menu item in the GUI and this code gets fired: def on_openDocs_command(self, event): Opens the documention. installDir = os.path.dirname(os.path.abspath(sys.argv[0])) docs = r'documentation\FilePrinter.html' webbrowser.open(os.path.join(installDir, docs)) and no matter where they installed my program, it's possible for me to find the file 'FilePrinter.html' and open it. HTH Bill ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Some questions about my yen-USD.py
At 05:37 AM 9/7/2006, Andrei wrote: Dick Moores rdm at rcblue.com writes: (2) Is my roundingN() function OK? Is there a better way to write it? Will the line n = round(float(n)*(10**rounding))/(10**rounding) Using format strings is easier I think. %.2f % 2.34234 will give '2.34'. I had mistakenly believed that format strings could be used only in print expressions! So now that I know better, I'm trying to write the beginnings of a general setPrecision() function using format strings. However, it appears that a variable cannot be used instead of the .2 in %.2f % 2.234234 def setPrecision(n, precision): n = str(n) p = precision if . in n: n = %.pf % float(n) n = str(n) return n n = 2.234234 precision = 2 print setPrecision(n, precision) This get the error: ValueError: unsupported format character 'p' (0x70) at index 2 How to do this? Dick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A simple list question...
Richard Querin wrote: I've got a list of strings. There are some duplicates. I want a list of only the unique entries in that list. So I do the following: mylist = ['project1' , 'project2', 'project3', 'project4', 'project1'] d = {} for item in mylist: d[item] = None cleanedlist = d.keys() But d.keys() seems to add '\n' to each entry in cleanedlist. No, it doesn't. You are confused somewhere; my guess is your original data has newlines. Using your code above exactly: In [1]: mylist = ['project1' , 'project2', 'project3', 'project4', 'project1'] In [2]: d = {} In [3]: for item in mylist: ...: d[item] = None ...: In [4]: cleanedlist = d.keys() In [5]: cleanedlist Out[5]: ['project4', 'project1', 'project3', 'project2'] No newlines here. 2. Is there a better way to achieve my objective (ie. a list method for generating the cleaned list?) If you don't care about the order of items in the new list, just convert to a set and back (essentially a more concise version of what you did with a dict): In [6]: list(set(mylist)) Out[6]: ['project4', 'project1', 'project3', 'project2'] Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A simple list question...
On 08/09/06, Richard Querin [EMAIL PROTECTED] wrote: I've got a list of strings. There are some duplicates. I want a list of only the unique entries in that list. So I do the following: mylist = ['project1' , 'project2', 'project3', 'project4', 'project1'] d = {} for item in mylist: d[item] = None cleanedlist = d.keys() But d.keys() seems to add '\n' to each entry in cleanedlist. Um. I'm not in a position to test your code right now, but I can't think of any reason why it would do that.. 1. How can I easily strip out the newline characters from the elements of cleanedlist? You could do [s.strip() for s in cleanedlist] -- the .strip() string method will strip whitespace from both ends of the string. 2. Is there a better way to achieve my objective (ie. a list method for generating the cleaned list?) cleanedlist = list(set(mylist)) If you don't have python 2.4+, you will need to import the sets module. Also, depending on what you are doing with cleanedlist, you could just leave it as a set. Or even construct mylist as a set. -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A simple list question...
On 9/7/06, Kent Johnson [EMAIL PROTECTED] wrote: No, it doesn't. You are confused somewhere; my guess is your original data has newlines. Sorry, my bad. When I created the original list I was splitting a string in two pieces. The latter portion of the string had a newline at the end. I had taken the slice with [index:] instead of [index:-1]. Thanks for the help and the tips regarding other ways to do it. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Some questions about my yen-USD.py
I'm looking at the last part of the main() function: # def main(): while True: ... again() if again: break # This looks a little suspicious. What does the again() function do, and is it supposed to return a value? Yes. It will return anything other than y, Y, etc., in answer to the prompt, \n\nDo you want to do another calculation? Y/N: . Hi Dick, Are you sure? When you say it will return anything other than 'y', 'Y', what do you mean? What's the return value of again()? Just from a pure pattern matching perspective, compare what you had in the previous statements in terms of shape: rate = getRate() if str(rate) in QqXx: break or: currency = getYenOrUSD() if currency in QqXx: break versus the shape of the again block: again() if again: break Do you see something about the shape of the third block that's different from the first two blocks? That's what I'm trying to get at: there's something very different here. Read Andrei's point 3 on again() again, and see if what he says makes sense to you. http://mail.python.org/pipermail/tutor/2006-September/049105.html This is a point that you'll want to look at with scrutiny: even though the program looks like it's working, suspend your belief for the moment. *grin* There's something funky happening in the control flow of the code around this area. If you don't understand, ask for more clarification, and one of us here will be more explicit. Just to be fair: what you have does work, from a purely technical perspective. The thing is that it is not following the human intentions that you've written into the code, and other readers will get confused unless they stare at the code for a while. Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor