加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

popen与python在python2.7中读取和写入块

发布时间:2020-12-20 13:16:08 所属栏目:Python 来源:网络整理
导读:我面临类似的问题另一个用户@AMisra发布了一段时间,但没有收到明确的答案.问题是因为我使用的是第三方代码而无法对其进行太多修改.我有一个在代码中多次调用的函数来创建子进程,将数据写入stdin然后读取.它只是挂在这条线上 line = self.classifier.stderr.r
我面临类似的问题另一个用户@AMisra发布了一段时间,但没有收到明确的答案.问题是因为我使用的是第三方代码而无法对其进行太多修改.我有一个在代码中多次调用的函数来创建子进程,将数据写入stdin然后读取.它只是挂在这条线上

line = self.classifier.stderr.readline()

请注意,我不能使用通信:因为需要多次调用func2(分类器,向量),它会抛出异常.

import subprocess
import paths
import os.path

class CRFClassifier:
    def __init__(self,name,model_type,model_path,model_file,verbose):
        self.verbose = verbose
        self.name = name
        self.type = model_type
        self.model_fname = model_file
        self.model_path = model_path

        if not os.path.exists(os.path.join(self.model_path,self.model_fname)):
            print 'The model path %s for CRF classifier %s does not exist.' % (os.path.join(self.model_path,self.model_fname),name)
            raise OSError('Could not create classifier subprocess')


        self.classifier_cmd = '%s/crfsuite-stdin tag -pi -m %s -' % (paths.CRFSUITE_PATH,os.path.join(self.model_path,self.model_fname))
#        print self.classifier_cmd
        self.classifier = subprocess.Popen(self.classifier_cmd,shell = True,stdin = subprocess.PIPE,stderr = subprocess.PIPE)

        if self.classifier.poll():
            raise OSError('Could not create classifier subprocess,with error info:n%s' % self.classifier.stderr.readline())

        #self.cnt = 0


    def classify(self,vectors):
#        print 'n'.join(vectors) + "nn"

        self.classifier.stdin.write('n'.join(vectors) + "nn")

        lines = []
        line = self.classifier.stderr.readline()
        while (line.strip() != ''):
#            print line
            lines.append(line)
            line = self.classifier.stderr.readline()


        if self.classifier.poll():
            raise OSError('crf_classifier subprocess died')

        predictions = []
        for line in lines[1 : ]:
            line = line.strip()
#            print line
            if line != '':
                fields = line.split(':')
#                print fields
                label = fields[0]
                prob = float(fields[1])
                predictions.append((label,prob))

        seq_prob = float(lines[0].split('t')[1])

        return seq_prob,predictions


    def poll(self):
        """
        Checks that the classifier processes are still alive
        """
        if self.classifier is None:
            return True
        else:
            return self.classifier.poll() != None

为输入文件创建分类器对象,该输入文件是具有句子列表的文档,并且在创建时它还使用该句子列表执行外部命令.然后在单独的函数中处理每个句子,为每个句子提供单独的向量.这个新向量被传递给classify函数.

def func2():
    classifier=create a classifier object for an input file,this executes the external command
    for sentence in sentences:
        vectors=process(sentence)# some external function
        classifier.classify(features)

解决方法

在classify方法而不是构造函数中初始化self.classifier,并使用Popen().还需要使用stdout而不是stderr.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读