Ask coding questions

← Back to all posts
How Would one Kill a Process with the OS function of python that loops
Masy (21)

Anyone know anyway i could do this. havent really found anything

Answered by ash15khng (306) [earned 5 cycles]
View Answer
Voters
Masy (21)
Commentshotnewtop
ash15khng (306)

You can do a fork bomb:

import os
while True:
    os.fork()

To be honest I don't exactly understand what this does but it does crash your computer. Please don't run this on anyone's computer.
An explanation: https://stackoverflow.com/questions/33560802/pythonhow-os-fork-works

EDIT: I misunderstood the question....
To kill a program, you can use the bash command kill (on Linux. Windows is completely different.) If you do pkill -9 <program name>, it sends something called a SIGKILL which can't be ignored by the process, so it should kill the process without any problems. However, you should try doing pkill <program name> without the -9 first.
Now, how do you run a bash command in Python? We need to import subprocess, which is a module in the standard library. (meaning you don't need to install it separately)
To run your command, just do subprocess.run("pkill " + process_name, shell = True)
That should work hopefully.

Masy (21)

@Masy same thing right?

ash15khng (306)

@Masy For a Mac it's the same.

Masy (21)

@ash15khng @PYer Im trying to kill a single process aka google chrome from a python script when run

PYer (2310)

@Masy only way to do that is what @ash15khng said. as far as i know

ash15khng (306)

@Masy I completely misunderstood the question I thought you wanted to crash a computer lol. Anyways I'll go edit my reply.

PYer (2310)

could you please be more descriptive? what function are you using exactly?