python repl communication_python - 捕获崩溃的子进程的“分段错误”消息:在调用communication()之后没有out和err - 堆栈内存溢出...

shell可能会生成"Segmentation fault"消息。 要找出该过程是否被SIGSEGV杀死,请检查proc.returncode == -signal.SIGSEGV 。

如果要查看消息,可以在shell中运行该命令:

#!/usr/bin/env python

from subprocess import Popen, PIPE

proc = Popen(shell_command, shell=True, stdout=PIPE, stderr=PIPE)

out, err = proc.communicate()

print out, err, proc.returncode

我已经用shell_command="python -c 'from ctypes import *; memset(0,1,1)'"测试了它,导致了段错误并且err捕获了消息。

如果消息直接打印到终端,那么您可以使用pexpect模块捕获它:

#!/usr/bin/env python

from pipes import quote

from pexpect import run # $ pip install pexpect

out, returncode = run("sh -c " + quote(shell_command), withexitstatus=1)

signal = returncode - 128 # 128+n

print out, signal

或直接使用pty stdlib模块:

#!/usr/bin/env python

import os

import pty

from select import select

from subprocess import Popen, STDOUT

# use pseudo-tty to capture output printed directly to the terminal

master_fd, slave_fd = pty.openpty()

p = Popen(shell_command, shell=True, stdin=slave_fd, stdout=slave_fd,

stderr=STDOUT, close_fds=True)

buf = []

while True:

if select([master_fd], [], [], 0.04)[0]: # has something to read

data = os.read(master_fd, 1 << 20)

if data:

buf.append(data)

else: # EOF

break

elif p.poll() is not None: # process is done

assert not select([master_fd], [], [], 0)[0] # nothing to read

break

os.close(slave_fd)

os.close(master_fd)

print "".join(buf), p.returncode-128

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值