Re: StringIO MySQL data blob Image problem


dimitri pater wrote:
>
> the following code works when inserting images in reportlab tables:
>
> (result4 is a query result)
> a=0
> for i in result4:
> cfoto = StringIO()
> cfoto.write(result4[a][9].tostring())
> dfoto = cfoto.getvalue()
> fileFoto = open(str(a)+'temp.jpg','wb')
> fileFoto.write(dfoto)
> fileFoto.close()
> foto = Image(str(a)+'temp.jpg')
> a+=1
>
> Do stuff here (insert the Image)
>
> The problem with this code is that I need to create a unique file
> (str(a)+'temp.jpg'), I tried to use a single temp.jpg but it kept
> using the data from the first record. Tried flush(), truncate(0), but
> it didn't work. (My mistake probably ;-)
> But the images show in the PDF so that's fine for now.

You've obviously already worked this one out, which is
great. But if I might just comment on the code a little
bit, in a spirit of helpful criticism:

* It's not clear (to me) why you're using a StringIO
at all. I'm not familiar with MySQL in particular, but
in general, database interface modules will return a Python
string or possibly a buffer object from a Blob field.
In other words, is there anything to stop you simply
writing "result4[a][9]" directly into a file


# ... stuff leading up to:
blob = result4[a][9]
ofile = open ("temp.jpg", "wb")
ofile.write (blob) # (or, possibly, str (blob) if it's a buffer)
ofile.close ()


* Assuming you're using any recent version of Python,
you can save the extra counter by iterating over
enumerate (result4) which return a 0-based index
and the indexed item as a tuple. In fact, now I look
at it, you're doing the work twice. You're iterating
over result4 but doing nothing with the "i" which
is the result of the iteration. You might do better
with something like this:


#
# I've used "a", "i" to match your code,
# but more descriptive names are good, such
# as n_result, result or whatever fits your mind.
#
for a, i in enumerate (result4):
blob = i[9]
ofile = open ("%d-temp.jpg" % a, "wb")
ofile.write (blob)
ofile.close ()



* Finally, the tempfile module is a good one to use for
temporary files. (Although the xx-temp.jpg solution you
used may be perfectly acceptable for your needs).

In the above, I've avoided quite a few good-practice
issues, such as try-except blocks when writing a file,
or with-blocks in Python 2.5+. The code I've sketched
out is merely a rough-and-ready illustration of a
particular point, not a manual of best practice.

I suspect you may be newish to Python, if not to programming
in general. My comments above aren't intended to be
nitpicks to show up your ignorance, but hopefully hints
which might help you look at alternatives or consider
alternative idioms within Python itself.

Good luck with the PDFs!

TJG
Posted On: Monday 5th of November 2012 02:09:16 AM Total Views:  164
View Complete with Replies

RELATED TOPICS OF Python Programming PROGRAMMING LANGUAGE




Re: Pythonic ORM with support for composite primary/foreign keys?

On Tue, 06 Nov 2007 12:58:02 +0100, Wolfgang Keller wrote: >, > > [snip] > >So, is there another ORM module for Python besides SQLAlchemy which >supports composite porimary (and foreign) keys, and maybe also other >more "advanced", maybe even some of the PostgreSQL-specific features >(such as e.g. composite types) storm supports composite primary keys. I'm not sure if it supports composite foreign keys, but I suspect it does. It's also pretty good overall. Jean-Paul
VIEWS ON THIS POST

237

Posted on:

Monday 5th November 2012
View Replies!

RE: How to Create pyd by C#

> On Behalf Of jane janet > I'm wondering how to create extension fill (.pyd) or anything > that seem like DLL file by C# language. If you are going to be using C#, I would suggest that you create an ordinary assembly, and call it via IronPython.
VIEWS ON THIS POST

142

Posted on:

Monday 5th November 2012
View Replies!

Regular expression use

Nick Maclaren a crit : > For reasons that I won't explain, as they are too complicated > and not terribly relevant, I am interested in discovering what > people actually use regular expressions for. Usually, to obfuscate code. Sometimes for good reasons.... Hu Ok, me get out ---->[]
VIEWS ON THIS POST

137

Posted on:

Monday 5th November 2012
View Replies!

List Comprehension Question: One to Many Mapping?

Hi , How do I map a list to two lists with list comprehension For example, if I have x=[ [1,2], [3,4] ] What I want is a new list of list that has four sub-lists: [[1,2], [f(1), f(2)], [3,4], [f(3), f(4)]] [1,2] is mapped to [1,2] and [f(1), f(2)] and [3,4] is mapped to [3,4], [f(3), f(4)]. I just can't find any way to do that with list comprension. I ended up using a loop (untested code based on real code): l=[] for y in x: l.append(y) l.append([f(z) for z in y])
VIEWS ON THIS POST

135

Posted on:

Monday 5th November 2012
View Replies!

Redo: Problem with dynamic creation of classes.

Sorry, I had a small description problem. It's corrected below. I have a base class B and a derived class D which inherits from B. I also have a D2 class which inherits from D. D is used as a base class for most of my generated classes. I have a "special" class which inherits from D2 because I need to override a couple of its methods. Anything based on D will inherit Encode and Decode from B. class D(b.B): def __init__(self, data, timestamp = None): b.B.__init__(self, data) self.timestamp = timestamp class D2( D ): def __init__(self, data, timestamp = None): DS.__init__(self, data, timestamp) def Decode(self): pass def Encode(self): pass The generated classes come from this loop: for m in mdefs: mdef = mdefs[m] name = mdef['name'] + fbase if mdef.has_key('baseclass'): base_class_seq = mdef['baseclass'] else: base_class_seq = DEFAULT_BASE_CLASS nclass = new.classobj( name, base_class_seq, globals() ) base_class_seq is either going to be (D,) or (D2,) After I get through the class generation, I want to say globals()['IFRAMED2'].Decode = dynDecode globals()['IFRAMED2'].Encode = dynEncode for the one class that inherited from D2. If I do that, I find that *all* classes that call Encode or Decode are all calling dyn{En,De}code (which is exactly what I *don't* want). So I looked at the id values after class generation. print 'IFRAMED2.Encode = ', IFRAMED2.Encode, id(IFRAMED2.Encode) print 'SNRMD.Encode = ', SNRMD.Encode, id(SNRMD.Encode) print 'IFRAMED2 = ', IFRAMED2, id(IFRAMED2) print 'SNRMD = ', SNRMD, id(SNRMD) IFRAMED2.Decode = dynDecode IFRAMED2.Encode = dynEncode print 'IFRAMED2.Encode = ', IFRAMED2.Encode, id(IFRAMED2.Encode) print 'SNRMD.Encode = ', SNRMD.Encode, id(SNRMD.Encode) Here's the output: IFRAMED2.Encode = 1100623660 SNRMD.Encode = 1100623660 IFRAMED2 = d.IFRAMED2 1076299644 SNRMD = d.SNRMD 1103202364 IFRAMED2.Encode = 1100623660 SNRMD.Encode = 1100623660 So it looks like the IFRAMED2 class which inherits from D2 is starting out with the same id value for Encode as SNRMD which inherits from D, even though D2 defines its own Encode method. Is it me of is it the interpreter doing something wrong -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 DonorBlack holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question steveo at syslang.net -- http://mail.python.org/mailman/listinfo/python-list
VIEWS ON THIS POST

171

Posted on:

Monday 5th November 2012
View Replies!

Re: Python is removing my quotes!

* Gary Herron (Tue, 21 Aug 2007 09:09:13 -0700) > Robert Dailey wrote: > > Note: I'm using Python on Windows > > > > I have an application that allows a user to submit a password as a > > command line parameter. The password of choice may contain any > > characters the user wishes, including quotes. If I do the following: > > > > python password.py "9999"MyPassword > > > > The resulting output when I print this inside the script is: > > > > 9999MyPassword > > > > Notice how the quotations have been stripped. Is it DOS doing this, or > > Python Is there a way I can fix it > > Not Python. It never even sees those quotes. Whatever system you are > using for entering the text is stripping them. Is it the command prompt > (cmd.exe) If so then you can escape the quote by preceding it with a > backslash. (This is true of the DOS prompt [...] No, under Cmd it's "^".
VIEWS ON THIS POST

203

Posted on:

Monday 5th November 2012
View Replies!

read part of jpeg file by pure python

, I am wondering whether it's possible to read part (e.g. 1000*1000) of a huge jpeg file (e.g. 30000*30000) and save it to another jpeg file by pure python. I failed to read the whole file and split it, because it would cost 2GB memory. Can anyone help me Any comments would be appreciated.
VIEWS ON THIS POST

151

Posted on:

Monday 5th November 2012
View Replies!

Re: extract text from log file using re

On 13/09/2007, Fabian Braennstroem wrote: > me again... I should describe it better: > the result should be an array with just: > > 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 > 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 > 500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 8.3913e-04 > 3.8545e-03 1.3315e-01 11:14:10 500 > 501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 > > as field values. > > Fabian Braennstroem schrieb am 09/13/2007 09:09 PM: > > > > > > I would like to delete a region on a log file which has this > > kind of structure: > > > > > > #------flutest------------------------------------------------------------ > > 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 > > 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 > > 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 > > 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 > > reversed flow in 1 faces on pressure-outlet 35. > > > > Writing > > "/home/gcae504/SCR1/Solververgleich/Klimakruemmer_AK/CAD/Daimler/fluent-0500.cas"... > > 5429199 mixed cells, zone 29, binary. > > 11187656 mixed interior faces, zone 30, binary. > > 20004 triangular wall faces, zone 31, binary. > > 1104 mixed velocity-inlet faces, zone 32, binary. > > 133638 triangular wall faces, zone 33, binary. > > 14529 triangular wall faces, zone 34, binary. > > 1350 mixed pressure-outlet faces, zone 35, binary. > > 11714 mixed wall faces, zone 36, binary. > > 1232141 nodes, binary. > > 1232141 node flags, binary. > > Done. > > > > > > Writing > > "/home/gcae504/SCR1/Solververgleich/Klimakruemmer_AK/CAD/Daimler/fluent-0500.dat"... > > Done. > > > > 500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 > > 8.3913e-04 3.8545e-03 1.3315e-01 11:14:10 500 > > > > reversed flow in 2 faces on pressure-outlet 35. > > 501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 > > 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 > > > > #------------------------------------------------------------------ > > > > I have a small script, which removes lines starting with > > '(re)versed', '(i)teration' and '(t)urbulent' and put the > > rest into an array: > > > > # -- plot residuals ---------------------------------------- > > import re > > filename="flutest" > > reversed_flow=re.compile('^\ re') > > turbulent_viscosity_ratio=re.compile('^\ tu') > > iteration=re.compile('^\ \ i') > > > > begin_of_res=re.compile('>\ \ \ i') > > end_of_res=re.compile('^\ ad') > > > > begin_of_writing=re.compile('^\Writing') > > end_of_writing=re.compile('^\Done') > > > > end_number=0 > > begin_number=0 > > > > > > n = 0 > > for line in open(filename).readlines(): > > n = n + 1 > > if begin_of_res.match(line): > > begin_number=n+1 > > print "Line Number (begin): " + str(n) > > > > if end_of_res.match(line): > > end_number=n > > print "Line Number (end): " + str(n) > > > > if begin_of_writing.match(line): > > begin_w=n+1 > > print "BeginWriting: " + str(n) > > print "HALLO" > > > > if end_of_writing.match(line): > > end_w=n+1 > > print "EndWriting: " +str(n) > > > > if n > end_number: > > end_number=n > > print "Line Number (end): " + str(end_number) > > > > > > > > > > > > n = 0 > > array = [] > > array_dummy = [] > > array_mapped = [] > > > > mapped = [] > > mappe = [] > > > > n = 0 > > for line in open(filename).readlines(): > > n = n + 1 > > if (begin_number n): > > # if (begin_w n): > > if not reversed_flow.match(line) and not > > iteration.match(line) and not > > turbulent_viscosity_ratio.match(line): > > m=(line.strip().split()) > > print m > > if len(m) > 0: > > # print len(m) > > laenge_liste=len(m) > > # print len(m) > > mappe.append(m) > > > > > > #--end plot > > residuals------------------------------------------------- > > > > This works fine ; except for the region with the writing > > information: > > > > #-----writing information > > ----------------------------------------- > > Writing "/home/fb/fluent-0500.cas"... > > 5429199 mixed cells, zone 29, binary. > > 11187656 mixed interior faces, zone 30, binary. > > 20004 triangular wall faces, zone 31, binary. > > 1104 mixed velocity-inlet faces, zone 32, binary. > > 133638 triangular wall faces, zone 33, binary. > > 14529 triangular wall faces, zone 34, binary. > > 1350 mixed pressure-outlet faces, zone 35, binary. > > 11714 mixed wall faces, zone 36, binary. > > 1232141 nodes, binary. > > 1232141 node flags, binary. > > Done. > > # -------end writing information ------------------------------- > > > > Does anyone know, how I can this 'writing' stuff too The > > matchingIt occurs a lot :-( > > > > the result should be an array with just: > > > 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 > 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 > 500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 8.3913e-04 > 3.8545e-03 1.3315e-01 11:14:10 500 > 501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 > 3.8560e-03 4.8384e-02 11:40:01 499 Sometimes Python is so simple there is a tendancy to overthink the problem Based soley on the input and output in your example and not withstanding errors from the email itself word-wrapping yours and my text: >>> print '\r\n'.join([x.strip() for x in open('c:/flutest.txt') if 'e-0' in x]) 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 500 1.0049e-03 2.4630e-04 9.8395e-05 1.4865e-04 8.3913e-04 3.8545e-03 1.3315e-01 11:14:10 500 501 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 >>> HTH
VIEWS ON THIS POST

215

Posted on:

Monday 5th November 2012
View Replies!

Adjusting the names of custom exceptions (since raising strings is deprecated)

as So this probably highlights my lack of understanding of how naming works in python, but I'm currently using FailUnlessRaises in a unit test and raising exceptions with a string exception. It's working pretty well, except that I get the deprecation warning that raising a string exception is going to go away. So my question is, how do I mangle the name of my exception class enough that it doesnt stick the name of the module before the name of the exception Namely I'd like to get the following *** Traceback (most recent call last): File "", line 1, in MyError: 'oops!' instead of *** Traceback (most recent call last): File "", line 1, in __main__.MyError: 'oops!' (or even test_thingie.MyError as is usually the case). Creating a class in a separate file and then doing *** from module import MyError raise MyError still gives *** Traceback (most recent call last): File "", line 1, in module.MyError Anyway, any help appreciated.
VIEWS ON THIS POST

158

Posted on:

Monday 5th November 2012
View Replies!

cannot declare global vars!

i had posted earlier for not being able to declare global vars. No i followed the suggestions and created a class, but still the vars do not seem to have a global scope. I have tried pretty much everything. Any advice appreciated... Here: ======================================================== #!/usr/bin/env jython #imports .... class SVNLogs2DBParser: #svnLogging_ #dbTable_ #cmterID_ #projID_ #fileIDNumber_ #Commiter_ #Commit_ #StoredProject_ #ProjectVersion_ #entryList_ def __init__(self,svnLogging_=SVNLogging(SVN_REPOS),dbTable_=DBTablesHandler(),cmterID_=0,projID_=0, fileIDNumber_=0,Commiter_={},Commit_={},StoredProject_={},ProjectVersion_={},entryList_={}): pass #svnLogging_=SVNLogging(SVN_REPOS) #print "Connection established to SVN repository..." #dbTable_=DBTablesHandler() #cmterID_=0 #projID_=0 #fileIDNumber_=0 #Commiter_={} #Commit_={} #StoredProject_={} #ProjectVersion_={} #entryList_={} #reads all the revision logs (traversing them PIVOT at a time) and #processes each log entry def getLogsLoop(self): while svnLogging_.getCurrentRevisionNumber()!=svnLogging_.getLatestRevisionNumber(): entryList_=svnLogging_.getNextLogs(PIVOT); #print "Attempting to go over the HEAD revision..." for entry in self.entryList: print "processing new SVN entry..." processLogEntry(entry) entryList_.clear() #processes each log entry # #"entry" is of type SVNLogEntry. See SVNKit API #"changedPaths" is returned as a java.util.HashMap #with key strings (paths) and values SVNLogEntryPath objects #"entry.getDates()" returns a java.util.Date object def processLogEntry(self, entry): revision = int(entry.getRevision()) commiter = str(entry.getAuthor()) datetime = getTimeStamp(entry.getDate()) message = str(entry.getMessage()) changedPaths = entry.getChangedPaths() #array passed for updating the Commiter DB table Commiter_[0] = cmterID_ Commiter_[1] = commiter dbTable_.updateCommiterTable(Commiter_) #array passed for updating the Commit DB table Commit_[0] = projID_ Commit_[1] = datetime Commit_[2] = cmterID_ Commit_[3] = 0.0 Commit_[4] = "" #properties fileStats=getFileTypes(changedPaths) Commit_[5] = fileStats[0] Commit_[6] = fileStats[2] Commit_[7] = fileStats[1] Commit_[8] = fileStats[3] Commit_[9] = fileStats[4] dbTable_.updateCommitTable(self.Commit_) ProjectVersion_[0]=projID_ ProjectVersion_[1]=0.0 dbTable_.updateProjectVersionTable(ProjectVersion_) Project[0]=projID_ Project[1]="" Project[2]="" Project[3]="" Project[4]="" dbTable_.updateProjectTable(Project_) cmterID_+=1 projID_+=1 ##############################HELPER##METHODS############################### .... ##############################HELPER##METHODS###############################
VIEWS ON THIS POST

310

Posted on:

Monday 5th November 2012
View Replies!

using the filter function within class return error

I'm trying to use the __builtin__ filter function within a class; however, I receive the following error: NameError: global name 'MajEthnic' is not defined The line of code is: EthMaj = filter(self.MajEthnic,flist) So, I'm trying to use the MajEthnic function to filter the list flist. Any ideas
VIEWS ON THIS POST

185

Posted on:

Monday 5th November 2012
View Replies!

Re: optparse - required options

Robert Dailey wrote: > Well, I don't know what is wrong with people then. I don't see how > required arguments are of bad design. Some command-line applications are > built around performing tasks based on information received. Compilers, > for example. A compiler can't do much of anything unless you give it at > the very least a filename. So, a --file command would most definitely be > one required argument. Anyway, I'm not trying to start a debate on this > issue. I have my own implementation for required arguments at the > moment, I am just a little bit surprised that this module doesn't make > it convenient. It would definitely help on code duplication. > >
VIEWS ON THIS POST

174

Posted on:

Monday 5th November 2012
View Replies!

Re: reading a line in file

Shawn Milochik wrote: > Hopefully this will help (using your input file) > > #!/usr/bin/env python > import re > buildinfo = "input.txt" > input = open(buildinfo, 'r') > > regex = re.compile(r"^\s*build.number=(\d+)\s*$") > > for line in input: > if re.search(regex, line): > print line > buildNum = re.sub(r"^\s*build.number=(\d+)\s*$", "\\1", line) > print line > print buildNum If the only thing needed is this specific match text, this should be more efficient (re module and regular expressions have a lot of overhead): #!/usr/bin/env python buildinfo = "input.txt" input = open(buildinfo, 'r') token = "build.number=" BUILDNUM = "" for line in input: if line.startswith(token): BUILDNUM = line[len(token):-1] print "Build number: %s" % BUILDNUM
VIEWS ON THIS POST

212

Posted on:

Monday 5th November 2012
View Replies!

Using a time duration to print out data where every 2 seconds is a pixel

, I wonder if any of you could tell me the best way to going about solving this little problem! I have a list of Step objects containing their start and finish times The steps are sorted so that they are in order of their step times The start and finish times are in string format of "%H:%S:%M" all on the same day I want to be able print out the Steps as a visual representation so that I can show 1. The order the steps started 2. The duration of the steps i.e. a print out such as: [ a ] [ b ] [ c ] so: [ stepName ] is the duration of the Step (i.e. 1 pixel for every 2 seconds it lasted) [ a ] started first so it is printed first, [ b ] started x seconds later so it is printed y pixels tabbed away form the side etc etc Any help would be much appreciated. Another related question is that I can't seem to do arithmetic when the variables are in String format of %H:%M:%S or converted to type struct_time i.e. > startPoint = strptime(step.sTime, "%H:%S:%M") > finishPoint = strptime(step.fTime, "%H:%S:%M") > duration = finishPoint - startPoint generates a error: Type error: unsupport operand types for: 'time.struct_time' and 'time.struct_time' trying to do time arithmetic when the times are stored in this format as strings also fails so any help regarding any of this would be muhc appreciated
VIEWS ON THIS POST

199

Posted on:

Monday 5th November 2012
View Replies!

Does shuffle() produce uniform result ?

I have read the source code of the built-in random module, random.py. After also reading Wiki article on Knuth Shuffle algorithm, I wonder if the shuffle method implemented in random.py produces results with modulo bias. The reasoning is as follows: Because the method random() only produces finitely many possible results, we get modulo bias when the number of possible results is not divisible by the size of the shuffled list. 1. Does shuffle() produce uniform result 2. If not, is there a fast and uniform shuffle() available somewhere
VIEWS ON THIS POST

216

Posted on:

Monday 5th November 2012
View Replies!

Naming dictionaries recursively

I'd like to do something like this; iterate through a file which consists of data stored in dictionary format, one dict on each line, and read each line into a new dict using one of the values in the dict as its name... for example: stuff = open('data.txt') for eachLine in stuff: name{} name = eachLine .....and then do something clever to extract the value of the key (name) from the line and use it as the dictionary's name. A line from data.txt would look like this: {'name' : Bob, 'species' : Humboldt, 'colour' : red, 'habits' : predatory}. Aim is to call one of them by name, and merge the values in that dictionary into a string pulled from another source.
VIEWS ON THIS POST

203

Posted on:

Monday 5th November 2012
View Replies!

APL2007 reminder: early (cheaper) registration ends Thursday 9/13

On-line registration is through the OOPSLA registrar http://www.regmaster.com/conf/oopsla2007.html APL 2007 home page http://www.sigapl.org/apl2007.html
VIEWS ON THIS POST

246

Posted on:

Monday 5th November 2012
View Replies!

Re: advice about `correct' use of decorator

BJrn Lindqvist wrote: >On 8/16/07, Gerardo Herzig wrote: > > >>@is_logued_in >>def change_pass(): >> bla >> bla >> >>And so on for all the other functions who needs that the user is still >>loged in. >> >>where obviosly the is_logued_in() function will determine if the dude is >>still loged in, and THEN execute change_pass(). If the dude is not loged >>in, change_pass() is NOT executed at all. Instead, it will be redirected >>to the `login' screen. >> >> > >I think this is redundant use of a decorator. You can achieve the >exact same effect by writing: > >def is_logued_in(): > if not user.is_logged_in(): > raise NotLoggedInError > >It costs you one more line, but reduces complexity. And if you are >worried about that extra line you can put it in a function. > > > As far as i know (by the way, AFAK is the shortcut, and BTW means `by the way' ), decorators are not indispensable. I mean, all that you can do with python, you can doit without decorators. And from my point of view, this hides the complexity for the other developers of my group, since all they have to do is add the @is_logged_in line at the top of the cgi script, and not to worrie about exceptions, not even how the decorator is implemented (i may log the error in some file). they have to know is that any abnormal situation will redirect to the `login' screen. Thank you for your comments! Gerardo
VIEWS ON THIS POST

266

Posted on:

Monday 5th November 2012
View Replies!

Re: Getting original working directory

rave247 rave247 wrote: > If I could use os.getcwd() or save the value to some variable before calling os.chdir() > I would do it, believe me. However I can't because it is the part of code where I > can't do any changes. > > Also I do not agree that such thing is not possible because after python script > finishes its work, it naturally gets back into the original location from where > you started the script (in shell you are in the original location after script > finishes). So this information has to be stored somewhere (probably in shell which > runs the interpreter) and there *must* be a way how to get it. Simply after > calling os.chdir() the original value doen't disappear, I think it just needs > some nice hack if python doesn't provide a way how to get it. > Python runs as a sub-process. The parent process (the one that started Python) contains the working directory that the Python interpreter inherited from it. But you can't expect to just go poking around inside the environment of your parent process, which will typically be waiting for you to finish before it continues. Why *must* there be a way to get at its current directory Once it continues, of course, it does so in the same directory. If you want to hack into your parent process to find that information that's up to you, but Python certainly has no special mechanism for doing it. If you treat the answers to all your questions with so little respect it's a wonder you bother asking the questions in the first place. You didn't even explain what the relationship was between the "myscript" that you want to run and the Python code that you want to switch back to the original working directory. Sorry, we aren't mind readers (though some of the on this list get close on occasion). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading -------------
VIEWS ON THIS POST

219

Posted on:

Monday 5th November 2012
View Replies!

=?us-ascii?Q?Re=3A=20Getting=20original=20working=20directory?=

If I could use os.getcwd() or save the value to some variable before calling os.chdir() I would do it, believe me. However I can't because it is the part of code where I can't do any changes. Also I do not agree that such thing is not possible because after python script finishes its work, it naturally gets back into the original location from where you started the script (in shell you are in the original location after script finishes). So this information has to be stored somewhere (probably in shell which runs the interpreter) and there *must* be a way how to get it. Simply after calling os.chdir() the original value doen't disappear, I think it just needs some nice hack if python doesn't provide a way how to get it. > ------------ Pvodn zprva ------------ > Od: Ian Clark > Pedmt: Re: Getting original working directory > Datum: 06.9.2007 20:31:33 > ---------------------------------------- > rave247 rave247 wrote: > > "......the *original* directory location *after* os.chdir() is > performed......" os.getcwd() is not helping much as it returns the location that > was set up in os.chdir() call > > > >
VIEWS ON THIS POST

193

Posted on:

Monday 5th November 2012
View Replies!