python执行shell命令并实时输出信息

from subprocess import Popen, PIPE, STDOUT


def exe_command(command):
	# 为什么要写一个这么复杂的函数?
	# 在实际使用中发现,很多方法需要ctrl c掉,但是他的进程还在后台运行,使用 process.kill()也无法杀死进程,查询发现是Popen 创建了一个子进程去执行命令,process.kill() 只是杀死了Popen本身的进程,所以使用下面的笨方法去获取真正的进程然后kill,之后谁有更好的方法,希望指正
    process = Popen(command, stdout=PIPE, stderr=STDOUT, shell=True)
    try:
        result = []
        with process.stdout:
            for line in iter(process.stdout.readline, b''):
                print(line.decode().strip())
                result.append(line.decode().strip())
        process.wait()
        return process, result
    except KeyboardInterrupt:
        get_pid_cmd = """ps -ef | grep "%s" | grep -v grep | awk '{print $2}'""" % command[:10]
        _, result = exe_command(get_pid_cmd)
        kill_cmd = f"kill -9 {process.pid} {result[0]}"
        print(f"kill -9 {process.pid} {result[0]}")
        exe_command(kill_cmd)
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值