I'm running a python 2.7 program using Terminal, on a Mac. If I open up Terminal and run the program, it executes differently from when I run the program a second time, in the same Terminal window. What could possibly cause a problem like this?
Below is the code I'm using. The line print bg("grey_50") prints nothing on the first program execution, but it correctly prints a grey line on the second execution. On BOTH executions, the for function operates the same, and correctly. Why does the grey line only print the second time I run the program?
uses_color = "True"
if uses_color == "True":
from colored import fg, bg
if uses_color == "True":
print bg("grey_50")
for i in range(44):
print bg("grey_100")
As a side note, there is also some code between the second and third stanzas that works the same, and correctly, every time I run the function.
Additionally, please observe that both the line print bg("grey_50") and print bg("grey_100") use the colored module, but only the latter of those two works consistently.
Link to colored: https://github.com/dslackw/colored
This has nothing to do with your program or repeated runs. The problem lies in the behavior of your terminal when scrolling. Only when scrolling, the terminal uses the current background color to fill the entire line.
On a first run, with the current edit prompt high enough, you will see that no color at all is printed. On next runs, the display scrolls and the terminal checks with what color to clear – the current active background color. My default terminal background is not pure white (the grey_100 in your code) so I don't see anything different in the first run.
If you literally want to print an entire line in the background color, interrogate your terminal width and print a line of spaces.
from colored import fg, bg, attr
import os
# from https://stackoverflow.com/questions/566746/how-to-get-linux-console-window-width-in-python
rows, columns = os.popen('stty size', 'r').read().split()
columns = int(columns)
print bg("red")+(columns * ' ')
for i in range(10):
print bg("yellow")+(' ' * columns)
print attr('reset')
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