lundi 21 septembre 2015

"If/elif" statement ins't working for no apparent reason

The following part of code, is supposed to do the following, depending on the variable data:

  • Print the currently running processes, along with their PID.
  • Kill a process with its name or its PID.

import psutil
...
elif data.startswith("process"):
    if data[8:12] == "show":
        processes = []
        for proc in psutil.process_iter():
            pinfo = proc.as_dict(attrs=["name", "pid"])
            processes.append(pinfo)
    elif data[8:12] == "kill":
        something = data[13:]
        if something.isdigit():
            p = psutil.Process(int(data[13:]))
            p.kill()
        else:
            for proc in processes:
                if proc["name"] == data[13:]:
                    p = psutil.Process(int(proc["pid"]))
                    p.kill()
...
else:
    proc = subprocess.Popent(data, shell=True)


Yet though, no matter how many times I try to accomplish so, I can't reach the second "elif" statement, the one that has to do with killing a process.

For data = "process show" works perfectly fine whereas data = "process kill calc.exe" opens the Calculator.exe. It seems like data = "process kill calc.exe" skips elif data.startswith("process"), and there (in the very bottom of the code) it successfully opens the Calculator.exe.

Why does this happen? Isn't it supposed to go in to the first elif, since it literally starts with "process"?

Aucun commentaire:

Enregistrer un commentaire