Reputation: 77
I am using "popen" to get the process list in linux.Since i am new to python i don't know how to search for my process in the list of processes.Below i am adding my code snippet:
import os
p = os.popen('ps -aef',"r")
while 1:
line = p.readline()
if not line: break
print line
I want to search whether command "python ./yowsup-cli demos -c config -e" is running or not and if not running run this command.How should I iterate the process to check for this and restart again. Can anyone help me with the approach.
Upvotes: 0
Views: 284
Reputation: 1762
I recommend you use subprocess
when running linux os commands from within python. Second you should use grep
to filter the output of your command. ps
command may return more than one line so stdout should be saved into a list. As an example for your need:
import subprocess
def subprocess_cmd(command):
process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
return proc_stdout
process_ids = subprocess_cmd("ps -ef |grep python |grep yowsup-cli |grep -v grep |awk '{ print $2 }'")
process_ids_list = process_ids.split('\n')
if process_ids_list == ['']:
print = 'STOPPED'
else:
print = 'RUNNING'
Upvotes: 1
Reputation: 355
You could use readlines() and list comprehension instead. Then your code should look something like this:
command_to_run = "python ./yowsup-cli demos -c config -e"
if not any([command_to_run in line for line in p.readlines()]):
# run your command
Note that this would run your command even if a wider command line was specified, such as "python ./yowsup-cli demos -c config -e -a -b -c", but I just didn't find it likely to happen in this case, so that code would do fine.
Upvotes: 1