Perhaps this is something that is inherently understood by “coders”, but as a newbie code writer, I had to figure this out on my own. It’s much more efficient to make your own tools and reference them over and over than it is to write the same code over and over in each little script you make.
I didn’t come to realize that I had things I wanted to do over and over until I had a library of scripts and started to see patterns. Some of the ‘do-overs’ are things like FTP all the files in a folder to our FTP site, or email myself a note once a script has completed (or even if it has failed), or log events into a table or file as the script progresses.
This sort of thing was intimidating as I was reading python tutorials and the samples use things like double underscores and references to “self” in a def statement. I still have no idea what those do (I”ll let you know if I figure it out!) but honestly I haven’t needed it yet. It doesn’t have to be that complicated.
To make this work, you’ll need a “library” folder that your other scripts can reference. You’ll write the small bits of code that are going to get reused and store them in the library folder. For this example I’ll demonstrate how to send the contents of a folder to an FTP site.
The first step is to write the bit of script that will be reused. We need to write it generically so that any file will work. We are defining a tool that needs a source directory, a list of files to send, and an output path on the FTP server. Here’s how it looks:
# written for python version 2.6
import sys, os
def Send(source_directory_path, input_list, ftpOutputPath):
try:
from ftplib import FTP
#establish the FTP connection
ftp = FTP('ftp.yourserver.com')
ftp.login("yourlogin","yourpswd")
#move to the right output diretory
ftp.cwd(ftpOutputPath)
#copy the files from the list to the output directory
for i in input_list:
#stor is the ftp command, i is the item in the list
sendThis = 'STOR ' + i
fullPath = os.path.join(source_directory_path, i)
f = open(fullPath, 'rb')
ftp.storbinary(sendThis, f)
f.close()
#close the connection politely
ftp.quit()
# if things go wrong, this should return control to the calling script
except:
sys.exit()
- an input directory (everything within a folder will get sent to the ftp site)
- a list of files in that input directory
- the path to the output FTP folder
Here’s the set up:
<your script did stuff here> print "\n SENDING TO FTP" # variable inputpath is defined earlier in the script as an actual path input_list = os.listdir(inputPath + '/sendFolder') source = inputPath+ '/sendFolder' Path = "FTPpath/ftpFolder" ftp_files.Send(source, input_list, Path)