View previous topic :: View next topic |
Author |
Message |
Schizoid Apprentice
Joined: 11 Apr 2003 Posts: 267
|
Posted: Tue Nov 04, 2003 7:02 am Post subject: Fun with Python. "WinXP like" camera wizard + scre |
|
|
Two weeks ago I started reading about Python. So far it seems to be quite a simple language to learn.
Anyway I have made these two scripts. They are not "gentoo specific" so if this is in the wrong forums please forgive me.
Obviously I am new at this so my code might not live up to some higher standards but they all work on the computers I have tried them on and only use the standard python modules. I have python 2.2.3 on my system; as far as I can tell they should work on anything 2.2.0 or above and maybe lower.
Both of these scripts require you to insert the mount path for your device, ftp server info etc to work. Take a look at the first few dozen lines of code in each and I think it should be quite obvious what to do.
Camera script:
This first script tries to duplicate the basic functions of WindowsXP's "Camera & Scanner Wizard" . . .ignoring the scanner part and the pretty interface of course.
It can mount/umount your device, copy/move/delete your files, and rename them sequentially if you like.
Oh if you use supermount or some sort of automounter for your filesystems I wouldn't recommend using the mount function of this script. It just invokes the standard mount /mnt/bla command which I don't think will make your automounter happy.
Code: |
#!/usr/bin/python
"""
http://www.patbert.com
This script should copy your cameras files to a directory on your hard drive
whos name is the date the file was taken on. It can rename the files sequentially
for you if you like, as well as delete the originals.
"""
import time, os, stat, getopt, sys
delFile = 1 # - Delete the original file
savenames = 0 # - Keep the original filename, otherwise use 'photoname###'
plzMount = 1 # - Mount/unmount the device. mountpath must point to a valid
# place in your fstab.
mountpath = "/mnt/memstick/" # - Camera mount point (must be in fstab)
camerapath = "dcim/100msdcf/" # - Path to images on camera when mounted
photopath = "/home/patrick/Documents/Images/Photos/" # - Path you want to copy/move your photos to
photoname = "Image" # - When renaming, this is the initial name
# which it will add a file number to
# Command Line Options in case ur dumb
def commandOptHelp():
print "Camera Photo Copier by Kibler. http://www.patbert.com"
print
print "usage: --help --save --nodel --mount-off --photo-name=<filename>"
print "usage: -h -s -n -m -p=<filename>"
print
print " -h, --help This help dialog."
print " -s, --save Use the original filenames when copying."
print " -n, --nodel The original file will not be removed."
print " -m, --mount-off Do not perform a mount/umount"
print " -p=, --photo-name= Filename prefix if renaming"
print
print " Example: --save -n --mount-off -p=Picture"
print
sys.exit(2)
# Take a look at what options were passed, if any
def optCheck():
try:
opts, args = getopt.getopt(sys.argv[1:], "hsnmp:", ["help", "save", "nodel", "mount-off", "photo-name="])
except getopt.GetoptError:
commandOptHelp()
for o, a in opts:
if o in ("-h", "--help"):
commandOptHelp()
if o in ("-s", "--save"):
global savenames
savenames = 1
if o in ("-n", "--nodel"):
global delFile
delFile = 0
if o in ("-m", "--mount-off"):
global doMount
doMount = 0
if o in ("-p", "--photo-name"):
global photoname
photoname = a
# Run the option check
optCheck()
# Mounts/unmounts the device
def doMount(mountpath,dowhat):
if dowhat == "mount":
if os.path.ismount(mountpath) == 0:
print "Mounting", mountpath
os.system("mount %s" % mountpath)
else:
print "Looks like", mountpath, "is already mounted."
elif dowhat == "umount":
if os.path.ismount(mountpath) == 1:
print "Unmounting", mountpath
os.system("umount %s" % mountpath)
else:
print "Looks like", mountpath, "is already unmounted."
else:
print dowhat, "is not a valid option for 'dowhat.'"
sys.exit(2)
# Perform a mount?
if plzMount == 1:
doMount(mountpath, "mount")
else:
print "Assuming drive is already mounted. . ."
# Creat a list using the filenames on the camera
photolist = os.listdir(mountpath + camerapath)
# If photolist is empty (no files) exit gracefully
if photolist == 0:
print "No files to copy, exiting."
sys.exit(2)
# Finds and stores the file extention of the files. Used when making new file names.
def getExt():
sup = photolist[0]
nmu = sup[-4:]
return nmu
# Make the initial filename
filenum = 1
pext = getExt()
npname = photoname + str(filenum).zfill(3) + pext
# Copies the files
def fileCopy(ifilename,ofilename,pdate):
print "Copying %s. . ." % ifilename
ifile = open(mountpath + camerapath + ifilename, "r")
ofile = open(photopath + pdate + "/" + ofilename, "w")
pdata = ifile.read()
print " - Writing %s. . ." % ofilename
ofile.write(pdata)
ofile.close
ifile.close
# Checks to see if the directory exists
def checkDir(pdate):
return os.path.exists(photopath + pdate)
# Find & return the "last accessed" date of the file. This should be the creation date.
def getFiledate(filename):
filestat = os.stat(mountpath + camerapath + filename)
ppdate = time.strftime("%Y, %m, %d", time.localtime(filestat[8]))
pdate = str(ppdate[0:4]) + "-" + str(ppdate[6:8]) + "-" + str(ppdate [10:12])
return pdate
# For every filename in the photolist, move/copy/rename/delete the file
def readFiles(npname,filenum,pext):
while photolist:
pdate = getFiledate(photolist[0])
while checkDir(pdate) == 0:
os.mkdir(photopath + pdate)
if savenames == 0:
while os.path.isfile(photopath + pdate + "/" + npname) == 1:
filenum = filenum + 1
npname = photoname + str(filenum).zfill(3) + pext
newname = npname
else:
newname = photolist[0]
fileCopy(photolist[0], newname, pdate)
if delFile == 1:
os.remove(mountpath + camerapath + photolist[0])
del photolist[0]
if savenames == 1:
print "Using original filenames. . ."
# Go go go
readFiles(npname, filenum, pext)
# Unmount?
if plzMount == 1:
doMount(mountpath, "umount")
|
Screenshot script:
This is the first script I wrote. It invokes the basic "import" command to take a quick snapshot of your X desktop and then optionally uploads it to a designated ftp/web server. 99.9% of the time I take a screenshot it is to share it on the web so this just automates the task quite nicely.
It will always make sure to create a unique file name based on the date. Kinda neat I think; but hey I am new at this so anything that I typed that actually runs impresses me.
It has a few basic options like filetype and the option to remove the local file after it has been uploaded.
Code: |
#!/usr/bin/python
"""
http://www.patbert.com
This will hopefully take a screenshot using the import command
and upload it to an ftp if you tell it to.
If your ftp info is not correct who knows what will happen!
"""
# ftp info, if you don't change this using the --ftp option will fail
ftpname = "Website Hosting"
ftpaddr = "ftp.website.com"
ftpuser = "ftp-username"
ftppass = "ftp-password"
ftpdir = "/webroot/screencaps"
siteurl = "http://www.website.com/screencaps/"
# Defaults
filetype = "png"
useftp = 0
delfile = 0
fileList = []
import os, string, time, getopt, sys
# Command Line Options in case ur dumb
def commandOptHelp():
print "Screenshot/FTP Program by Kibler. http://www.patbert.com"
print ""
print "usage: --help --type=<file type> --ftp --del"
print "usage: -h -t=<file type> -f -d"
print
print " -h, --help This help dialog."
print " -t=, --type= File type:", filetype, "is the default."
print " eps"
print " jpg"
print " miff"
print " png"
print " -f, --ftp The program will ask if you would like"
print " to upload to the defined FTP site."
print " -d, --del The local file will be removed after"
print " it is uploaded to the server."
print
print " Example: --type=eps --ftp -d"
print
sys.exit(2)
# Take a look at what options were passed, if any
def optCheck():
try:
opts, args = getopt.getopt(sys.argv[1:], "ht:fd", ["help", "type=", "ftp", "del"])
except getopt.GetoptError:
commandOptHelp()
for o, a in opts:
if o in ("-h", "--help"):
commandOptHelp()
if o in ("-f", "--ftp"):
global useftp
useftp = 1
if o in ("-t", "--type"):
global filetype
filetype = a
if o in ("-d", "--del"):
global delfile
delfile = 1
# Generate the initial filename
filenum = 1
filename = "snap%s-%s.%s" % (time.strftime("%m%d%y"), str(filenum), filetype)
# Take the screenshot
def makeSnap(filename):
print "Taking screenshot. . ."
snapoutput = "import -silent -window root " + filename
os.system(snapoutput)
filesize = os.path.getsize(filename)
print "File is", filesize, "bytes."
# Create a list from the ftp filenames
def ftpList(y):
for x in [y]:
fileIndex = string.rfind(y, " ")
fileList.append(y[fileIndex+1:])
# Take a screenshot and exit, don't bother with FTP
def goLocal(filename,filenum):
print "Creating unique filename. . ."
while os.path.isfile(filename) == 1:
filenum = filenum + 1
filename = "snap%s-%s.%s" % (time.strftime("%m%d%y"), str(filenum), filetype)
else:
if delfile == 1:
print "-d/--del switch ignored."
makeSnap(filename)
print filename, "should now be in your current directory."
# Connects to the remote ftp site, creates a unique file name,
# takes the screenshot, and deletes the local file if asked
def goFTP(filename,filenum):
localnames = os.listdir(".")
import ftplib
ftp = ftplib.FTP(ftpaddr)
ftp.login(ftpuser,ftppass)
ftp.cwd(ftpdir)
ftp.dir(".", ftpList)
allnames = localnames + fileList
print "Creating globally unique filename. . ."
while filename in allnames:
filenum = filenum + 1
filename = "snap%s-%s.%s" % (time.strftime("%m%d%y"), str(filenum), filetype)
else:
makeSnap(filename)
openfile = open(filename, "r")
print "Uploading file. . ."
ftp.storbinary("STOR %s" % filename, openfile)
ftp.quit()
ftp.close()
openfile.close()
print "Upload complete."
if delfile == 1:
print "Deleting local file. . ."
os.remove(filename)
print "Hope it worked.", filename, "should now be on your server."
print siteurl + filename
# Run the option check
optCheck()
# To ftp or not ftp
if useftp == 0:
goLocal(filename,filenum)
else:
goFTP(filename,filenum)
|
I hope some of you can make some use out of these! Please let me know what you think. |
|
Back to top |
|
|
Stu L Tissimus Veteran
Joined: 08 Jun 2003 Posts: 1339 Location: NJ, 5 minutes from NYC
|
Posted: Tue Nov 04, 2003 4:18 pm Post subject: |
|
|
Wow, very nice... I also started teaching myself Python recently. It's a great language. _________________ old outdated sig |
|
Back to top |
|
|
hadfield Retired Dev
Joined: 18 Mar 2003 Posts: 308 Location: Vancouver, BC, Canada
|
Posted: Tue Nov 11, 2003 1:27 am Post subject: |
|
|
I'm a bit confused about your camera script. I didn't know I could just mount my camera... I thought I needed some kind of interface like gphoto to connect to it. Can you mount ANY digital camera, or only specific models? How would I find out which device my camera uses if it is possible to mount it? |
|
Back to top |
|
|
nazul n00b
Joined: 15 Apr 2003 Posts: 18 Location: Manchester, UK
|
Posted: Tue Nov 11, 2003 11:49 am Post subject: |
|
|
My camera is mountable - its a olympus C750 ultra. I knew it would be from the start though as windows thinks its a mass storage device.
i would probably think that all camera's are. Heres a great tutorial for USB ones that I used to get mine working https://forums.gentoo.org/viewtopic.php?t=53537&highlight=usb+mass+storage |
|
Back to top |
|
|
grant.mcdorman Apprentice
Joined: 29 Jan 2003 Posts: 295 Location: Toronto, ON, Canada
|
Posted: Tue Nov 11, 2003 5:16 pm Post subject: |
|
|
shadfiel wrote: | I'm a bit confused about your camera script. I didn't know I could just mount my camera... I thought I needed some kind of interface like gphoto to connect to it. Can you mount ANY digital camera, or only specific models? How would I find out which device my camera uses if it is possible to mount it? | Depends on the make & model. I have an Olympus C-3000Z; that requires gphoto2 (or an app that uses gphoto2 libraries). Other Olympus models do work as "hard drives"; however apparently in some firmware versions Olympus got an ID string wrong, so a change to the USB mass storage driver is (or was?) needed to get them recognized.
In general, however, any camera model less than about a year or so old will use the USB mass storage mode; older camera models vary.
EDIT: To see if your camera shows up as a USB storage device, try loading the USB storage drivers (they need to be configured in your kernel & modprobe'd if built as modules), and check in /dev - can't tell you the device name offhand, as I'm at work right now. |
|
Back to top |
|
|
Schizoid Apprentice
Joined: 11 Apr 2003 Posts: 267
|
Posted: Wed Nov 12, 2003 10:59 pm Post subject: |
|
|
If your camera shows up as a hard drive it will only work if you have:
USB Mass storage support
SCSI Support
SCSI Generic Support
SCSI Disk Support
Assuming you don't have any other scsi devices it will appear as /dev/sda1 when you plug it in.
You also probably need vfat file system. |
|
Back to top |
|
|
dl1vr8r n00b
Joined: 07 Mar 2003 Posts: 39 Location: SLC
|
Posted: Thu Nov 13, 2003 5:23 am Post subject: |
|
|
Under kernel 2.4, my camera (Minolta S404) required an edit in unusual_devs.h before I compiled my kernel. Under 2.6, it is automatically detected when I plug it in with no additional steps. One of the many great things about 2.6 |
|
Back to top |
|
|
hadfield Retired Dev
Joined: 18 Mar 2003 Posts: 308 Location: Vancouver, BC, Canada
|
Posted: Thu Nov 13, 2003 5:40 am Post subject: |
|
|
That's sweet. Perhaps I'll be switching to 2.6 sooner than planned... My Kodak is definately not being recognized as a drive with my current setup. It's a couple years old though. |
|
Back to top |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|