qshinoの日記

Powershell関係と徒然なこと

python process 関係

python プロセス基本モジュール

  • os.kill( pid, signal.SIGKILL )
  • os.killpg( os.getpgid(pid), signal.SIGKILL )
  • os.getpgid( pid )
  • os.fork()
  • os.waitpid( pid, 0 )
  • os.system( 'echo Hello' )

  • subprocess.Popen()

p = subprocess.Popen( 'pwd', stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True, shell=True)

  • 戻り値 の使い方

p.stdout, p.stdin等。

利用例

import os
from subprocess import Popen, PIPE
from signal import SIGKILL

def killproc(name):
  proc = Popen( f"ps aux | grep {name}", stdin=PIPE, stdout=PIPE, close_fds=True, shell=True)
  pout = proc.stdout
  greppid = proc.pid
  for line in pout.readlines():
    pid = int(  line.strip().split(' ')[1] )
    if ( pid == greppid ): continue
    pgid = os.getpgid(pid)
    try: os.killpg( pgid, SIGKILL ) 
    except: pass

killproc('hello')

参考

http://www.python.jp/doc/nightly/library/subprocess.html