~jtv/corpusfiltergraph/cross-python

« back to all changes in this revision

Viewing changes to trunk/lib/corpusfg/plugins/subprocess-synch.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 common as cf
 
15
import logging
 
16
 
 
17
logger = logging.getLogger('.'.join([os.path.splitext(os.path.basename(sys.argv[0]))[0],'manager','filtergraph',__name__]))
 
18
skipclose = True
 
19
 
 
20
class filter(object):
 
21
 
 
22
        cfg = {
 
23
                'args': {},
 
24
                'encoding': 'utf8',
 
25
                'exeoptions': '',
 
26
                'kw': {
 
27
                        'bufsize': 0,
 
28
                        'executable': None,
 
29
                        'stdin': 'PIPE',
 
30
                        'stdout': 'PIPE',
 
31
                        'stderr': 'PIPE',
 
32
                        'preexec_fn': None,
 
33
                        'close_fds': False,
 
34
                        'shell': False,
 
35
                        'cwd': None,
 
36
                        'env': None,
 
37
                        'universal_newlines': False,
 
38
                        'startupinfo': None,
 
39
                        'creationflags': 0,
 
40
                        },
 
41
                'script': '',
 
42
                'inputfile': '',
 
43
                'outputfile': '',
 
44
                'version': '4.0.264',
 
45
                }
 
46
        args = []
 
47
        encoding = 'utf8'
 
48
        kw = {}
 
49
        script = ''
 
50
        inputfile = ''
 
51
        outputfile = ''
 
52
        isopen = False
 
53
        p = object
 
54
        errors = []
 
55
 
 
56
        def open(self,parent,cfg):
 
57
                self.args = dict(cfg['args'])
 
58
                self.kw = dict(cfg['kw'])
 
59
                if cfg['script']:
 
60
                        self.script = self.p.decodepath('%s,%s'%(__name__.split(',')[1],cfg['script']),True)
 
61
                        if not self.script:
 
62
                                self.errors.append([__name__,'missing',cfg['script']])
 
63
                                logger.error('%s\t%s',*self.errors[-1][1:])
 
64
                        self.args[0] = self.script
 
65
                        self.kw['cwd'] = os.path.dirname(self.script)
 
66
                else:
 
67
                        self.script = None
 
68
                # convert args dict to args list
 
69
                self.args = [str(self.args[k]) for k in sorted(self.args.keys())]
 
70
                if 'executable' in cfg['kw'] and cfg['kw']['executable']:
 
71
                        self.kw['executable'] = self.p.decodepath('%s,%s'%(__name__.split(',')[1],cfg['kw']['executable']),True)
 
72
                        if not self.kw['executable']:
 
73
                                self.errors.append([__name__,'missing',cfg['kw']['executable']])
 
74
                                logger.error('%s\t%s',*self.errors[-1][1:])
 
75
                        self.args.insert(0,cfg['exeoptions'] if cfg['exeoptions'] else '')
 
76
                else:
 
77
                        self.kw['executable'] = None
 
78
                self.kw['stdin'] = subprocess.PIPE if cfg['kw']['stdin'] == 'PIPE' else cfg['kw']['stdin']
 
79
                self.kw['stdout'] = subprocess.PIPE if cfg['kw']['stdout'] == 'PIPE' else cfg['kw']['stdout']
 
80
                self.kw['stderr'] = subprocess.PIPE if cfg['kw']['stderr'] == 'PIPE' else cfg['kw']['stderr']
 
81
 
 
82
                self.encoding = 'utf8' if 'utf8' in cfg['encoding'].lower().replace('-','') else cfg['encoding']
 
83
                self.inputfile = cfg['inputfile'].replace('%(rootfolder)s',self.p.rootfolder) if cfg['inputfile'] else self.inputfile
 
84
                self.outputfile = cfg['outputfile'].replace('%(rootfolder)s',self.p.rootfolder) if cfg['outputfile'] else self.outputfile
 
85
                if (self.inputfile and not self.outputfile) or (not self.inputfile and self.outputfile):
 
86
                        self.errors.append([__name__,'invalid','[%s] inputfile=%s without outputfile= value'%(__name__,cfg['inputfile'])])
 
87
                        logger.warn('%s\t%s',*self.errors[-1][1:])
 
88
 
 
89
        def run(self,k):
 
90
                global skipclose
 
91
                skipclose = not self.inputfile
 
92
                if self.inputfile: return
 
93
 
 
94
                try:
 
95
                        subproc = subprocess.Popen(self.args,**self.kw)
 
96
                except Exception,e:
 
97
                        raise RuntimeError('failed \"[%s]\" \"%s %s\" - %s'%(__name__,self.kw['executable'],' '.join(self.args),str(e)))
 
98
                txtout, txterr = subproc.communicate('\x0a'.join(self.p.cfoutput[k]['tempbuff']).encode(self.encoding) + '\n')
 
99
                self.p.cfoutput[k]['tempbuff'] = [line.decode(self.encoding) for line in txtout.splitlines()]
 
100
 
 
101
        def flush(self,k):
 
102
                return
 
103
 
 
104
        def close(self):
 
105
                if skipclose: return
 
106
 
 
107
                import codecs
 
108
 
 
109
                if not os.path.exists(self.inputfile):
 
110
                        self.errors.append([__name__,'missing','[%s] %s'%(__name__,self.inputfile)])
 
111
                        logger.error('%s\t%s',*self.errors[-1][1:])
 
112
                        return
 
113
 
 
114
                # make output folder
 
115
                try:
 
116
                        os.makedirs(os.path.dirname(self.outputfile))
 
117
                except OSError,e:
 
118
                        if not e.errno == 17:
 
119
                                logger.exception('%s\t%s, %s, %s',*['failed',e.errno,e.strerror,e.filename,])
 
120
                                raise OSError(e)
 
121
 
 
122
                # open input and output files
 
123
                out = self.outputfile
 
124
                if out == self.inputfile:
 
125
                        import tempfile
 
126
                        fd,out = tempfile.mkstemp(suffix='.tmp', prefix='~', dir=self.p.tempdir)
 
127
                        os.close(fd)
 
128
                try:
 
129
                        o = codecs.open(out,'w',self.encoding)
 
130
                        i = codecs.open(self.inputfile,'r',self.encoding)
 
131
                except:
 
132
                        os.unlink(out)
 
133
                        raise RuntimeError('Failed to open [%s] input/output files'%(__name__))
 
134
 
 
135
                sys.stderr.write('[%s] %s\n   Please wait'%(__name__,self.outputfile))
 
136
                cnt = 0
 
137
 
 
138
                try:
 
139
                        subproc = subprocess.Popen(self.args,**self.kw)
 
140
                except Exception,e:
 
141
                        raise RuntimeError('failed \"[%s]\" \"%s %s\" - %s'%(__name__,self.kw['executable'],' '.join(self.args),str(e)))
 
142
 
 
143
                try:
 
144
                        # loop writes output line-by-line
 
145
                        for line in i:
 
146
                                subproc[tgtlang]['popen'].stdin.write('%s\n'%(line.encode(self.encoding).strip()))
 
147
                                o.write('%s\n'%(subproc[tgtlang]['popen'].stdout.readline().rstrip('\r\n').decode(self.encoding)))
 
148
                                cnt += 1
 
149
                                if not cnt%5000: sys.stderr.write('.')
 
150
                        sys.stderr.write('\n')
 
151
                        # close input and output files
 
152
                        i.close()
 
153
                        o.close()
 
154
 
 
155
                        if not out == self.outputfile:
 
156
                                import shutil
 
157
                                shutil.move(out,self.outputfile)
 
158
 
 
159
                except KeyboardInterrupt:
 
160
                        os.unlink(out)
 
161
                        raise KeyboardInterrupt()
 
162
 
 
163
                if not os.path.exists(self.outputfile):
 
164
                        self.errors.append([__name__,'missing','[%s] %s'%(__name__,self.outputfile)])
 
165
                        logger.error('%s\t%s',*self.errors[-1][1:])
 
166
 
 
167
def usage():
 
168
        '''Command prompt help.'''
 
169
        return "\n%s\n\tUsage:\n\tfrom %s import filter\n"%(
 
170
        os.path.basename(sys.argv[0]),
 
171
        os.path.splitext(os.path.basename(sys.argv[0]))[0]
 
172
        )
 
173
 
 
174
licensetxt=u'''CorpusFiltergraph™ v4.0
 
175
Copyright © 2010-2012 Precision Translation Tools Co., Ltd.
 
176
 
 
177
This program is free software: you can redistribute it and/or modify
 
178
it under the terms of the GNU Lesser General Public License as published by
 
179
the Free Software Foundation, either version 3 of the License, or
 
180
(at your option) any later version.
 
181
 
 
182
This program is distributed in the hope that it will be useful,
 
183
but WITHOUT ANY WARRANTY; without even the implied warranty of
 
184
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
185
GNU Lesser General Public License for more details.
 
186
 
 
187
You should have received a copy of the GNU Lesser General Public License
 
188
along with this program.  If not, see http://www.gnu.org/licenses/.
 
189
 
 
190
For more information, please contact Precision Translation Tools Co., Ltd.
 
191
at: http://www.precisiontranslationtools.com'''
 
192
 
 
193
if __name__ == "__main__":
 
194
        import os
 
195
        import sys
 
196
        sys.stdout.write(usage().encode('utf8')+'\n')