1

I developed an algorithm that was made to run in the foreground (with several beautiful and elegant prints) but realized that most of the time it will run in the background.

Unfortunately I did a task that runs every x time to check the size of the terminal and to do some calculations and print the results efficiently. And since this task consumes a bit of processing, when my script was in the background, I'd like to disable it.

Is there any way to know if the program was started to run in the background or foreground in python?

1 Answers1

5

Simple:

import sys

sys.stdout.isatty()
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • A nice description can be found [here](https://www.geeksforgeeks.org/python-os-isatty-method/). – S3DEV Sep 26 '19 at 13:06
  • When I use **pythonw** to run in background my script, the `sys.stdout` are not available. As can see [here](https://stackoverflow.com/a/30313091). – Lincoln Schreiber Sep 26 '19 at 14:02
  • @LincolnSchreiber Your question is tagged “linux” yet pythonw only exists on Windows — in fact, it makes no sense on Linux. (Technically it exists on Linux but it’s the same as normal Python, and *my solution still works* in it.) – Konrad Rudolph Sep 26 '19 at 14:22
  • It's true hehehe I tested on linux and it worked. Thanks again! – Lincoln Schreiber Sep 26 '19 at 14:28