Vasiliy Sharapov
Vasiliy Sharapov

Reputation: 1057

os.system('exit') in python

My friend is in a macOS environment and he wanted to call os.system('exit') at the end of his python script to make the terminal close. It doesn't. This doesn't surprise me but I would like to know what exactly is going on between the python script and the terminal when this call is made.

In my mental simulation the terminal should have to tell you that there are still running jobs, but that doesn't happen either.

As a side question : will some less common terminals close when a process calls this?

Upvotes: 2

Views: 12894

Answers (3)

Foo Bah
Foo Bah

Reputation: 26271

read the help:

Execute the command (a string) in a subshell.

A subshell is launched, and exit is run in that subshell.

To exit the enclosing terminal, you have to kill the parent. One way to do it is:

os.system("kill -9 %d"%(os.getppid())

Upvotes: 5

user405725
user405725

Reputation:

The system function starts another shell to execute a command. So in this case your Python scripts starts a shell and runs "exit" command in there, which makes that process exit. However, the Python script itself, including a terminal where it is running, continues to run. If the intent is to kill the terminal, you have to get the parent process ID and send a signal requesting it to stop. That will kill both Python script and a terminal.

Upvotes: 2

Yann Ramin
Yann Ramin

Reputation: 33177

Remember that system first spawns/forks a sub-shell to execute its commands. In effect, you are asking only the sub-shell to exit.

Upvotes: 1

Related Questions