Документ взят из кэша поисковой машины. Адрес оригинального документа : http://www.stsci.edu/spst/UnixTransition/doc/sms_edit.py
Дата изменения: Fri Feb 28 14:46:12 2014
Дата индексирования: Sat Mar 1 14:18:14 2014
Кодировка:

Поисковые слова: orion nebula
#
#MODULE sms_edit
#
#***********************************************************************
"""

**PURPOSE** --
Edit an SMS manually..

Based on SMSEDIT.COM

**DEVELOPER** --
Gary Bower

**MODIFICATION HISTORY** --

o Initial implementation 12/18/01
o Include modifications from Python review - G. Bower 1/14/02
- abort if editor environment variable is not set
- use shutil.copy instead of UNIX cp
- delete the difference message and text files at end
- use the time of last modification for the database instead of
current time
- add comments by editing a template file, rather than line editing
o Include modifications from Python review - G. Bower 2/13/02
- test that the program is being run on a Sun
- separate comment from keyword before adding to db
- format time of edit for consistency with previous entries in db
- use spss_sys_util.filecopy instead of shutil
o Mods for Mac OS X - M. Reinhart 3/15/05
"""
#***********************************************************************
import errno, spss_sys_util, string, os, stpydb, time_util
import stat, time

__version__ = "3/15/05"

def run(sms_id=None):
"""Edit an SMS manually and send e-mail message containing the changes
to a distribution list.

Usage:
do sms_edit

sms_id must be a valid SMS id

This program uses the editor pointed to by the environment
variable EDITOR.

"""

# This module works only on Sun or Mac.
if (not (spss_sys_util.on_sun() or spss_sys_util.on_mac())):
print "Error: sms_edit works only on Sun or Mac."
return not spss_sys_util.SUCCESS

if not sms_id:
# Spew out the usage and quit when no Mission Schedule run name
# is provided.
print run.__doc__
return spss_sys_util.SUCCESS

# Get the passops directory, and build the
# path to the input SMS, then test path to SMS for existence.
passops = spss_sys_util.resolver("PASSOPS")
if sms_id[-4:] != '.sms':
sms_id_root = sms_id
sms_id = sms_id + '.sms'
else:
sms_id_root = sms_id[:-4]
path = os.path.join(passops,'msin',sms_id)
if not os.path.exists(path):
raise IOError(errno.ENOENT,os.strerror(errno.ENOENT),path)

# Change working directory to passops + msin. Set directory for backup copy.
# Changing directories is acceptable in this case since we are editing files.
smsdir = os.path.join(passops,'msin')
os.chdir(smsdir)

# Copy the sms to save a backup copy of the unedited version.
spss_sys_util.filecopy(sms_id,sms_id_root + '_unedited.sms')

# Edit the SMS.
editor = spss_sys_util.get_environ_variable('EDITOR')
if editor:
do_edit = spss_sys_util.command(string.join(editor) + ' ' + sms_id)
else:
print "EDITOR environment variable was not found. Abort now ..."
return not spss_sys_util.SUCCESS

# Compare the edited version of the sms to the original. Flag if there are no
# differences, prompt the user if they want to re-edit or quit.
old = open(sms_id_root + '_unedited.sms','r').readlines()
while(1):
new = open(sms_id,'r').readlines()
if new == old:
print "No differences detected between the edited SMS and the original."
print "Ensure that the new file overwrites the old file."
ans = string.lower(raw_input("Would you like to (R)e-edit the SMS or (Q)uit? "))
if ans == 'r':
do_edit = spss_sys_util.command(string.join(editor) + ' ' + sms_id)
else:
# Return with a success because the user has decided not to edit the SMS.
return spss_sys_util.SUCCESS
else:
break

# Save the differences between the old and new SMS files into a difference file.
com = 'diff ' + sms_id + ' ' + sms_id[:-4] + '_unedited.sms > ' + sms_id[:-4] + '_edit_dif.txt'
do_diff = spss_sys_util.command(com)

# Prompt the user to place comments into the sms_id_root"_edit.dif.msg" file and append the
# edit_dif.txt file. Use the editor on a template for this.
print "Enter comments on the reason for changing the SMS.\n"
print "%s will start with the SMS differences and template fields for" % editor
print "comment and name.\n"
print "Only the first 80 characters in the first line of the comments field will go"
print "into the database. "
pause_now = raw_input("Press return to continue.")
# Create the template file.
f = open(sms_id_root + '_edit_dif.msg','w')
f.write("Reason for changing SMS: \n")
f.write("Name: \n")
# Write a divider between comments and difference.
f.write("-" * 40 + "\n")
diff_list = open(sms_id_root + '_edit_dif.txt','r').readlines()
f.writelines(diff_list)
f.close()
# Now edit this file to allow user to fill in template fields.
do_edit = spss_sys_util.command(string.join(editor) + ' ' + sms_id_root + '_edit_dif.msg')
# Find and read the first 79 characters of the comment in the edited file. This is to be stored
# in the database. The restriction to 79 characters is imposed to avoid overflowing the
# database field.
f = open(sms_id_root + '_edit_dif.msg','r')
found = 0
eof = 0
while (not found) and (not eof):
line = f.readline()
if (string.find(line,'Reason for changing SMS:') != -1):
found = 1
# The comment is found by splitting off keyword, then strip the trailing whitespace.
comment = string.strip(string.split(line,'Reason for changing SMS:')[1][0:80])
if (not line):
eof = 1
print "Warning: The comment was not found in the differences file."
print "\t No comment is being added to the database."
f.close()

# Copy the edited SMS to the spss_data_dk area.
# Although path is owned by plantest, planinst should have write privelege.
spss_data_dk = spss_sys_util.resolver("SPSS_DATA_DK")
path = os.path.join(spss_data_dk,'instruct','todev','.')
spss_sys_util.filecopy(sms_id,path)

# E-mail the changes to the SMS to the distribution list.
distr = spss_sys_util.resolver('PE_DAT','editreq.dis')
subject = "Edit to SMS " + sms_id
file = sms_id_root + '_edit_dif.msg'
spss_sys_util.mail(distr,subject,file,1)

# Get the modification time for the SMS to put into the database.
# os.stat returns a tuple containing the stats of the sms_id file;
# stat.ST_MTIME finds the modification time in integer sec since 1970.0.
# Then time.ctime() converts that to a string in UTC.
modtime = time.ctime(os.stat(sms_id)[stat.ST_MTIME])
# Change the format of this time to be consistent with the format used previously.
# An example time format in the pass_sms_edits relation is 30-DEC-1999 16:21;
# however,the format of modtime is Wed Feb 13 15:10:04 2002.
modtime_spss = time_util.spss_time().strptime(modtime,'%a %b %d %H:%M:%S %Y')
modtime_db = time_util.spss_time(modtime_spss).strftime('%d-%b-%Y %H:%M')
# Update the pass_sms_edits relation
print ""
print "Updating pass_sms_edits relation at ",modtime_db," ..."
print ""
dbconn = stpydb.stpydb(dbmsName=spss_sys_util.get_environ_variable("SPSS_DB")[0])
dbconn.beginTransaction()
dbconn.query("insert into pass_sms_edits")
dbconn.query(" (pass_sms_id,")
dbconn.query(" sms_edit_done,")
dbconn.query(" comments)")
dbconn.query("values")
dbconn.query(" (@sms,@now,@txt)")
dbconn.setParam([['sms', sms_id[:-4]],['now', str(modtime_db)],['txt', comment]])
dbconn.executeUpdate()
rows = dbconn.getRowcount()
if rows == 1:
dbconn.commitTransaction()
else:
print "Error: pass_sms_edits relation not updated because nrows = ",rows
dbconn.rollbackTransaction()

# Clean up. Delete the differences message and text files.
os.remove(sms_id_root + '_edit_dif.msg')
os.remove(sms_id_root + '_edit_dif.txt')


return spss_sys_util.SUCCESS