Mostly Linux & Python syntax notes and hyperlinks.

Tuesday, September 15, 2009

python day 2: functions, if, else, TypeError

To create a function, define it before you need to use it, and don't forget the colons. Not for the if either. (Python seems to like colons. It's kind of like how C likes semicolons, and Lisp likes parentheses.)

import os, sys

def run_cmd(cmd,fd):
try:
if sys.platform.startswith("win")
print cmd
fd.write('running cmd from win: '+cmd+'\n')
EXITCODE = os.system(cmd) >> 8
#Here's where I got the TypeError:fd.write('cmd returned '+EXITCODE+'\n')
else:
import popen2
process = popen2.Popen3(cmd)
EXITCODE = process.wait() >> 8
return EXITCODE
except:
print "run_cmd: Some Exception Caught."
fd.write('run_cmd: Some Exception Caught\n')

The TypeError complained:

    TypeError: cannot concatenate 'str' and 'int' objects

I didn't realize Python was so fussy about types. I thought it was a cavalier sort of Javascript kind of interpreted thingy. OK, so to solve that...it looked like I needed to use a sort of C syntax with the print statements, but that wasn't quite right. I tried it, but got another TypeError:

      fd.write('cmd returned %d\n',EXITCODE)
TypeError: function takes exactly 1 argument (2 given)

Oh, wow, this really is fussy. Experimenting with the shell again:

    >>> num=3
>>> num
3
>>> print "%d" %(3)
3
>>> print "num=%d" %(num)
num=3
>>> print "num=%d" % num
num=3

OK, so it's not C/Java. I need to say:

    fd.write('cmd returned %d\n' % EXITCODE)

Now it works.

One weird thing is that the tutorial I've been using has both %d and %i listed as "signed decimal integer". The python.org page on string formats only lists the 'd' as an integer type, so I'll stick with that. Researching further, there's a section on String Formatting Operations that lists both d and i again. Must be some historic reason for it...

No comments:

Post a Comment