This question is related to Python: why print statements and subprocess.call() output are out of sync? but the solutions are not working for my particular situation. I am trying to accomplish an automation test process in python that has first prints the name of a Test Suite, then has a for loop which iterate through a list printing the name of a particular test, followed by a subprocess call to execute the test, ended with a print statement that the test is finished. Lastly, I print a statement that says it is the end of the test suite name.
i.e. =========BEGIN TEST SUITE: =========
---------start test: ----------
subprocess call to execute test
---------end test: ------------
repeat for tests
=========END TEST SUITE: ==========
My current code works fine but when I redirect its output to a file, it puts all the print statements at the bottom. When using the solutions in the other question, it does the complete opposite for me and prints all the print statements first, then executes the test. I tried used the sys.stdout.flush(), as well as turning off the buffering but both give me the same thing. How can I get everything to be printed exactly the way it executes/is in the code when I redirect output or write to a file??
The way I generally solve problems like this is to capture the output in the python program and print it when I want it to print using a Popen
>>> def do_ls():
... print "I'm about to ls"
... ls = subprocess.Popen('ls', stdout=subprocess.PIPE)
... output = ls.communicate()[0] #wait for the process to finish, capture stdout
... print 'ls output:'
... print output
... print 'done.'
I can show you how to do this more specifically for your tests if you post some code