Reputation: 660
I try to implement an option which will save the console output additionally into a file. (if the option is activated)
I found two ways: 1. to use the logging module 2. to write a class like this:
class MyWriter:
def __init__(self, stdout, filename):
self.stdout = stdout
self.logfile = file(filename, 'a')
def write(self, text):
self.stdout.write(text)
self.logfile.write(text)
def close(self):
self.stdout.close()
self.logfile.close()
But I got a problem. Some pieces of code will execute in a new process. And this ways does not catch their prints.
When I start my program like
"myscript.py > mylog.txt"
it works. He got all prints. But how can I simulate this functionally in my script?
Upvotes: 1
Views: 205
Reputation: 43096
My suggestion would be to use the logging module, to use a sockethandler and to push to a socket server that would write the received logs into a file.
I hope it helps
Upvotes: 1
Reputation: 6152
If I understand you correctly, you want to redirect stdout
of other process that you start right?
Then all you have to do is use
subprocess.Popen(...)
command. Then you have use your MyWriter
class with it.
Upvotes: 1
Reputation: 14487
Problem probably has to be solved how you execute a new process, you either need to collect output from sub-process in main-process, or pass a filename to sub-process. You can use environment variables for filename instead of passing it as argument, then it will be easy to access log file in sub-process too.
Upvotes: 0