[Tutor] python equivalent of perl readlink()?
Is there a python equivalent of the perl readlink() function (e.g. one that returns the relative path in cases where a command such as ``ln -s ls /usr/local/bin/gls'' created the link? Reading the documentation on the various os.path functions, the only thing I see returns the fully resolved path rather than the relative one (/usr/local/bin/ls in the case above). Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``It's time to feed the hogs'' -- Unintended Consequences ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
On 10/14/06, Chris Hengge [EMAIL PROTECTED] wrote: Guess nobody has had a chance to point me in the write direction on this problem yet?Thats ok, I've gotten a ton of other code written, and I'll come back to this tricky part later.This particular project I've been working on to automate some of my job at work has been an excellent learning experience. :D On 10/14/06, Chris Hengge [EMAIL PROTECTED] wrote: I was using afile.split(/), but I'm not sure how to impliment it... I think kent johnson gave you a solution to this...was it not acceptable? Another alternate route you can take is os.path.split(path)[-1]this will give you the filename no matter what system you're on.it should work for '\\' and '/'.Are you making a script to automatically unzip something? ( I confess, I didn't read the other e-mails before this one.)If you are, and the problem you're having is with writing files to subdirectories,you'd want to do something like this:check if directory you want exists if it does, change into it.if it doesn't, create it and then change into it.recursively do this until you get to where you want to create the file...then create the file you want.in python, this would look like: import ospath = 'directory/subdir/filename.txt' #this is the path you use from your zipfile or w/epath = os.path.split(path) #this will make a list ['directory','subdir','filename.txt']for item in path[:-1]: #everything but the last item (which is the filename) if item not in os.listdir(): #directory doesn't exist os.mkdir(item)#so we'll create it os.chdir(item)#it doesn't matter to us if the directory exists before, we change into it either way. f = file(path[-1])#create the file you wantedf.write(Hello, this is the file)#change this to write the file info from out of the zip.f.close()#close file :)#now let's go back to the parent directory so we don't get lost later on :) for x in path[:-1]:#for every directory that we've changed into, os.chdir('..') #go back to parent directory.I don't have a python interp installed on this computer, so there may be errors,and if so, I apologize in advance, but I can't see any reason why this wouldn't work. I just realized os.path doesn't do what I thought it does. It only splits the end.so I guess my solution above would work, but you'd have to split it a different way :)I hope that helps,-Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
I must have not been clear.. I have a zip file with folders inside.. When I extract it.. I dont want the folder structure, just the files.. using split doesn't seem to help in this situation.. unless I'm not putting the results in the right spot.. Thanks again though. On 10/15/06, Luke Paireepinart [EMAIL PROTECTED] wrote: On 10/14/06, Chris Hengge [EMAIL PROTECTED] wrote: Guess nobody has had a chance to point me in the write direction on this problem yet?Thats ok, I've gotten a ton of other code written, and I'll come back to this tricky part later.This particular project I've been working on to automate some of my job at work has been an excellent learning experience. :D On 10/14/06, Chris Hengge [EMAIL PROTECTED] wrote: I was using afile.split(/), but I'm not sure how to impliment it... I think kent johnson gave you a solution to this...was it not acceptable? Another alternate route you can take is os.path.split(path)[-1]this will give you the filename no matter what system you're on.it should work for '\\' and '/'.Are you making a script to automatically unzip something? ( I confess, I didn't read the other e-mails before this one.)If you are, and the problem you're having is with writing files to subdirectories,you'd want to do something like this:check if directory you want exists if it does, change into it.if it doesn't, create it and then change into it.recursively do this until you get to where you want to create the file...then create the file you want.in python, this would look like: import ospath = 'directory/subdir/filename.txt' #this is the path you use from your zipfile or w/epath = os.path.split(path) #this will make a list ['directory','subdir','filename.txt']for item in path[:-1]: #everything but the last item (which is the filename) if item not in os.listdir(): #directory doesn't exist os.mkdir(item)#so we'll create it os.chdir(item)#it doesn't matter to us if the directory exists before, we change into it either way. f = file(path[-1])#create the file you wantedf.write(Hello, this is the file)#change this to write the file info from out of the zip.f.close()#close file :)#now let's go back to the parent directory so we don't get lost later on :) for x in path[:-1]:#for every directory that we've changed into, os.chdir('..') #go back to parent directory.I don't have a python interp installed on this computer, so there may be errors, and if so, I apologize in advance, but I can't see any reason why this wouldn't work. I just realized os.path doesn't do what I thought it does. It only splits the end.so I guess my solution above would work, but you'd have to split it a different way :)I hope that helps,-Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] [OT] Python and Excel/OOCalc
Hi, friends! Is there exist python extension or library for writing or exporting data into the Excel and/or OO Calc file? Excuse me for crossposting. Thanks in advance! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to open file in Excel/Calc spreadsheet?
Hi ,friends! How I can open Excel or OOCalc spreadsheet file 'remotely' from python programm? I mean how to execute Excel or Calc with appropriate spreadsheet file? Thanks in advance! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
Chris Hengge wrote: I must have not been clear.. I have a zip file with folders inside.. When I extract it.. I dont want the folder structure, just the files.. using split doesn't seem to help in this situation.. unless I'm not putting the results in the right spot.. Can you show us what you tried? split() can definitely help here. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
Chris Hengge wrote: I was using afile.split(/), but I'm not sure how to impliment it... Did you see my hint below? Is there something you don't understand about it? Kent if / in afile: (for some reason I can't add 'or \ in afile' on this line) outfile = open(afile, 'w') # Open output buffer for writing. (to open the file, I can't split here) outfile.write(zfile.read(afile)) # Write the file. (zfile.read(afile)) wont work if I split here...) outfile.close() # Close the output file buffer. On 10/14/06, *Kent Johnson* [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] wrote: Chris Hengge wrote: Ok, last problem with this whole shebang... When I write the file from the zip, if it is in a subfolder, it will error.. The code below will detect if the file in contained inside a directory in the zip, but I just want it to write it like it wasn't. Another words Zipfile.zip looks like this file.ext file2.ext folder/ anotherfile.ext file.ext extracts fine, file2.ext extracts file.. but it see's the last file as folder/anotherfile.ext and it can't write it.. I tried to figure out how to use .split to get it working right.. but I'm not having any luck.. Thanks. for afile in zfile.namelist(): # For every file in the zip. # If the file ends with a needed extension, extract it. if afile.lower().endswith('.cap') \ or afile.lower().endswith('.hex') \ or afile.lower().endswith('.fru') \ or afile.lower().endswith('.cfg'): if afile.__contains__(/): This should be spelled if / in afile: __contains__() is the method used by the python runtime to implement 'in', generally you don't call double-underscore methods yourself. I think you want afile = afile.rsplit('/', 1)[-1] that splits afile on the rightmost '/', if any, and keeps the rightmost piece. You don't need the test for '/' in afile, the split will work correctly whether the '/' is present or not. If you are on Windows you should be prepared for paths containing \ as well as /. You can use re.split() to split on either one. Kent outfile = open(afile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. else: outfile = open(afile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to open file in Excel/Calc spreadsheet?
Basil Shubin wrote: Hi ,friends! How I can open Excel or OOCalc spreadsheet file 'remotely' from python programm? I mean how to execute Excel or Calc with appropriate spreadsheet file? You can use win32com to drive Excel using its COM interface. The sample chapter from the O'Reilly book Python Programming on Win32 shows how to open a spreadsheet in Excel; http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html Google 'python excel com' for more examples. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Exception and sys.exit() in a cgi script
This is a peace of a CGI script i have. 1 import cgi 2 form=cgi.FieldStorage() 3 try : 4 ano=form[ano].value 5 conta=form[conta].value 6 except KeyError : 7 print 'htmlbrbrbodypPlease enter values in the fields/p/body/html ' 8 sys.exit(0) When the excption occurs, no message is shown on the browser. If I run the script with IDLE, the message is printed and then the script exits. What's wrong here? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to open file in Excel/Calc spreadsheet?
Very simple: os.startfile([file]) ex: import os os.startfile("d:\\documentos\\eleicoes2005-dn.xls") It works with any file tipe in windows, the file is opened with it's associated application. Basil Shubin wrote: Hi ,friends! How I can open Excel or OOCalc spreadsheet file 'remotely' from python programm? I mean how to execute Excel or Calc with appropriate spreadsheet file? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Exception and sys.exit() in a cgi script
Hi Paulino, This is a peace of a CGI script i have. 1 import cgi 2 form=cgi.FieldStorage() 3 try : 4 ano=form[ano].value 5 conta=form[conta].value 6 except KeyError : 7 print 'htmlbrbrbodypPlease enter values in the fields/p/body/html ' 8 sys.exit(0) When the excption occurs, no message is shown on the browser. Can you tell us a bit more about the set up? What OS? What web server? Can you get any other python CGI scripts running correctly? If I run the script with IDLE, the message is printed and then the script exits. The IDE environment is very different to a web server environment. You should only treat IDLE as a first approximation when developing Web scripts. You can use the OS prompt for a slightly better approximation provided you set some environment variables first, but ultimately you need to test on the web server you will be using. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Exception and sys.exit() in a cgi script
Thank you, Yes I have other scripts working fine. The OS is WXP and the server is the python's CGIHTTPserver (for an intranet use only) - Hi Paulino, This is a peace of a CGI script i have. 1 import cgi 2 form=cgi.FieldStorage() 3 try : 4 ano=form["ano"].value 5 conta=form["conta"].value 6 except KeyError : 7 print 'htmlbrbrbodypPlease enter values in the fields/p/body/html ' 8 sys.exit(0) When the excption occurs, no message is shown on the browser. Can you tell us a bit more about the set up? What OS? What web server? Can you get any other python CGI scripts running correctly? If I run the script with IDLE, the message is printed and then the script exits. The IDE environment is very different to a web server environment. You should only treat IDLE as a first approximation when developing Web scripts. You can use the OS prompt for a slightly better approximation provided you set some environment variables first, but ultimately you need to test on the web server you will be using. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to open file in Excel/Calc spreadsheet?
How I can open Excel or OOCalc spreadsheet file 'remotely' from python programm? I mean how to execute Excel or Calc with appropriate spreadsheet file? there was a similar question on the main newsgroup a few days ago, slightly related to this post, but the answers will be helpful here. http://groups.google.com/group/comp.lang.python/browse_thread/thread/a7ed60067ca5a8d4/# if you're interested, i added a section (in chapter 23) to my book, Core Python Programming, on programming Microsoft Office applications, with examples for Word, Excel, PowerPoint, and Outlook. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Core Python Programming, Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] CGIHTTPServer - redirect output to a log file
Paulino wrote: How can I redirect the output of an CGIHTTPServer from the console to a logfile? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor You can start it from a shell script #!/bin/sh ./MyWebServer.py 2/path/to/output.log Good Luck, Glenn -- Ketchup. For the good times... - Ketchup Advisory Board Glenn Norton Application Developer Nebraska.gov 1-402-471-2777 [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] CGIHTTPServer - redirect output to a log file
well, I'm running this CGIserver on windows... Glenn T Norton escreveu: Paulino wrote: How can I redirect the output of an CGIHTTPServer from the console to a logfile? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor You can start it from a shell script #!/bin/sh ./MyWebServer.py 2/path/to/output.log Good Luck, Glenn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] CGIHTTPServer - redirect output to a log file
You can start it from a shell script #!/bin/sh ./MyWebServer.py 2/path/to/output.log Paulino [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] well, I'm running this CGIserver on windows... You can still use redirection although its not as powerful as unix. Just try C:\PATH python \path\mywebserver.py logfile.txt You can get full details by entering the search string output redirection at the XP Help screen and viewing the Using command redirection operators topic. 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] executing with double click on linux
Thank you for your answer, Jonathon. I have found that the problem ocurs only with programs that make use of glade files for the interface. With pure pygtk programs without using glade files, making a launcher with a simple double click works perfectly. But if the program builds his interface basing in a glade file, that doesn't work. The mime type is ok, and I have tried your proposal, but it doesn't work with those programs. I'll keep trying to find the reason. I'll tell you if I find it. I have wroten to gnome-devel about this, and they have recommended me to have a look at the source from orca, a gnome application that makes use of glade files, so I'll have a look at it... __ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y móviles desde 1 céntimo por minuto. http://es.voice.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] an alternative to shutil.move()?
Is there an alternative in python to use shutil.move()? It copies the files and then removes the source file insted of just moving directly the file (don't know much about file systems, but I suppose that when you move using the shell, if both source and destination are in the same partition, it's just a matter of changing the entries in the file allocation table). Copying the entire file, specially with big files is very slow, and I think that it makes an unnecesary use of the hard drive and system resources, when both source file and destination are on the same partition... __ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y móviles desde 1 céntimo por minuto. http://es.voice.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
After getting some sleep and looking at my code, I think I was just to tired to work through that problem =PHere is my fully working and tested code..Thanks to you all for your assistance!if / in afile: aZipFile = afile.rsplit('/', 1)[-1] # Split file based on criteria. outfile = open(aZipFile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close () # Close the output file buffer.elif \\ in afile: aZipFile = afile.rsplit('\\', 1)[-1] # Split file based on criteria. outfile = open(aZipFile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. else: outfile = open(afile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer.On 10/15/06, Kent Johnson [EMAIL PROTECTED] wrote:Chris Hengge wrote: I must have not been clear.. I have a zip file with folders inside.. When I extract it.. I dont want the folder structure, just the files.. using split doesn't seem to help in this situation.. unless I'm not putting the results in the right spot..Can you show us what you tried? split() can definitely help here. Kent___Tutor maillist-Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Equivalent to perl -e
My professor and advisor has been inspired by me to give Python a try. He's an avid Perl user, and challenged me with the following: What is the Python equivalent to perl -e 'some oneliner'? Embarassingly, I had no answer, but I figure, someone on the list will know. His use of Python is at stake; he threatened that, since he's dependant enough on using perl -e within Emacs enough, if it can't be done in Python, he won't take the language seriously. Help me, Python Tutor, you're his only hope! Thanks in advance, Chris ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Equivalent to perl -e
Chris Lasher wrote: My professor and advisor has been inspired by me to give Python a try. He's an avid Perl user, and challenged me with the following: What is the Python equivalent to perl -e 'some oneliner'? python -c More details here: http://linuxcommand.org/man_pages/python1.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Equivalent to perl -e
Chris Lasher wrote: My professor and advisor has been inspired by me to give Python a try. He's an avid Perl user, and challenged me with the following: What is the Python equivalent to perl -e 'some oneliner'? Embarassingly, I had no answer, but I figure, someone on the list will know. His use of Python is at stake; he threatened that, since he's dependant enough on using perl -e within Emacs enough, if it can't be done in Python, he won't take the language seriously. Help me, Python Tutor, you're his only hope! Thanks in advance, Chris ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor How about... python -c for x in 'Tell them to jump on board and take the blue pill': print x Glenn -- Ketchup. For the good times... - Ketchup Advisory Board Glenn Norton Application Developer Nebraska.gov 1-402-471-2777 [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python equivalent of perl readlink()?
On 10/15/06, Bill Campbell [EMAIL PROTECTED] wrote: Is there a python equivalent of the perl readlink() function(e.g. one that returns the relative path in cases where a commandsuch as ``ln -s ls /usr/local/bin/gls'' created the link?Reading the documentation on the various os.path functions, theonly thing I see returns the fully resolved path rather than therelative one (/usr/local/bin/ls in the case above).BillThe function is in the os module ( http://docs.python.org/lib/os-file-dir.html). -Arcege-- There's so many different worlds,So many different suns.And we have just one world,But we live in different ones. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Equivalent to perl -e
Haha! I'll relay that message! Thanks Kent and Glenn! Chris On 10/15/06, Glenn T Norton [EMAIL PROTECTED] wrote: Chris Lasher wrote: My professor and advisor has been inspired by me to give Python a try. He's an avid Perl user, and challenged me with the following: What is the Python equivalent to perl -e 'some oneliner'? Embarassingly, I had no answer, but I figure, someone on the list will know. His use of Python is at stake; he threatened that, since he's dependant enough on using perl -e within Emacs enough, if it can't be done in Python, he won't take the language seriously. Help me, Python Tutor, you're his only hope! Thanks in advance, Chris ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor How about... python -c for x in 'Tell them to jump on board and take the blue pill': print x Glenn -- Ketchup. For the good times... - Ketchup Advisory Board Glenn Norton Application Developer Nebraska.gov 1-402-471-2777 [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
Chris Hengge wrote: After getting some sleep and looking at my code, I think I was just to tired to work through that problem =P Here is my fully working and tested code.. Thanks to you all for your assistance! if / in afile: aZipFile = afile.rsplit('/', 1)[-1] # Split file based on criteria. outfile = open(aZipFile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close () # Close the output file buffer. elif \\ in afile: aZipFile = afile.rsplit('\\', 1)[-1] # Split file based on criteria. outfile = open(aZipFile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. else: outfile = open(afile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. Somewhere along the way, I got lost ;-) Why are you messing with the slashes (/ \\)? If you're trying to split a path and filename, then your best bet is 'os.path.split()'. For Example: import os s = '/some/path/to/file.txt' path, filename = os.path.split(s) path '/some/path/to' filename 'file.txt' 'os.path.split()' works equally as well for paths containing \\. I have some code below which I *think* does what you want. read a zip file and 'write out' only those files with a certain file extension. The directory structure is *not* preserved (it just writes all files to the current working directory). It has a little helper function 'myFileTest()' which I think makes things easier ;-) The function tests a file to see if meets our extension criteria. HTH, Bill code import zipfile import os # This is what I did for testing. Change it to point # to your zip file... zip = zipfile.ZipFile('test.zip', 'r') def myFileTest(aFile): myFileTest(aFile) - returns True if input file endswith one of the extensions specified below. for ext in ['.cap', '.hex', '.fru', '.cfg']: if aFile.lower().endswith(ext): return True for aFile in zip.namelist(): # See if the file meets our criteria. if myFileTest(aFile): # Split the path and filename. path, filename = os.path.split(aFile) # Don't overwrite an existing file. if not os.path.exists(filename): # Write out the file. outfile = open(filename, 'w') outfile.write(zip.read(aFile)) outfile.close() /code ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Equivalent to perl -e
[Chris Lasher] My professor and advisor has been inspired by me to give Python a try. He's an avid Perl user, and challenged me with the following: What is the Python equivalent to perl -e 'some oneliner'? The initally attractive but unsatisfying answer is: python -c 'some oneliner' The reason it's unsatisfying is that Python isn't concerned with making: some oneliner pleasant, or even sanely possible, for many tasks. Perl excels at one-liners; Python doesn't much care about them. Embarassingly, I had no answer, but I figure, someone on the list will know. His use of Python is at stake; he threatened that, since he's dependant enough on using perl -e within Emacs enough, if it can't be done in Python, he won't take the language seriously. Help me, Python Tutor, you're his only hope! Like many Python (very) old-timers, I used Perl heavily at the time Python came out. As was also true for many of them, as time went on the size of a new program I was willing to write in Perl instead of in Python got smaller and smaller, eventually reaching almost 0. I still use Perl some 15 years later, but now /only/ for perl -e-style 1-liners at an interactive shell. If it takes more than a line, I stick it in a module (and maybe a class) for reuse later. Python's strengths are more in readability, helpful uniformity, easy use of classes and rich data structures, and maintainability. Cryptic one-liners are in general (but not always) opposed to all of those. So, ya, python -c exists, but your professor won't be happy with it. That's fine! If one-liners are all he cares about, Perl is usually the best tool for the job. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
The code in my last email that I stated worked, is doing exactly what I want (perhaps there is a better method, but this is working)The slash detection is for the subdirectories located inside of a zip file. The name list for a file located inside a zipped folder shows up as folder/file.ext in windows, and folder\file.ext in linux.. so I was accounting for both. I dont think your method os.path.split() would work since there isn't a fully qualified path coming from the namelist. I like this little snip of code from your suggestion, and I may incorporate it...for ext in ['.cap', '.hex', '.fru', '.cfg']: if aFile.lower().endswith(ext): return TrueJust for sake of sharing.. here is my entire method.. def extractZip(filePathName): This method recieves the zip file name for decompression, placing the contents of the zip file appropriately. if filePathName == : print No file provided...\n else: if filePathName[0] == '': # If the path includes quotes, remove them. zfile = zipfile.ZipFile(filePathName[1:-1], r) else: # If the path doesn't include quotes, dont change. zfile = zipfile.ZipFile(filePathName, r) for afile in zfile.namelist(): # For every file in the zip. # If the file ends with a needed extension, extract it. if afile.lower().endswith('.cap') \ or afile.lower().endswith('.hex') \ or afile.lower().endswith('.fru') \ or afile.lower().endswith('.sdr') \ or afile.lower().endswith('.cfg'): if / in afile: aZipFile = afile.rsplit('/', 1)[-1] # Split file based on criteria. outfile = open(aZipFile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. elif \\ in afile: aZipFile = afile.rsplit('\\', 1)[-1] # Split file based on criteria. outfile = open(aZipFile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. else: outfile = open(afile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. print Resource extraction completed successfully!\n Not to go on and bore people with my project, the goal of this application (which is nearly done) is to take several zip files that I've prompted the user to drag and drop into the console, extract the necessary peices, add a few more files, change some lines within a couple of the files extracted, then pack it all back into one single zip... At this point, my little script is doing everything other then the file i/o for changing the lines inside the couple files needed (which I'll probably have done tomorrow if I have time at work). The script does a little more then that, like sets up a file structure and some menu's for the user, but essentially I've explained it... and it takes about a 20-45minute job and chops it into less then 30 seconds.. And considering I run through this process sometimes dozens of times a day, that time adds up fast.. Hopefully I can work on getting better at coding python with my newly earned time =D The flow of the script is a little odd because I had to make it extensible by basically copying a method for a specific package I'm trying to build and modifying to suite.. but.. once I'm fully done, this script should let me add an entire new type of zip package within minutes. Again, thanks to all of you for your input and suggestions. On 10/15/06, Bill Burns [EMAIL PROTECTED] wrote:Chris Hengge wrote: After getting some sleep and looking at my code, I think I was just to tired to work through that problem =P Here is my fully working and tested code.. Thanks to you all for your assistance! if / in afile: aZipFile = afile.rsplit ('/', 1)[-1] # Split file based on criteria. outfile = open(aZipFile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close () # Close the output file buffer. elif \\ in afile: aZipFile = afile.rsplit('\\', 1)[-1] # Split file based on criteria. outfile = open(aZipFile, 'w') # Open output buffer for writing. outfile.write (zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. else: outfile = open(afile, 'w') # Open output buffer for writing. outfile.write(zfile.read (afile)) # Write the file. outfile.close() # Close the output file buffer.Somewhere along the way, I got lost ;-) Why are you messing with theslashes (/ \\)?If you're trying to split a path and filename, then your best bet is 'os.path.split()'.For Example: import os s = '/some/path/to/file.txt' path, filename = os.path.split(s) path'/some/path/to' filename 'file.txt''os.path.split()' works equally as well for paths containing \\.I have some code below which I *think* does what you want. read azip file and 'write out' only those files with a certain file extension. The directory structure is *not* preserved (it just writes all files tothe current working directory).It has a little helper function
[Tutor] Help with sessions
I tried creating sessions for each appand then did htis codedef session_mw(app): sessionStore = DiskSessionStore(storeDir="%s/sessions/" % os.getcwd(), timeout=5) sessionStore= sessionStore.createSession() return SessionMiddleware(sessionStore, app)def initsession(session): session['id'] = 0 session['username'] = '' session['groups'] = '' session['loggedin'] = 0in 2 diff webapps, I run them in 2 different ports 9109 and 9911But the problem is both are now sharing the same session how do i ensure that they dont share browser session and create a new one from themselvesAnil___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Equivalent to perl -e
Points well taken. In fact, the example he demonstrated to me as a one-liner was a regular expression as a line filter in Emacs--essentially just a grep. There's no Pythonic equivalent to this. Right tool for the right job, as you said. He was half-joking about not learning Python if it lacked the option to execute snippets. His lab maintains a significant amount of Perl code; he was intrigued by my zealous enthusiasm for Python and my assertion that, personally, I experienced greater long-term readability with my scripts written in Python over those written in Perl. I think once he begins to experience Python he will come to understand why it's not suited for one-liners, and why that's a Good Thing. Excellent reply! Chris On 10/15/06, Tim Peters [EMAIL PROTECTED] wrote: [Chris Lasher] My professor and advisor has been inspired by me to give Python a try. He's an avid Perl user, and challenged me with the following: What is the Python equivalent to perl -e 'some oneliner'? The initally attractive but unsatisfying answer is: python -c 'some oneliner' The reason it's unsatisfying is that Python isn't concerned with making: some oneliner pleasant, or even sanely possible, for many tasks. Perl excels at one-liners; Python doesn't much care about them. Embarassingly, I had no answer, but I figure, someone on the list will know. His use of Python is at stake; he threatened that, since he's dependant enough on using perl -e within Emacs enough, if it can't be done in Python, he won't take the language seriously. Help me, Python Tutor, you're his only hope! Like many Python (very) old-timers, I used Perl heavily at the time Python came out. As was also true for many of them, as time went on the size of a new program I was willing to write in Perl instead of in Python got smaller and smaller, eventually reaching almost 0. I still use Perl some 15 years later, but now /only/ for perl -e-style 1-liners at an interactive shell. If it takes more than a line, I stick it in a module (and maybe a class) for reuse later. Python's strengths are more in readability, helpful uniformity, easy use of classes and rich data structures, and maintainability. Cryptic one-liners are in general (but not always) opposed to all of those. So, ya, python -c exists, but your professor won't be happy with it. That's fine! If one-liners are all he cares about, Perl is usually the best tool for the job. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python equivalent of perl readlink()?
On Sun, Oct 15, 2006, Michael P. Reilly wrote: On 10/15/06, Bill Campbell [EMAIL PROTECTED] wrote: Is there a python equivalent of the perl readlink() function (e.g. one that returns the relative path in cases where a command such as ``ln -s ls /usr/local/bin/gls'' created the link? Reading the documentation on the various os.path functions, the only thing I see returns the fully resolved path rather than the relative one (/usr/local/bin/ls in the case above). Bill The function is in the os module ([2] http://docs.python.org/lib/os-file-dir.html). Silly me. I was looking in the os.path module :-). Thanks. Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``Unix is simple. It just takes a genius to understand its simplicity'' -- Dennis Ritchie ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor