~jtv/corpusfiltergraph/cross-python

« back to all changes in this revision

Viewing changes to trunk/lib/corpusfg/graphs/sa-champollion/ar/atoken.py

  • Committer: tahoar
  • Date: 2012-05-02 15:46:23 UTC
  • Revision ID: svn-v4:bc069b21-dff4-4e29-a776-06a4e04bad4e::266
new layout. need to update code to use the new layout

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#! /usr/bin/env python
 
2
# -*- coding: utf8 -*-
 
3
 
 
4
#===============================================================================
 
5
# Author: Tom Hoar
 
6
#===============================================================================
 
7
 
 
8
#version:
 
9
#4.0.264 - version update
 
10
 
 
11
import os
 
12
import sys
 
13
import subprocess
 
14
import logging
 
15
import common as cf
 
16
 
 
17
logger = logging.getLogger('.'.join([os.path.splitext(os.path.basename(sys.argv[0]))[0],'manager','filtergraph',__name__]))
 
18
 
 
19
class filter(object):
 
20
 
 
21
        cfg = {
 
22
                'args': {},
 
23
                'encoding': 'utf8',
 
24
                'exeoptions': '-n',
 
25
                'kw': {
 
26
                        'bufsize': 0,
 
27
                        'executable': '4,perl',
 
28
                        'stdin': 'PIPE',
 
29
                        'stdout': 'PIPE',
 
30
                        'stderr': 'PIPE',
 
31
                        'preexec_fn': None,
 
32
                        'close_fds': False,
 
33
                        'shell': False,
 
34
                        'cwd': None,
 
35
                        'env': None,
 
36
                        'universal_newlines': False,
 
37
                        'startupinfo': None,
 
38
                        'creationflags': 0,
 
39
                        },
 
40
                'script': '3,atoken.pl',
 
41
                'version': '4.0.264',
 
42
                }
 
43
        args = []
 
44
        encoding = 'utf8'
 
45
        kw = {}
 
46
        script = '3,atoken.pl'
 
47
        isopen = False
 
48
        p = object
 
49
        errors = []
 
50
 
 
51
        def open(self,parent,cfg):
 
52
                self.args = dict(cfg['args'])
 
53
                self.kw = dict(cfg['kw'])
 
54
                if cfg['script']:
 
55
                        self.script = self.p.decodepath('%s,%s'%(__name__.split(',')[1],cfg['script']),True)
 
56
                        if not self.script:
 
57
                                self.errors.append([__name__,'missing',cfg['script']])
 
58
                                logger.error('%s\t%s',*self.errors[-1][1:])
 
59
                        self.args[0] = self.script
 
60
                        self.kw['cwd'] = os.path.dirname(self.script)
 
61
                else:
 
62
                        self.script = None
 
63
                # convert args dict to args list
 
64
                self.args = [str(self.args[k]) for k in sorted(self.args.keys())]
 
65
                if 'executable' in cfg['kw'] and cfg['kw']['executable']:
 
66
                        self.kw['executable'] = self.p.decodepath('%s,%s'%(__name__.split(',')[1],cfg['kw']['executable']),True)
 
67
                        if not self.kw['executable']:
 
68
                                self.errors.append([__name__,'missing',cfg['kw']['executable']])
 
69
                                logger.error('%s\t%s',*self.errors[-1][1:])
 
70
                        self.args.insert(0,cfg['exeoptions'] if cfg['exeoptions'] else '')
 
71
                else:
 
72
                        self.kw['executable'] = None
 
73
                self.kw['stdin'] = subprocess.PIPE if cfg['kw']['stdin'] == 'PIPE' else cfg['kw']['stdin']
 
74
                self.kw['stdout'] = subprocess.PIPE if cfg['kw']['stdout'] == 'PIPE' else cfg['kw']['stdout']
 
75
                self.kw['stderr'] = subprocess.PIPE if cfg['kw']['stderr'] == 'PIPE' else cfg['kw']['stderr']
 
76
                self.encoding = 'utf8' if 'utf8' in cfg['encoding'].lower().replace('-','') else cfg['encoding']
 
77
 
 
78
                try:
 
79
                        self.subproc = subprocess.Popen(self.args,**self.kw)
 
80
                except Exception,e:
 
81
                        raise RuntimeError('failed \"[%s]\" \"%s %s\"'%(__name__,self.kw['executable'],' '.join(self.args)))
 
82
 
 
83
        def run(self,k):
 
84
                '''run filter'''
 
85
                for i,line in enumerate(self.p.cfoutput[k]['tempbuff']):
 
86
                        self.subproc.stdin.write('%s\n'%(line.strip().encode(self.encoding)))
 
87
                        self.p.cfoutput[k]['tempbuff'][i] = self.subproc.stdout.readline().rstrip().decode(self.encoding)
 
88
 
 
89
        def flush(self,k):
 
90
                return
 
91
 
 
92
        def close(self):
 
93
                return
 
94
 
 
95
def usage():
 
96
        '''Command prompt help.'''
 
97
        return "\n%s\n\tUsage:\n\tfrom %s import filter\n"%(
 
98
        os.path.basename(sys.argv[0]),
 
99
        os.path.splitext(os.path.basename(sys.argv[0]))[0]
 
100
        )
 
101
 
 
102
licensetxt=u'''CorpusFiltergraph™ v4.0
 
103
Copyright © 2010-2012 Precision Translation Tools Co., Ltd.
 
104
 
 
105
This program is free software: you can redistribute it and/or modify
 
106
it under the terms of the GNU Lesser General Public License as published by
 
107
the Free Software Foundation, either version 3 of the License, or
 
108
(at your option) any later version.
 
109
 
 
110
This program is distributed in the hope that it will be useful,
 
111
but WITHOUT ANY WARRANTY; without even the implied warranty of
 
112
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
113
GNU Lesser General Public License for more details.
 
114
 
 
115
You should have received a copy of the GNU Lesser General Public License
 
116
along with this program.  If not, see http://www.gnu.org/licenses/.
 
117
 
 
118
For more information, please contact Precision Translation Tools Co., Ltd.
 
119
at: http://www.precisiontranslationtools.com'''
 
120
 
 
121
if __name__ == "__main__":
 
122
        import os
 
123
        import sys
 
124
        sys.stdout.write(usage().encode('utf8')+'\n')