loca1h0st's Blog
loca1h0st's Blog

Python subprocess调用命令及实时获取输出

Python subprocess调用命令及实时获取输出
import shlex, subprocess

def runCmd(tid, msg, cmd):
    try:
        p = subprocess.Popen(shlex.split(cmd), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        while p.poll() == None:
            out = p.stdout.readline().strip()
            if out:
                print('---->' + out.decode())

        res = ' 失败 ~_~' if p.returncode else ' 完成 ^_^'
        print('---->' + msg + res)

        return p.returncode
    except Exception as e:
        print('---->Shell Exec Error:%s' % str(e))
        return 999

中途中止:


#coding:utf-8
 
import datetime
import time
import subprocess
import signal
import os
 
cmd = ['ping', 'www.baidu.com']
#开启子进程 preexec_fn设置为进程组
p = subprocess.Popen(cmd, preexec_fn=os.setsid)
 
#接收到触发 杀死进程组
def signal_handler(signal, frame):
    os.killpg(os.getpgid(p.pid), 9)
 
#接受ctrl c终止信号
signal.signal(signal.SIGINT, signal_handler)
#阻塞等待子进程结束
p.wait()
print ('finish')

tips:

绕过网页禁止复制的方法: document.body.contentEditable=true

发表回复

textsms
account_circle
email

loca1h0st's Blog

Python subprocess调用命令及实时获取输出
import shlex, subprocess def runCmd(tid, msg, cmd): try: p = subprocess.Popen(shlex.split(cmd), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.…
扫描二维码继续阅读
2022-08-23