Pipe console outputs from a specific function into a file - python -
I have a function that I can not edit and prints the results on the console. Is it possible to call that function without changing the internal code of the function, but without changing the internal code of the function in the console output file?
For example, I have:
def somefunc (X): Print "Hello World", X ** X Def Pipe Out (Function, OutputName) Open As with ('outfilename', 'W') burst: # output output pipe in any way ... I could not use the logger Because I could not edit somefunc () . I have tried @aviVini to solve the problem but I can not believe that files were empty except for the first output file and it also overwrites that file repeatedly. Def redirect_output (file_name): DEF decorator (function): def shell (* args): open (file_name, 'w') as f: original_steadout = sys.stdout sys.stdout = F func (* args) sys.stdout = root_stout Return Cover Cover Return To Decorator def somefunc (x): print x * xx = [1,2,3,4] for x: outputfilename = 'results /' + str ( I) somefunc = redirect_output (outputfilename) (somefunc) somefunc (i)
You can use the decorator to redirect sys.stdout to a file object when using the Function Shn is brought back to the call and after the original Steediooti in. import sys def redirect_output (file_name): DEF DECORATOR (function): DEF COVER (* ARGUs): with Open (File_name, 'w') as f: original_stdout = sys. Stdout sys.stdout = f func (* args) sys.stdout = original_stdout return cover return decorator @redirect_output ('file.txt') def somefunc (x): print "hello world", x ** x somefunc (2) print 'Hello to console.' Output: & gt; & Gt; & Gt; % So.py to run Hello Console & gt; & Gt; & Gt; Update: Hello World 4 for I in X: outputfilename = 'results /' + str (i ) New_func = redirect_output (outputfilename) (somefunc) # or directly call it #redirect_output (outputfilename) (somefunc) (i) new_func (i)
Comments
Post a Comment