Skip to content

Commit bdbc287

Browse files
author
zhenwei-li
committed
the execure optimization
1 parent 484e034 commit bdbc287

3 files changed

Lines changed: 65 additions & 38 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# -*- coding:utf-8 -*-

src/com/dvsnier/process/execute.py

Lines changed: 42 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,60 @@
11
# -- coding:utf-8 --
22

33
import datetime
4-
# import logging
5-
import os
6-
import platform
7-
import time
8-
import sys
4+
import logging
95
import subprocess
6+
import time
107

118
from com.dvsnier.directory.common_dir import generate_complex_file_name
129

1310

1411
def execute(cmds, quiet=True):
1512
'the process execute that a command'
13+
content = ''
14+
stdouts = None
1615
start = time.time()
17-
p = subprocess.Popen(cmds[0], stdout=subprocess.PIPE, shell=True)
18-
# logging.debug('the current sub process pid(cwd: %s, ppid: %s, id: %s%d).' %
19-
# (p.pid, os.getppid(), type(p), id(p)))
20-
processes = [p]
21-
for x in cmds[1:]:
22-
p = subprocess.Popen(x, stdin=p.stdout, stdout=subprocess.PIPE, shell=True)
23-
# logging.debug(
24-
# 'the current sub process pid(cwd: %s, ppid: %s, id: %s%d).' %
25-
# (p.pid, os.getppid(), type(p), id(p)))
26-
# logging.debug(type(p), id(p))
27-
processes.append(p)
28-
# logging.debug('the current run process pid(cwd: %s, ppid: %s, id: %s%d).' %
29-
# (p.pid, os.getppid(), type(p), id(p)))
30-
# logging.debug(type(p), id(p))
31-
output = p.communicate()[0]
32-
for p in processes:
33-
p.wait()
16+
with subprocess.Popen(cmds[0], stdout=subprocess.PIPE, shell=True) as p:
17+
# logging.debug('the current sub process pid(cwd: %s, ppid: %s, id: %s%d).' %
18+
# (p.pid, os.getppid(), type(p), id(p)))
19+
processes = [p]
20+
for x in cmds[1:]:
21+
#
22+
# the airticle link reference:
23+
#
24+
# 1. https://docs.python.org/2.7/library/subprocess.html#subprocess.Popen.communicate
25+
# 2. https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate
26+
# 3. https://stackoverflow.com/questions/58649679/resourcewarning-unclosed-file-io-bufferedreader-name-4
27+
# 4. https://python.readthedocs.io/en/stable/library/subprocess.html
28+
#
29+
p = subprocess.Popen(x, stdin=p.stdout, stdout=subprocess.PIPE, bufsize=1024, shell=True)
30+
# logging.debug(
31+
# 'the current sub process pid(cwd: %s, ppid: %s, id: %s%d).' %
32+
# (p.pid, os.getppid(), type(p), id(p)))
33+
# logging.debug(type(p), id(p))
34+
processes.append(p)
35+
# logging.debug('the current run process pid(cwd: %s, ppid: %s, id: %s%d).' %
36+
# (p.pid, os.getppid(), type(p), id(p)))
37+
# logging.debug(type(p), id(p))
38+
stdouts, stderrs = p.communicate()
39+
if stderrs:
40+
logging.error(stderrs)
41+
for p in processes:
42+
p.kill()
43+
p.wait()
3444

3545
end = time.time()
3646
if not quiet:
37-
if platform.system() == 'Linux' and os.isatty(1):
38-
print('\r'),
3947
msg = '[%.5f] -> %s' % (end - start, ' | '.join(cmds))
40-
print(msg)
41-
content = None
42-
if sys.version_info.major > 2:
43-
content = str(output.rstrip(bytes('\n', encoding='utf-8')), encoding='utf-8')
44-
else:
45-
content = output.rstrip('\n')
46-
# logging.debug('the current run process pid(cwd: %s, ppid: %s, id: %s%d).' %
47-
# (p.pid, os.getppid(), type(p), id(p)))
48+
logging.debug(msg)
49+
if stdouts:
50+
if isinstance(stdouts, str):
51+
content = str(stdouts).rstrip('\n')
52+
elif isinstance(stdouts, bytes):
53+
content = str(stdouts.rstrip(bytes('\n', encoding='utf-8')), encoding='utf-8')
54+
else:
55+
content = ''
56+
# logging.debug('the current run process pid(cwd: %s, ppid: %s, id: %s%d).' %
57+
# (p.pid, os.getppid(), type(p), id(p)))
4858
return content
4959

5060

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# -*- coding:utf-8 -*-
22

3+
# import tracemalloc
34
import unittest
45

56
from com.dvsnier.process.execute import execute, trace
@@ -10,35 +11,50 @@ class Test_Execute(unittest.TestCase):
1011
@classmethod
1112
def setUpClass(cls):
1213
print("...the set up...")
13-
print
14+
print('')
1415

1516
def setUp(self):
16-
return super(Test_Execute, self).setUp()
17+
super(Test_Execute, self).setUp()
1718

1819
def test_execute(self):
1920
'the test execute'
21+
# self.debug_trace_malloc_start()
2022
# cmds = ["git config --local --list"]
2123
# cmds = ["git config --local --list", "grep \"user\""]
2224
cmds = ["git config --local --list", "grep \"user\"", "grep \"@\""]
2325
result = execute(cmds, quiet=False)
2426
self.assertIsNotNone(result, 'test_execute is error.')
25-
print(result)
27+
# self.debug_trace_malloc_end()
2628

2729
def test_trace(self):
2830
'the test trace'
31+
# self.debug_trace_malloc_start()
2932
# cmds = ["git config --local --list"]
3033
# cmds = ["git config --local --list", "grep \"user\""]
3134
cmds = ["git config --local --list", "grep \"user\"", "grep \"@\""]
3235
trace(cmds)
36+
# self.debug_trace_malloc_end()
37+
38+
# def debug_trace_malloc_start(self):
39+
# tracemalloc.start()
40+
41+
# def debug_trace_malloc_end(self):
42+
# snapshot = tracemalloc.take_snapshot()
43+
# top_stats = snapshot.statistics('lineno')
44+
# print("[ Top 10 ]")
45+
# for stat in top_stats[:10]:
46+
# print(stat)
3347

3448
def tearDown(self):
35-
return super(Test_Execute, self).tearDown()
49+
super(Test_Execute, self).tearDown()
3650

3751
@classmethod
3852
def tearDownClass(cls):
39-
print
53+
print('')
4054
print("...the tear down...")
4155

4256

4357
if __name__ == '__main__':
44-
unittest.main()
58+
suite = unittest.TestLoader().loadTestsFromTestCase(Test_Execute)
59+
unittest.TextTestRunner(verbosity=2).run(suite)
60+
# unittest.main()

0 commit comments

Comments
 (0)