def compileCommand(sourcePath, outputPath):This trick uses the dict
switches = "-O0 -g"
return "gcc -c %(switches)s %(sourcePath)s -o %(outputPath)" % locals()
locals()
to supply the values for formatting the string with the '%
' signs in it. The names inside the parens are resolved with the local variable names in the function. Example usage of the above function:
cmd = compileCommand("hello.c", "hello.o")
assert cmd == "gcc -c -O0 -g hello.c -o hello.o"
2 comments:
Thats the old way of string formatting, the new way would be:
return "gcc -c {switches} {sourcePath} -o {outputPath}".format(**locals())
I much prefer the str.format function over the '"%s" % variable' method
That does look a lot better. However, it's not available until Python 2.6. At work, I'm writing in Python 2.4.
Post a Comment