プロセス (特に iChat) を強制終了しようとしています。コマンド ラインでは、次のコマンドを使用します。
ps -A | grep iChat
それで:
kill -9 PID
ただし、これらのコマンドを Python に変換する方法が正確にはわかりません。
psutilは名前でプロセスを見つけて強制終了できます。
import psutil
PROCNAME = "python.exe"
for proc in psutil.process_iter():
# check whether the process name matches
if proc.name() == PROCNAME:
proc.kill()
Unix ライクなプラットフォームを使用していると仮定すると (それがps -A
存在するため)、
>>> import subprocess, signal
>>> import os
>>> p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
>>> out, err = p.communicate()
ps -A
の出力をout
変数 (文字列)に与えます。あなたはそれを行に分割してそれらをループすることができます...:
>>> for line in out.splitlines():
... if 'iChat' in line:
... pid = int(line.split(None, 1)[0])
... os.kill(pid, signal.SIGKILL)
...
( のインポートを避け、の代わりにsignal
使用することもできますが、私はそのスタイルが特に好きではないので、この方法で名前付き定数を使用したいと思います)。9
signal.SIGKILL
もちろん、これらの行でもっと洗練された処理を行うこともできますが、これはシェルで行っていることを模倣しています。
あなたが求めているのが を回避することである場合ps
、異なる Unix ライクなシステム間でそれを行うのは困難です (ps
ある意味では、プロセス リストを取得するための共通の API です)。ただし、特定の Unix ライクなシステムを念頭に置いている場合のみ (クロスプラットフォームの移植性は必要ありません)、それは可能かもしれません。特に、Linux では/proc
疑似ファイルシステムが非常に役立ちます。ただし、この後半の部分を支援する前に、正確な要件を明確にする必要があります。
クロスプラットフォームにするためにWindowsのケースを検討する必要がある場合は、次のことを試してください。
os.system('taskkill /f /im exampleProcess.exe')
killall がある場合:
os.system("killall -9 iChat");
または:
os.system("ps -C iChat -o pid=|xargs kill -9")
次のコードは、すべての iChat 指向のプログラムを強制終了します。
p = subprocess.Popen(['pgrep', '-l' , 'iChat'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
line = bytes.decode(line)
pid = int(line.split(None, 1)[0])
os.kill(pid, signal.SIGKILL)
WMIモジュールを使用してWindowsでこれを行うことができますが、UNIXの人々が慣れているよりもはるかに扱いにくいです。import WMI
時間がかかり、プロセスに到達するのに中程度の苦痛があります。
特定のタイトルを持つプロセスまたは cmd.exe を強制終了する場合。
import csv, os
import subprocess
# ## Find the command prompt windows.
# ## Collect the details of the command prompt windows and assign them.
tasks = csv.DictReader(subprocess.check_output('tasklist /fi "imagename eq cmd.exe" /v /fo csv').splitlines(), delimiter=',', quotechar='"')
# ## The cmds with titles to be closed.
titles= ["Ploter", "scanFolder"]
# ## Find the PIDs of the cmds with the above titles.
PIDList = []
for line in tasks:
for title in titles:
if title in line['Window Title']:
print line['Window Title']
PIDList.append(line['PID'])
# ## Kill the CMDs carrying the PIDs in PIDList
for id in PIDList:
os.system('taskkill /pid ' + id )
それが役に立てば幸い。彼らは私のより良い解決策をたくさん持っているかもしれません。
pkill <process_name>
UNIX システムで使用して、プロセスを名前で強制終了できます。
次に、python コードは次のようになります。
>>> import os
>>> process_name=iChat
>>> os.system('pkill '+process_name)
私にとって機能した唯一のことは次のとおりです。
例えば
import subprocess
proc = subprocess.Popen(["pkill", "-f", "scriptName.py"], stdout=subprocess.PIPE)
proc.wait()
import psutil
pid_list=psutil.get_pid_list()
print pid_list
p = psutil.Process(1052)
print p.name
for i in pid_list:
p = psutil.Process(i)
p_name=p.name
print str(i)+" "+str(p.name)
if p_name=="PerfExp.exe":
print "*"*20+" mam ho "+"*"*20
p.kill()