hexce
hexce

Reputation: 161

Python Issue with Values

I am trying to write a program in python (just learning as it looks a nice language) but have come across a small problem.

My code works for the most part but decided to print found process rather than just the first found process. All i want it to print out is whether it has found a process or not.

I have searched for sshd for example and my output has been

found
found
found

as there are 3 processes running.

my code is

import os
import signal

vProcessName = "sshd"

for line in os.popen("ps xa"):
    fields = line.split() 
    if vProcessName  in fields[4]: 
        print("Found")     

Thank you for any help you may provide its greatly appreciated.

Upvotes: 0

Views: 64

Answers (1)

falsetru
falsetru

Reputation: 369064

Using break statement, you can get out of the loop:

for line in os.popen("ps xa"):
    fields = line.split()

    if vProcessName  in fields[4]:
        print("Found")
        break # <----

Alternativing using any:

if any(vProcessName in line.split() for line in os.popen("ps xa")):
    print("Found")

Upvotes: 2

Related Questions