I would like to write a function in Python that will take arguments just like print does but instead of printing the strings to stdout, I would like to write the strings formatted into a text file.
How do I define the arguments for such a function arguments to accept the string formatting, I’m wondering?
I am looking for something that would replace
print "Test"
with
MyLog "Test"
but the % rguments should also be supported.
So far I have only come up with this:
def logger(txt):
fh = open (LOGFILE, "a") #Get handle in append mode
fh.write(txt)
fh.close()
print txt
return True
which works fine for a simple string but i don’t think it’ll take the % arguments nor will I be able to call it like logger “TEST”
You can use the “print chevron” statement to do what you want like this:
See the documentation for the print statement.
Of course, it probably is better practice to use the
print()function as Martijn Pieters suggests.Update
If I change your
loggerfunction to use the print chevron syntax, I get this:If you call this function like:
You’ll have a line in your log file that looks like this:
So you can use this with the
%formatting (although you really should take a look at the new-style formatting), but you won’t be able to call it like:That’s because print is a simple statement, which is a language level construct, and you can’t add those to Python.