Capturing terminal output in Google Colab

OpenSim Moco is a software toolkit to solve optimal control problems with musculoskeletal models defined in OpenSim using the direct collocation method.
POST REPLY
User avatar
Ana de Sousa
Posts: 67
Joined: Thu Apr 07, 2016 4:21 pm

Capturing terminal output in Google Colab

Post by Ana de Sousa » Mon Oct 14, 2024 4:22 am

Hi everyone!

I'm preparing a workshop on Moco and setting up an environment in Google Colab to run some examples. Here's the link:
https://colab.research.google.com/drive ... sp=sharing

Everything works well: I installed OpenSim successfully and was able to run a simple example. However, I'm facing an issue with terminal output in Google Colab. When I run solution = study.solve(), no output is displayed in the notebook, even though the function executes, and I can save the results. This happens because Colab doesn't handle standard terminal output the same way as a local terminal, so it runs the code silently.

I've tried a few methods to capture the output.

1) Redirecting sys.stdout to /dev/stdout. This results in an OSError since Colab doesn't seem to have access to /dev/stdout.

Code: Select all

sys.stdout = open('/dev/stdout', 'w')
2) Using io.StringIO to capture the output:

Code: Select all

import io
buffer = io.StringIO()
sys.stdout = buffer
solution = study.solve()
sys.stdout = sys.__stdout__
print(buffer.getvalue())
Unfortunately, no output was printed.

3) I also tried using contextlib.redirect_stdout to redirect the output to a StringIO object, but again, nothing was printed.

I know it is not the most usual execution, but I wondered if anyone else understands more about Jupyter's notebook-like environments. Do you have any suggestions on how to get the full terminal execution details to appear?

User avatar
Nicholas Bianco
Posts: 1044
Joined: Thu Oct 04, 2012 8:09 pm

Re: Capturing terminal output in Google Colab

Post by Nicholas Bianco » Mon Oct 14, 2024 10:20 am

Hi Ana,

If you're looking for the Ipopt output, you can add an ipopt.opt (Ipopt options) file to your working directory to specify where the Ipopt output should be directed to.

I haven't found a more general solution for this, but will let you know if I do!

Best,
Nick

User avatar
Ana de Sousa
Posts: 67
Joined: Thu Apr 07, 2016 4:21 pm

Re: Capturing terminal output in Google Colab

Post by Ana de Sousa » Tue Oct 15, 2024 2:05 am

Hi Nick, for the purpose of this workshop that works well, thanks a lot.

Code: Select all

# Create ipopt.opt file with the specified options
with open("ipopt.opt", "w") as file:
    file.write("output_file opensim.log\n")
    file.write("file_append yes\n")

solution = study.solve()

# Display the content of the Ipopt output log
with open("opensim.log", "r") as log_file:
    log_content = log_file.read()
    print(log_content)

POST REPLY