Hello all,

I have a very rookie question to ask. I am using Pyraf, Python, Sextractor, & a sextractor wrapper to do some automatic photometry on celestial images.

The following code I have written is used to extract info from a sextractor catalog such as image positions, image magnitudes, etc:

catalog_f=sextractor.open('Z2.cat')
    catalog=catalog_f.readlines()
    filename="Z2X.txt"
    sys.stdout=open(filename, 'w')
    for star in catalog:
       print star['X_IMAGE']
    sys.stdout=sys.__stdout__

Now, I am still learning python and I am still unclear on how to create functions (i.e. def etc). I have to use the above code many times in a single script to extract various fields from different catalogs.

So my question is this: is there a way to turn this bit of code into a function that I can call upon at a later time, where I specify the catalog (eg. 'Z2.cat'), the file name to write to (eg. 'Z2X.txt) and the field(s) to extract (eg. 'X_IMAGE').

Many thanks in advance,
Zach

Take a look as post #3 in the "starting python" topic at the top of the topics list on the Daniweb page. Basically, it would be

def function_name(catalog_f_name, write_filename):
    catalog_f=sextractor.open(catalog_f_name)
    catalog=catalog_f.readlines()
    sys.stdout=open(write_filename, 'w')
    for star in catalog:
       print star['X_IMAGE']
    sys.stdout=sys.__stdout__ 

## this calls the function with the appropriate names
function_name('Z2.cat', 'Z2X.txt')

thanks wooee for your reply and help.

One thing, in the print statement:

print star['X_IMAGE']

There are many times where I will need to print many many fields (i.e. RA, DEC, MAGNITUDE, etc). Is there a way to write the function where I can specify which fields I want to extract?

Thanks again for your help!

Zach

Yeah thats not too hard:

def printfunc(star=star, *printers):
    for item in printers:
        print star[item]
        #if you want it all on one line then use pring star[item],
This article has been dead for over six months. Start a new discussion instead.