0

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.

1
  • And what is the question? Why doesn't it leave the cycle after first finding? How about break? Commented Apr 5, 2014 at 13:55

1 Answer 1

2

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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.