Need help optimizing first script

Lonnie Princehouse fnord at u.washington.edu
Thu Jun 19 13:49:15 EDT 2003


Hi Frederic, welcome to Python.

I find that it's helpful to use the raw string syntax when 
mucking about with lots of Windows paths, i.e. r'\\server\foo'
instead of '\\\\server\\foo'

The formatting operator can be more readable than adding strings:
    execlog = r'%s\logs\trace%s.log' % (dirSource, fDate)
instead of 
    execlog = dirSource + '\\logs\\trace' + fDate + '.log'   

Whenever you find yourself doing something like this:
>     (Iyear, Imonth, Iday, Ihour, Iminute) = (time.localtime(now)[:5])
>     year = str(Iyear)
>     month = str(Imonth)
>     day = str(Iday)
>     hour = str(Ihour)
>     minute = str(Iminute)

It can probably also be with map():

year, month, day, hour, minute = map(str, time.localtime(now)[:5])





popup391 at yahoo.com (Frederic Lafleche) wrote in message news:<a34b632.0306190503.32483efe at posting.google.com>...
> I put this script together mainly from bits and pieces I picked up in
> this newsgroup and one or two books lying around. What it does is map
> a given NT network drive and copy a file to it if some conditions are
> met.  As this is my first script, I'm looking for ways to improve code
> in any possible way, whether it's overall design, style, grammar,
> logic, readability, performance, validation, anything.
> 
> #copyacs.py
> import os, shutil, sys, time, win32file
> from win32wnet import WNetAddConnection2, error
> 
> # Functions
> 
> # Generate timestamp
> # OUTPUT: string in yyymmddhhmm format
> def determineFN():
>     # Get current time
>     now = time.time()
>     # Parse elements
>     (Iyear, Imonth, Iday, Ihour, Iminute) = (time.localtime(now)[:5])
>     year = str(Iyear)
>     month = str(Imonth)
>     day = str(Iday)
>     hour = str(Ihour)
>     minute = str(Iminute)
>       
>     # Padding
>     if len(month) == 1:
>         month = '0' + month
>     if len(day) == 1:
>         day = '0' + day
>     if len(hour) == 1:
>         hour = '0' + hour
>     if len(minute) == 1:
>         minute = '0' + minute
> 
>     return year + month + day + hour + minute
> 
> # Map network drive
> def use (drive, host, user, passwd):
>     try:
>         WNetAddConnection2 (1, drive, host, None, user, passwd)
>         return 0
>     except error:
>         return 1
> 
> # Variable assignments
> 
> devicename = 'I:' # Enter network drive number.  Ex. format: 'Z:'
> dirTarget = devicename + '\\it\\popup' # Enter target path.
> sharename = '\\\\afs\\grps'            # Enter shared resource name.  
> username = 'login' # Enter user account inside single quotes
> password = 'password' # Enter user password inside single quotes
> drives = []                                 
> drivemask = win32file.GetLogicalDrives()    # Bitmask
> acsMode = sys.argv[1]    # Get second command-line argument of list.
>                          # (First argument is program name.)
> dirSource = 'd:\\oracle\\acs\\' + acsMode   # Source directory
> acsfile = 'import.txt'                      # File to copy
> sourceacsfile = dirSource + '\\' + acsfile  # Absolute path
> 
> # Main body
> 
> fDate = determineFN()
> execlog = dirSource + '\\logs\\trace' + fDate + '.log'                
>          # Operations log
> timestring = time.strftime("%Y-%m-%d %H:%M:%S",
> time.localtime(time.time()))    # Timestamp
> 
> if os.path.isdir(dirSource + '\\logs'):     # Log path exists?
>     fObject = open (execlog, 'w')
>     fObject.write(timestring + '\n')
> else:
>     sys.exit()
> 
> # List drives
> for drive in range(ord("A"), ord("Z") ):
>      if drivemask & 1 != 0:
>           drives.append( chr(drive) )
>      drivemask = drivemask >> 1
> 
> # Cut ":" suffix off devicename.
> # To test whether a value is in the list, use *in*,
> # which returns 1 if the value is found or 0 if it is not.
> 
> # If drive not mapped, map it.
> if devicename[0] not in drives:
>     if not (use(devicename, sharename, username, password)):
>         fObject.write('Cannot map device.\n')
>   
> if os.path.isfile(sourceacsfile):           # Source file exists?
>     if os.path.isdir(dirTarget):            # Target path exists?
>         shutil.copyfile(sourceacsfile, dirTarget + '\\' + acsfile)
>         fObject.write(sourceacsfile + ' copied.\n')
>         if os.path.isdir(dirSource + '\\sav'):
>             os.rename(sourceacsfile, dirSource + '\\sav\\import' +
> fDate + '.txt')
>     else:
>         fObject.write('Cannot access destination path ' + dirTarget +
> '.\n')
> else:
>     fObject.write('Source file ' + sourceacsfile + ' does not
> exist.\n')
>     fObject.write('Transfer aborted.\n')
> 
> fObject.close()
> 
> # End of main body




More information about the Python-list mailing list