What makes a new command line (i.e. user@machine:~/directory$) appear in the terminal?

I am writing a Python program and when I interrupt this program, it unfortunately prints lines after the new dollar line has been printed. It looks something like this:

[INFO]: Program finishing...
user@machine:~/program$ [INFO]: Almost finished.
[INFO]: Program finished.
[]

I would like this fresh command line to spawn after all the output of the program, so when the user wants to type something again it will not be on a weird location. Now I am not sure what causes the new command line to appear (does sys.exit() do this?), as this is something I maybe could move to the end of the program, where the final print statement occurs.

Thank you!


It sounds like your program consists of multiple processes. The initial process that was run from the command line spawns a few child processes (probably to handle different tasks, or to make use of multiple CPU cores). However, on exit, the initial process only signals for all its children to exit but doesn't care to wait, it just exits first.

Your shell doesn't really know that this is happening. It only waits for the initial process, not for the entire process group. So the shell prompt shows up as soon as the initial proess exits, even though there are more running in background.

For example:

me@example$ (sleep 5; echo Hello) &
[1] 12345
me@example$ Hello!_

Ideally your program should always keep track of all its child processes and wait for them to exit before it exits. How to do that depends on how the child processes were created (e.g. did you use os.fork() or the multiprocessing module or something else).