SadeepDarshana SadeepDarshana - 29 days ago 7
Python Question

Why is the python thread count 2 at the beginning?

import threading
print threading.activeCount()


output: 2

When this code is saved into a file and run.

How could it be 2 when it's the main thread?

Does python run another thread by default in addition to the main thread when we run a foo.py file?

Answer

Psychic debugging: You're not running in a plain Python interpreter. The plain Python interpreter doesn't launch extra threads (unless you have a weird PYTHONSTARTUP file), but other interpreters would. For example:

  • ipython launches an extra thread to save command history in the background (to avoid delaying the prompt)
  • IDLE is designed using multiple processes communicating over a socket, and the interactive interpreter it provides you is using a daemon thread to perform the background socket communication

Try running print threading.enumerate(); it might tell you what the background thread is doing (for example, ipython is using a Thread subclass named HistorySavingThread, IDLEs is plain Thread, but the function it runs is named SockThread which gives you a clue as to what it's doing).