1. 概要
ま、プロセスの有無を調べたいのですが。
「ps」コマンドで全文検索するのではなく、「pgrep」で、特定の名前のプロセスの有無を調べたいのです。
「ps」であれば、「psutil」というモジュールをインストールするらしく。
「pgrep」であれば、「pgrep」というモジュールらしいのです。
「FreeBSD」的な事情を言えば、「psutil」は、「ports」に存在するようですが、「pgrep」は、「pip」によってインストールするしかなさそうなのです。
2. pgrep を作成する
結論的なことを言うと「pip」で「pgrep」をインストールしたものの・・・。
import pgrep
の時点で、こける。
「Python」を実行するとようわかる
> python
Python 3.6.9 (default, Dec 9 2019, 07:50:20)
[GCC 4.2.1 Compatible FreeBSD Clang 8.0.0 (tags/RELEASE_800/final 356365)] on freebsd11
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> import pgrep
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/pgrep/__init__.py", line 6, in <module>
@public.add
AttributeError: module 'public' has no attribute 'add'
>>>
「Python」のことをよう知らんので、解決方法がわからんのですが・・・。
おかげで「/usr/local/lib/python3.6/site-packages/pgrep/__init__.py」のソースを読んで、なんかわかったような気がします。
中身が
#!/usr/bin/env python
import os
import public
@public.add
def pgrep(pattern):
"""return a list with process IDs which matches the selection criteria"""
args = ["pgrep", str(pattern)]
out = os.popen(" ".join(args)).read().strip()
return list(map(int, out.splitlines()))
これだけである・・・。
なんか、説明に、「pgrep」のラッパーと書いてありましたが、確かに、「pgrep」の実行結果を返しておるのですな・・・。
これならば、まるパクリしてもなんとかなりそうです。
3. パクって作る・その1
#!/bin/sh
pgrep mysqld
echo "-----------------"
pgrep httpd
echo "-----------------"
pgrep xxxxx
てなスクリプトを実行すると、こうなるとすれば。
21951
-----------------
54285
56748
56753
56758
56767
56782
83025
83029
83030
56793
83044
-----------------
まんま、パクったようなソースをこう書けば
import os
def pgrep(pattern):
"""return a list with process IDs which matches the selection criteria"""
args = ["pgrep", str(pattern)]
out = os.popen(" ".join(args)).read().strip()
return list(map(int, out.splitlines()))
print(pgrep("mysqld"))
print('-----------------')
print(pgrep("httpd"))
print('-----------------')
print(pgrep("xxxxx"))
実行結果は、こうなるわけです。
[21951]
-----------------
[54285, 56748, 56753, 56758, 56767, 56782, 83025, 83029, 83030, 56793, 83044]
-----------------
[]
4. パクって作る・その2
有無のみ、知りたいので、こう書きます。
import os
def pgrep(pattern):
"""return a list with process IDs which matches the selection criteria"""
args = ["pgrep", str(pattern)]
out = os.popen(" ".join(args)).read().strip()
return out
def check(pattern):
if (pgrep(pattern) != ''):
return True
else:
return False
def pgrepprint(pattern):
if (check(pattern) != False):
print('['+ pattern +'] is found')
else:
print('['+ pattern +'] is not found')
pgrepprint("mysqld")
print('-----------------')
pgrepprint("httpd")
print('-----------------')
pgrepprint("xxxxx")
結果は、こうなります。
[mysqld] is found
-----------------
[httpd] is found
-----------------
[xxxxx] is not found
実は、メッセージを日本語で書いていたら、ちょっと事情があってこけたので、アルファベットで書きましたが、最終的に 15行以下は、いらんわけで・・・。
わたしの当初の目的のためには、13行目までのコードがあればいいのだ。