Sunday, April 12, 2009

Some Python scripts

Well, as I mentioned in the last post I made, I plan on updating this blog every other Sunday (besides when I'm on vacation). This is the first of that series of updates (on time too!). I've been using Python a lot for small scripts lately, because a) it's good practice, and b) it's efficient. Below are a few scripts I wrote and an explanation of what they do:

Sorry, but the whitespaces seem to be ignored, so I'll post a link to a pastebin for each one as well. (For those who don't know, whitespace is significant in Python since each indentation level denotes a "block" of code, similar to the function of braces "{}" in Java or most other programming languages).

FileCondenser
http://lswest.pastebin.com/f21a592a4
#!/usr/bin/env python
#Script to condense the multiple files of a project into one for easy printing/copying
#Author: lswest
import os
import optparse

def main():
usage="usage: %prog [options] args"
p = optparse.OptionParser()
p.add_option('--origin', '-o', help="The location of the files to be read in.", default="")
p.add_option('--output', '-t', help="The location of the file to which the condensed output will be written.", default="");
p.add_option('--extension', '-e', help="The extension of the files to condense.", default="");
options, arguments = p.parse_args()
if options.origin == "" or options.output == "" or options.extension == "":
p.print_help()
else:
print "Input file: %(o)s*%(e)s \nOutput file: %(t)s" % {'o' : options.origin, 't' : options.output, 'e' : options.extension}
ff=open(os.path.join(options.output), "wt")
for root, dirs, files in os.walk(os.path.join(options.origin), "true", "none", "true"):
for infile in [f for f in files if f.endswith(options.extension)]:
fh=open(os.path.abspath(os.path.join(root,infile)))
for line in fh:
ff.write(line,)
fh.close()
ff.close()

if __name__ == '__main__':
main()
This is a small script that can be run using the arguments ("FileCondenser --help" to see the help information), and is used to take all the files within a directory tree ending in the specified extension, and then copy each line of those files into the output file. I used it for my Computer Science coursework, since I had to print a hard-copy of my code (weird, I know).

LineCounter
http://lswest.pastebin.com/f6c52aaa0
#!/usr/bin/env python
#Program to tally the lines in a file
#Author: lswest
import os
import os
import optparse

def main():
usage="usage: %prog [options] args"
p = optparse.OptionParser()
p.add_option('--file', '-f', help="The path to the file to count.", default="")
options, arguments = p.parse_args()
if options.file == "":
p.print_help()
else:
print "Input file: %s" % options.file
count=0
ff=open(os.path.join(options.file))
for x in ff:
count+=1
values={'name': os.path.join(options.file), 'count' : count}
print "The file %(name)s contains %(count)s lines." % values

if __name__ == '__main__':
main()
This script basically just tallies the number of lines within the specified files, and was done for practice (no real practical reason), but I still thought I'd include it.

updateCheck
http://lswest.pastebin.com/f4d33eb3d
#!/usr/bin/env python
#A program to check if there are any updates available for Arch
#Author: lswest
from subprocess import Popen,PIPE
import os

def main():
p=Popen("pacman -Qu|grep Targets|cut --delimiter=\" \" -f 2|sed -e 's/(//' -e 's/)://'",shell=True,stdout=PIPE)
x=p.stdout.read()
if x != "":
tally=int(x)
if tally == "1":
print "1 package to update"
else:
print "%s packages to update" % str(tally)
else:
print "No packages to update"

if __name__ == '__main__':
main()
I use this script in my Conky on both my PC and laptop, in combination with a cronjob of "pacman -Sy" to update the database, to display the number of available updates for my system.

To Buy.py
http://lswest.pastebin.com/f4b4c9849
#!/usr/bin/env python
## A script to print out my "to buy" list
#Author: lswest
import os

home=os.path.expanduser("~")

for root, dirs, files in os.walk(os.path.join(home,"To Buy")):
for infile in [f for f in files]:
if(infile.endswith("~")!=True):
fh=open(os.path.abspath(os.path.join(root,infile)))
for line in fh:
print "- "+line,
fh.close()
This is a small script that takes all the text files in my To Buy folder, and prints it out, which I use in Conky. I create the text files with just echo "something to buy" > To\ Buy/something.

TO DO.py
http://lswest.pastebin.com/f18550d93
#!/usr/bin/env python
#A script to print out my To Do list
#Author: lswest
import os

home=os.path.expanduser("~")

for root, dirs, files in os.walk(os.path.join(home,"Reminders")):
for infile in [f for f in files]:
if(infile.endswith("~")!=True):
fh=open(os.path.abspath(os.path.join(root,infile)))
for line in fh:
print "- "+line,
fh.close()
Basically the same as above, besides the fact that it's a to-do list.

Well, that's all the scripts I've written so far that are half-way useful. I'm thinking about making a github repository for scripts of mine, so if you think it's a good idea, drop a comment and I'll post an update on the blog with the link if I do it.

*edit* I went ahead and made the github repository: http://github.com/lswest/scripts/tree/master

2 comments:

Anonymous said...

Hi Lucas! I'm a member of fullcircle-ru translation team and I have several questions regarding your article for issue 24. Please let me know how I can contact you. Thanks :)

Anonymous said...

Amiable post and this mail helped me alot in my college assignement. Gratefulness you on your information.