2016-04-03 90 views
0

我已经穿线Popen bash来运行命令行工具。 bash会生成一个段错误或中止正在执行的命令。螺纹Popen在'bash'中出现分段错误时崩溃

def FunctionToThread(args): 

    su2 = Popen('bash', shell = True, stdin = PIPE, stdout=fp, env = os.environ) 
    for i in commands: 
     su2.stdin.write(i) 
    su2.stdin.close() 
    su2.wait() 
    fp.close() 

函数FunctionToThread使用线程模块进行线程化。如上所述,当在bash中遇到段错误时,该线程终止。

我想捕获这个段错误在try/except类型的控件中,最重要的是防止我的线程终止。

我该如何做到这一点?

"""SNIPPET""" 
from multiprocessing import cpu_count 
import threading 
from subprocess import Popen, PIPE 
import os 

start =0 
numcores = cpu_count() 
global RESULTS, LOCK 
LOCK = threading.Lock() 
RESULTS = [] 

def ParallelRun(commands, RESULTS, LOCK): 

    for i in range(0, 100): 
     LOCK.acquire() 
     RESULTS.append('ParallelRUn') 
     LOCK.release() 

    su2 = Popen('bash', shell = True, stdin = PIPE, stdout=PIPE, env = os.environ) 
    for i in commands: 
     su2.stdin.write(i) 
    su2.stdin.close() 
    err =su2.wait() 


for i in range(0, numcores): 
    commands = ['Enter commands which cause Segmentation Faults'] 
    t = threading.Thread(target=ParallelRun, args=(commands, RESULTS, LOCK)) 
    threads.append(t) 

for t in threads: 
    t.start() 

for t in threads: 
    t.join() 


print len(RESULTS), RESULTS 

要复制我的问题,在命令列表中输入其产生段错误的命令。

谢谢!

+0

你可以创建一个小的可重复片段,我可以通过复制+粘贴执行吗? – guettli

+0

@guettli:我添加了一个片段。在命令列表中,可以添加一组生成分段故障的命令。 – pds

+0

pds你在最后一个片段中有一个变量'fp',它用作'stdout',现在你正在使用'PIPE'。是什么促使了这种改变 – tijko

回答

1

此问题已解决。事实证明,我在终止我的线程的程序的if/else块中有一个返回语句。