← Back to team overview

sikuli-driver team mailing list archive

Re: [Question #246394]: Write to same file from different modules

 

Question #246394 on Sikuli changed:
https://answers.launchpad.net/sikuli/+question/246394

    Status: Open => Answered

RaiMan proposed the following answer:
Since code on the indent level 0 (not in def()s or classes) is run at import time and ONLY ONCE at import time, the statement
logfile = file("C:\\Users\\caan\\Documents\\SikuliTests\\TwoImports\\output.txt","w")

is executed at import Method1 (and it is executed twice, since Method1
imports Method2 at import) and it contains an implicit open of the file.

then you call
Method1.tst1()

which writes to the file and then closes it.

at rerun, the file is closed and not opened again, since
logfile = file("C:\\Users\\caan\\Documents\\SikuliTests\\TwoImports\\output.txt","w")
is not rerun (index level 0 code !)

so the easiest correction is to simply put the 
logfile = file("C:\\Users\\caan\\Documents\\SikuliTests\\TwoImports\\output.txt","w")
as 1st statement into the def()s and everything is fine ;-)

and you have to use "a" instead of "w", to open the file in append mode
("w" will always clear the file and only write the one record)

But what you are doing is against the DRY design pattern: don't repeat yourself:
the log-open-write-close should be a global def with the message to write as parameter 
def myLog(msg):
    logfile = file("C:\\Users\\caan\\Documents\\SikuliTests\\TwoImports\\output.txt","a")
    logfile.write(msg + "\n")
    logfile.close

But why are you inventing the wheel again:
version 1.0.1 has a user log feature:
Debug.user(msg)

or
Debug.user(format_string, var1, var2, …) according to the Java String format feature

The messages will even have timestamps at the beginning ;-)

when saying once at the beginning
Debug.setUserLogFile("C:\\Users\\caan\\Documents\\SikuliTests\\TwoImports\\output.txt")

you will get all your messages to that file.

… and if you want more features: Python has a nice logging feature ;-)

-- 
You received this question notification because you are a member of
Sikuli Drivers, which is an answer contact for Sikuli.