My program outputs state of computations to the terminal and includes quite a bit of information. I would like to, if possible, color code parts of the text.
I have seen how it can be done in Bash and C++ by referring to threads on this site. However, I have not been able to use any of that to achieve the same result in Fortran (modern). For example, I tried this sample code, which I thought should work:
PROGRAM test
PRINT*, 'A great color is \033[95m pink \033[0m.'
END PROGRAM test
I would have expected the output to be "A great color is pink" where pink is colored pink. Instead I get "A great color is \033[95m pink \033[0m." I don't understand what I am missing.
If I replace the print line in the code with: CALL EXECUTE_COMMAND_LINE("echo 'A great color is \033[95m pink \033[0m.'") then I get the output as desired. However I wouldn't want to keep calling on echo from my code. Is there any way I can get colored output?
Thanks!
Fortran - Basic Input Output. We have so far seen that we can read data from keyboard using the read * statement, and display output to the screen using the print* statement, respectively. This form of input-output is free format I/O, and it is called list-directed input-output.
Once an appropriate ANSI sequence is sent to the terminal, all following text is rendered that way. Thus if we want all text printed to this terminal in the future to be bright/bold red, print ESC [ followed by the codes for "bright" attribute (1) and red color (31), followed by m
Here is a basic approach to set the terminal so that all following prints are rendered with a given color, attributes, or mode. Once an appropriate ANSI sequence is sent to the terminal, all following text is rendered that way.
Would the Python termcolor module do? This would be a rough equivalent for some uses. The example is right from this post, which has a lot more. Here is a part of the example from docs A specific requirement was to set the color, and presumably other terminal attributes, so that all following prints are that way.
The escape character representation as '\033' doesn't appear to be working for you. I don't have fortran handy to check, but you might try explicitly using the character instead of the c-style escaping by calling the char
conversion function, i.e., make the actual character by calling char(27)
and build it into your output string in the correct places.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With