2019년 2월 23일 토요일

[Python] Shell Command Library Wrappers


pyshell.py

1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import sys
import os
import time
import select
import copy
import subprocess
import threading
from threading import *
  
######################################################################
# ShellExecute without Thread
######################################################################

def ShellExecute(cmd, timeout=None):
    
    si = subprocess.STARTUPINFO()
    si.dwFlags |= subprocess.STARTF_USESHOWWINDOW #|subprocess.STARTF_USESTDHANDLES
    si.wShowWindow = subprocess.SW_HIDE
        
    process = subprocess.Popen(cmd
        , shell=True
        #, stdin=subprocess.DEVNULL
        , stdout=subprocess.PIPE
        , stderr=subprocess.PIPE
        , startupinfo=si
        )

    outs, errs = process.communicate(timeout=timeout)
        
    #print(outs.decode("euc-kr").replace('\r',''))
    #print(errs.decode("euc-kr").replace('\r',''))
    #print('poll:: return: ' + str(process.poll()))
    #print('code:: return: ' + str(process.returncode))
    
    return process.returncode, outs, errs

'''
def ShellExecuteRealTime_V2(cmd, timeout=None):
    
    si = subprocess.STARTUPINFO()
    si.dwFlags |= subprocess.STARTF_USESHOWWINDOW #|subprocess.STARTF_USESTDHANDLES
    si.wShowWindow = subprocess.SW_HIDE
        
    process = subprocess.Popen(cmd
        , shell=True
        #, stdin=subprocess.DEVNULL
        , stdout=subprocess.PIPE
        , stderr=subprocess.PIPE
        , startupinfo=si
        )

    stdouts = []
    stderrs = []

    while True:
        fds = [process.stdout.fileno(), process.stderr.fileno()]
        rv = select.select(fds, [], [])
        for fd in rv[0]:
            if fd == process.stdout.fileno():
                chars = process.stdout.read()
                sys.stdout.write(chars.decode("euc-kr").replace('\r',''))
                stdouts.append(chars)
            if fd == process.stderr.fileno():
                chars = process.stderr.read()
                sys.stderr.write(chars.decode("euc-kr").replace('\r',''))
                stderrs.append(chars)
        if p.poll() != None:
            break

    return process.returncode
'''

def ShellExecuteRealTime(cmd, timeout=None):
    
    si = subprocess.STARTUPINFO()
    si.dwFlags |= subprocess.STARTF_USESHOWWINDOW #|subprocess.STARTF_USESTDHANDLES
    si.wShowWindow = subprocess.SW_HIDE
        
    process = subprocess.Popen(cmd
        , shell=True
        , stdin=subprocess.DEVNULL
        , stdout=subprocess.PIPE
        , stderr=subprocess.DEVNULL
        , startupinfo=si
        )

    outs = b''
    while True:
        char = process.stdout.read() # read(1), process.stderr.readline()
        if not char:
            break
        outs += char
    #sys.stdout.write(char.decode("euc-kr").replace('\r',''))
        
    return process.returncode, outs

######################################################################
# ShellCommand with small output string
#
# outs, errs = Popen.communicate(input=None, timeout=None)
#
# proc = subprocess.Popen(...)
# try:
#     outs, errs = proc.communicate(timeout=15)
# except TimeoutExpired:
#     proc.kill()
#     outs, errs = proc.communicate()
#
# Note:
# The data read is buffered in memory, so do not use this method if the data size is large or unlimited.
######################################################################

class ShellExecuteThread(object):
    
    def __init__(self, cmd, timeout=None):
        self.cmd = cmd
        self.thread = None
        self.process = None
        self.timeout = timeout
        self.stdouts = None
        self.stderrs = None
        self.running = None
        self.lock = threading.Lock()

    def run(self, timeout=None):
        if timeout is not None:
            self.timeout = timeout
        def target():
            self.running = True
            si = subprocess.STARTUPINFO()
            si.dwFlags |= subprocess.STARTF_USESHOWWINDOW # |subprocess.STARTF_USESTDHANDLES
            si.wShowWindow = subprocess.SW_HIDE
            self.process = subprocess.Popen(self.cmd
                    , shell=True 
                    , stdout=subprocess.PIPE
                    , stderr=subprocess.PIPE                    
                    , startupinfo=si
                    , bufsize=0
                    , universal_newlines=True 
                    , encoding='euc-kr'
                    , text=True
                )
            self.stdouts, self.stderrs = self.process.communicate(self.timeout)
            self.running = False

        self.thread = threading.Thread(target=target)
        self.thread.start()
        
    def runwait(self, timeout=None):
        self.run(timeout)
        self.thread.join(self.timeout)
        if self.thread.is_alive():
            self.process.terminate()
            self.thread.join()

        return self.process.returncode, self.stdouts, self.stderrs

    def run_stdouts(self):
        def target():
            self.running = True
            word = b''
            while True:
                char = self.process.stdout.read(1) #readline()
                if not char:
                    break
                if self.process.poll() is not None:
                    break;
                word += char
                if char.isspace():
                    self.lock.acquire()
                    self.stdouts += word
                    self.lock.release() 
                    word = b''
            if len(word) > 0:
                self.lock.acquire()
                self.stdouts += word
                self.lock.release() 
            self.running = False
            
        si = subprocess.STARTUPINFO()
        si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        si.wShowWindow = subprocess.SW_HIDE
        self.process = subprocess.Popen(self.cmd
                , shell=True 
                , stdout=subprocess.PIPE
                , startupinfo=si
            )

        self.stdouts = b'';
        self.thread = threading.Thread(target=target)
        self.thread.start()
        
    def get_stdouts(self):
        if self.running == True or len(self.stdouts) > 0 is None:
            self.lock.acquire()
            outs = self.stdouts  #copy.deepcopy(self.stdouts)
            self.stdouts = b'';
            self.lock.release()            
            return outs
        else:
            return None
    
    def get_returncode(self):
        if self.process is not None:
            return self.process.returncode
        return None
    
###########################################################################
## ShellExecute with WorkerThread
###########################################################################

class WorkerThread(Thread):
    
    def __init__(self, cmd, timeout=None):
        Thread.__init__(self)
        self.cmd = cmd
        self.stoprequest = threading.Event()
        self.start()

    def run(self):
        import subprocess
        global threadLock
        global line
        
        si = subprocess.STARTUPINFO()
        si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        si.wShowWindow = subprocess.SW_HIDE

        process = subprocess.Popen(self.cmd
                , shell=False 
                , stdin=subprocess.DEVNULL
                , stdout=subprocess.PIPE
                , stderr=subprocess.PIPE
                , startupinfo=si
                )

        while not self.stoprequest.isSet():
            char = process.stdout.read(1) #process.stderr.readline()
            if not char:
                break
            if process.poll() is not None:
                break;
            if char != b'\r': # accept only b'\n'
                self.lock.acquire()
                self.stdouts += char
                self.lock.release()    

        errcode = process.returncode
        if errcode is not None:
            raise Exception('cmd %s failed, see above for details', cmd)
        process.terminate()

    def stop(self, timeout=None):
        self.stoprequest.set()
        super(WorkerThread, self).join(timeout)
        

def main():
    
    #code, outs, errs = ShellExecute("dir C:\\")
    #print( outs.decode("euc-kr").replace('\r','') )
    
    #code, outs = ShellExecuteRealTime("dir C:\\")
    #print( outs.decode("euc-kr").replace('\r','') )
    
    #th = ShellExecuteThread("dir C:\\")
    #code, outs, errs = th.runwait()
    #print( outs.decode("euc-kr").replace('\r','') )

    th = ShellExecuteThread("dir C:\\")
    th.run_stdouts()
    while True:
        outs = th.get_stdouts()
        if outs is None:
            break
        if len(outs) > 0:
            print( outs.decode('euc-kr').replace('\r','') )
    
    #th = ShellExecuteThread("dir C://")
    #th.run()

if __name__ == '__main__':
    print( os.getcwd() )
    main()
    exit(0)

댓글 없음:

댓글 쓰기