python subprocess ,service

多指令 是否阻塞 返回類型 推薦使用
os.system 支持 阻塞 returncode
subprocess Popen 支持 根據參數靈活調整 returncode,stdout,stderr 推薦
call 支持 阻塞 returncode
check_call 支持 非阻塞 returncode 推薦
check_output 支持 非阻塞 stdout 推薦
getoutput 不支持 阻塞 stdout
getstatusoutput 不支持 阻塞 returncode,stdout

Help on module subprocess:

NAME

subprocess - Subprocesses with accessible I/O streams

DESCRIPTION

This module allows you to spawn processes, connect to their
input/output/error pipes, and obtain their return codes.

For a complete description of this module see the Python documentation.

Main API
========
run(...): Runs a command, waits for it to complete, then returns a
          CompletedProcess instance.
Popen(...): A class for flexibly executing a command in a new process

Constants
---------
DEVNULL: Special value that indicates that os.devnull should be used
PIPE:    Special value that indicates a pipe should be created
STDOUT:  Special value that indicates that stderr should go to stdout


Older API
=========
call(...): Runs a command, waits for it to complete, then returns
    the return code.
check_call(...): Same as call() but raises CalledProcessError()
    if return code is not 0
check_output(...): Same as check_call() but returns the contents of
    stdout instead of a return code
getoutput(...): Runs a command in the shell, waits for it to complete,
    then returns the output
getstatusoutput(...): Runs a command in the shell, waits for it to complete,
    then returns a (status, output) tuple

import os
import sys
import signal
import psutil
import time
import subprocess

if __name__ == '__main__':

    oo = ['cd', os.path.abspath('.'),
          '&&',
          'dir',
          '&&'
          ]

    process_cmd = ' '.join(oo)
    # outputstatus= subprocess.check_call(process_cmd, shell=True)
    # print("return", outputstatus)
    
    pro = subprocess.Popen(process_cmd,  stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                           shell=True)
    returncode = pro.poll()
    while returncode is None:
        returncode = pro.poll()

    back_data = dict(
        pid=pro.pid,
        output_lines=pro.stdout.readlines(),
        error_lines=pro.stderr.readlines())

    # os.kill(back_data['pid'], signal.SIGTERM)

    print("back \npid {pid} \noutput_lines {output_lines} \nerror_lines {error_lines}".format(
        **back_data))
    

關閉進程及子進程相關相關


import os 
import psutil

process = psutil.Process(back_data.get('pid'))
process_children = process.children(recursive=True)
print([{"pid": child.pid, "status": child.status(), "name": child.name()}
           for child in process_children])
os.kill(back_data['pid'], signal.SIGTERM)
   

關閉與名字匹配的進程


import psutil

def kill_process(name):
   """search process ,kill process by name """
    kill_pids = []
    try:
        for process in psutil.process_iter():
            if name == process.name():
                kill_pids.append(process.pid)
    except psutil.NoSuchProcess:
        pass
    [os.kill(kill_pid, signal.SIGTERM) for kill_pid in kill_pids]
    

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,937評論 18 139
  • Python 面向對象Python從設計之初就已經是一門面向對象的語言,正因為如此,在Python中創建一個類和對...
    順毛閱讀 4,238評論 4 16
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,335評論 25 708
  • 今天的遭遇,對我來說真的是頭一回。兩個城市間本只有1個小時的距離,卻被自己的粗心與大意拉長至了4個小時。在背著行李...
    逝事拾閱讀 237評論 0 0