[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

if text == None:
showerror('PyEdit', 'Could not decode and open file ' + file)
else:
self.setAllText(text)
self.setFileName(file)
self.text.edit_reset() # 2.0: clear undo/redo stks
self.text.edit_modified(0) # 2.0: clear modified flag


def onSave(self):
self.onSaveAs(self.currfile) # may be None


def onSaveAs(self, forcefile=None):
"""
2.1: total rewrite for Unicode support: Text content is always
returned as a str, so we must deal with encodings to save to
a file here, regardless of open mode of the output file (binary
requires bytes, and text must encode); tries the encoding used
when opened or saved (if known), user input, config file setting,
and platform default last; most users can use platform default;


retains successful encoding name here for next save, because this
may be the first Save after New or a manual text insertion; Save
and SaveAs may both use last known encoding, per config file (it
probably should be used for Save, but SaveAs usage is unclear);
gui prompts are prefilled with the known encoding if there is one;


does manual text.encode() to avoid creating file; text mode files
perform platform specific end-line conversion: Windows \r dropped
if present on open by text mode (auto) and binary mode (manually);
if manual content inserts, must delete \r else duplicates here;
knownEncoding=None before first Open or Save, after New, if binary Open;


encoding behavior is configurable in the local textConfig.py:



  1. if savesUseKnownEncoding > 0, try encoding from last open or save

  2. if savesAskUser True, try user input next (prefill with known?)

  3. if savesEncoding nonempty, try this encoding next: 'utf-8', etc

  4. tries sys.getdefaultencoding() as a last resort
    """


filename = forcefile or self.my_asksaveasfilename()
if not filename:
return


text = self.getAllText() # 2.1: a str string, with \n eolns,
encpick = None # even if read/inserted as bytes


try known encoding at latest Open or Save, if any


if self.knownEncoding and ( # enc known?
(forcefile and self.savesUseKnownEncoding >= 1) or # on Save?
(not forcefile and self.savesUseKnownEncoding >= 2)): # on SaveAs?
try:
text.encode(self.knownEncoding)
encpick = self.knownEncoding
except UnicodeError:
pass


PyEdit: A Text Editor Program/Object | 703
Free download pdf