Skip to content

Commit 469c5e7

Browse files
authored
some subprocess.Popen() related Python cleanups / added TODOs about missing returncode usage (#7065)
1 parent b194c6f commit 469c5e7

15 files changed

+81
-55
lines changed

addons/cppcheckdata.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1714,8 +1714,9 @@ def get_path_premium_addon():
17141714

17151715
def cmd_output(cmd):
17161716
with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
1717-
comm = p.communicate()
1718-
out = comm[0]
1719-
if p.returncode == 1 and len(comm[1]) > 2:
1720-
out = comm[1]
1721-
return out.decode(encoding='utf-8', errors='ignore')
1717+
stdout, stderr = p.communicate()
1718+
rc = p.returncode
1719+
out = stdout
1720+
if rc == 1 and len(stderr) > 2:
1721+
out = stderr
1722+
return out.decode(encoding='utf-8', errors='ignore')

test/cli/clang-import_test.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from testutils import cppcheck, assert_cppcheck
1010

1111
try:
12+
# TODO: handle exitcode?
1213
subprocess.call(['clang', '--version'])
1314
except OSError:
1415
pytest.skip("'clang' does not exist", allow_module_level=True)

test/cli/testutils.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ def __run_subprocess(args, env=None, cwd=None, timeout=None):
119119
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, cwd=cwd)
120120

121121
try:
122-
comm = p.communicate(timeout=timeout)
122+
stdout, stderr = p.communicate(timeout=timeout)
123123
return_code = p.returncode
124124
p = None
125125
except subprocess.TimeoutExpired:
@@ -141,10 +141,9 @@ def __run_subprocess(args, env=None, cwd=None, timeout=None):
141141
# sending the signal to the process groups causes the parent Python process to terminate as well
142142
#os.killpg(os.getpgid(p.pid), signal.SIGTERM) # Send the signal to all the process groups
143143
p.terminate()
144-
comm = p.communicate()
144+
stdout, stderr = p.communicate()
145+
p = None
145146

146-
stdout = comm[0]
147-
stderr = comm[1]
148147
return return_code, stdout, stderr
149148

150149

test/signal/test-signalhandler.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,11 @@ def __call_process(arg):
2424
if exe is None:
2525
raise Exception('executable not found')
2626
with subprocess.Popen([exe, arg], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
27-
comm = p.communicate()
28-
stdout = comm[0].decode(encoding='utf-8', errors='ignore').replace('\r\n', '\n')
29-
stderr = comm[1].decode(encoding='utf-8', errors='ignore').replace('\r\n', '\n')
30-
return p.returncode, stdout, stderr
27+
stdout, stderr = p.communicate()
28+
rc = p.returncode
29+
stdout = stdout.decode(encoding='utf-8', errors='ignore').replace('\r\n', '\n')
30+
stderr = stderr.decode(encoding='utf-8', errors='ignore').replace('\r\n', '\n')
31+
return rc, stdout, stderr
3132

3233

3334
def test_assert():

test/signal/test-stacktrace.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,11 @@ def __call_process():
2323
if exe is None:
2424
raise Exception('executable not found')
2525
with subprocess.Popen([exe], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
26-
comm = p.communicate()
27-
stdout = comm[0].decode(encoding='utf-8', errors='ignore').replace('\r\n', '\n')
28-
stderr = comm[1].decode(encoding='utf-8', errors='ignore').replace('\r\n', '\n')
29-
return p.returncode, stdout, stderr
26+
stdout, stderr = p.communicate()
27+
rc = p.returncode
28+
stdout = stdout.decode(encoding='utf-8', errors='ignore').replace('\r\n', '\n')
29+
stderr = stderr.decode(encoding='utf-8', errors='ignore').replace('\r\n', '\n')
30+
return rc, stdout, stderr
3031

3132

3233
def test_stack():

tools/bisect/bisect_res.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,17 @@ def run(cppcheck_path, options):
1010
print('running {}'.format(cppcheck_path))
1111
with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) as p:
1212
stdout, stderr = p.communicate()
13-
# only 0 and 1 are well-defined in this case
14-
if p.returncode > 1:
15-
print('error')
16-
return None, None, None
17-
# signals are reported as negative exitcode (e.g. SIGSEGV -> -11)
18-
if p.returncode < 0:
19-
print('crash')
20-
return p.returncode, stderr, stdout
21-
print('done')
22-
return p.returncode, stderr, stdout
13+
rc = p.returncode
14+
# only 0 and 1 are well-defined in this case
15+
if rc > 1:
16+
print('error')
17+
return None, None, None
18+
# signals are reported as negative exitcode (e.g. SIGSEGV -> -11)
19+
if rc < 0:
20+
print('crash')
21+
return rc, stderr, stdout
22+
print('done')
23+
return rc, stderr, stdout
2324

2425

2526
# TODO: check arguments

tools/ci.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,10 @@ def gitpush():
4141
def iconv(filename):
4242
with subprocess.Popen(['file', '-i', filename],
4343
stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:
44-
comm = p.communicate()
45-
if 'charset=iso-8859-1' in comm[0]:
44+
# TODO: handle p.returncode?
45+
stdout, _ = p.communicate()
46+
if 'charset=iso-8859-1' in stdout:
47+
# TODO: handle exitcode?
4648
subprocess.call(
4749
["iconv", filename, "--from=ISO-8859-1", "--to=UTF-8", "-o", filename])
4850

@@ -51,14 +53,19 @@ def iconv(filename):
5153
def generate_webreport():
5254
for filename in glob.glob('*/*.cpp'):
5355
iconv(filename)
56+
# TODO: handle exitcode?
5457
subprocess.call(
5558
["git", "commit", "-a", "-m", '"automatic conversion from iso-8859-1 formatting to utf-8"'])
5659
gitpush()
5760

61+
# TODO: handle exitcode?
5862
subprocess.call(["rm", "-rf", "devinfo"])
63+
# TODO: handle exitcode?
5964
subprocess.call(['nice', "./webreport.sh"])
6065
upload('-r devinfo', 'htdocs/')
66+
# TODO: handle exitcode?
6167
subprocess.call(["make", "clean"])
68+
# TODO: handle exitcode?
6269
subprocess.call(["rm", "-rf", "devinfo"])
6370

6471

tools/compare_ast_symdb.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,9 @@ def run_cppcheck(cppcheck_parameters:str, clang:str):
1515
cmd = '{} {} {} --debug --verbose'.format(CPPCHECK, cppcheck_parameters, clang)
1616
#print(cmd)
1717
with subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
18-
comm = p.communicate()
19-
return comm[0].decode('utf-8', 'ignore')
18+
# TODO: handle p.returncode?
19+
stdout, _ = p.communicate()
20+
return stdout.decode('utf-8', 'ignore')
2021

2122

2223
def get_ast(debug):

tools/daca2-download.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ def wget(filepath):
2323
if '/' in filepath:
2424
filename = filename[filename.rfind('/') + 1:]
2525
for d in DEBIAN:
26+
# TODO: handle exitcode?
2627
subprocess.call(
2728
['nice', 'wget', '--tries=10', '--timeout=300', '-O', filename, d + filepath])
2829
if os.path.isfile(filename):
@@ -40,9 +41,11 @@ def latestvername(names):
4041
def getpackages():
4142
if not wget('ls-lR.gz'):
4243
return []
44+
# TODO: handle exitcode?
4345
subprocess.call(['nice', 'gunzip', 'ls-lR.gz'])
4446
with open('ls-lR', 'rt') as f:
4547
lines = f.readlines()
48+
# TODO: handle exitcode?
4649
subprocess.call(['rm', 'ls-lR'])
4750

4851
path = None
@@ -141,10 +144,13 @@ def downloadpackage(filepath, outpath):
141144

142145
filename = filepath[filepath.rfind('/') + 1:]
143146
if filename[-3:] == '.gz':
147+
# TODO: handle exitcode?
144148
subprocess.call(['tar', 'xzvf', filename])
145149
elif filename[-3:] == '.xz':
150+
# TODO: handle exitcode?
146151
subprocess.call(['tar', 'xJvf', filename])
147152
elif filename[-4:] == '.bz2':
153+
# TODO: handle exitcode?
148154
subprocess.call(['tar', 'xjvf', filename])
149155
else:
150156
return
@@ -153,6 +159,7 @@ def downloadpackage(filepath, outpath):
153159

154160
for g in glob.glob('[#_A-Za-z0-9]*'):
155161
if os.path.isdir(g):
162+
# TODO: handle exitcode?
156163
subprocess.call(['tar', '-cJvf', outpath + filename[:filename.rfind('.')] + '.xz', g])
157164
break
158165

tools/daca2-getpackages.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ def wget(filepath):
2424
if '/' in filepath:
2525
filename = filename[filename.rfind('/') + 1:]
2626
for d in DEBIAN:
27+
# TODO: handle exitcode?
2728
subprocess.call(
2829
['nice', 'wget', '--tries=10', '--timeout=300', '-O', filename, d + filepath])
2930
if os.path.isfile(filename):
@@ -41,11 +42,13 @@ def latestvername(names):
4142
def getpackages():
4243
if not wget('ls-lR.gz'):
4344
sys.exit(1)
45+
# TODO: handle exitcode?
4446
subprocess.call(['nice', 'gunzip', 'ls-lR.gz'])
4547
if not os.path.isfile('ls-lR'):
4648
sys.exit(1)
4749
with open('ls-lR', 'rt') as f:
4850
lines = f.readlines()
51+
# TODO: handle exitcode?
4952
subprocess.call(['rm', 'ls-lR'])
5053

5154
# Example content in ls-lR:

tools/donate-cpu.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -251,10 +251,11 @@ def get_client_version_head(path):
251251
cmd = 'python3' + ' ' + os.path.join(path, 'tools', 'donate-cpu.py') + ' ' + '--version'
252252
with subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, universal_newlines=True) as p:
253253
try:
254-
comm = p.communicate()
255-
return comm[0].strip()
254+
# TODO: handle p.returncode?
255+
stdout, _ = p.communicate()
256256
except:
257257
return None
258+
return stdout.strip()
258259

259260
client_version_head = get_client_version_head(tree_path)
260261
c, errout, info, t, cppcheck_options, timing_info = lib.scan_package(tree_path, source_path, libraries, capture_callstack)

tools/donate_cpu_lib.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
# Version scheme (MAJOR.MINOR.PATCH) should orientate on "Semantic Versioning" https://semver.org/
1717
# Every change in this script should result in increasing the version number accordingly (exceptions may be cosmetic
1818
# changes)
19-
CLIENT_VERSION = "1.3.65"
19+
CLIENT_VERSION = "1.3.66"
2020

2121
# Timeout for analysis with Cppcheck in seconds
2222
CPPCHECK_TIMEOUT = 30 * 60
@@ -403,13 +403,12 @@ def __run_command(cmd, print_cmd=True):
403403
if print_cmd:
404404
print(cmd)
405405
time_start = time.time()
406-
comm = None
407406
if sys.platform == 'win32':
408407
p = subprocess.Popen(shlex.split(cmd, comments=False, posix=False), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, errors='surrogateescape')
409408
else:
410409
p = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, errors='surrogateescape', preexec_fn=os.setsid)
411410
try:
412-
comm = p.communicate(timeout=CPPCHECK_TIMEOUT)
411+
stdout, stderr = p.communicate(timeout=CPPCHECK_TIMEOUT)
413412
return_code = p.returncode
414413
p = None
415414
except subprocess.TimeoutExpired:
@@ -422,16 +421,16 @@ def __run_command(cmd, print_cmd=True):
422421
child.terminate()
423422
try:
424423
# call with timeout since it might get stuck e.g. gcc-arm-none-eabi
425-
comm = p.communicate(timeout=5)
424+
stdout, stderr = p.communicate(timeout=5)
426425
p = None
427426
except subprocess.TimeoutExpired:
428427
pass
429428
finally:
430429
if p:
431430
os.killpg(os.getpgid(p.pid), signal.SIGTERM) # Send the signal to all the process groups
432-
comm = p.communicate()
431+
stdout, stderr = p.communicate()
432+
p = None
433433
time_stop = time.time()
434-
stdout, stderr = comm
435434
elapsed_time = time_stop - time_start
436435
return return_code, stdout, stderr, elapsed_time
437436

@@ -545,7 +544,7 @@ def scan_package(cppcheck_path, source_path, libraries, capture_callstack=True,
545544
cmd += dir_to_scan
546545
_, st_stdout, _, _ = __run_command(cmd)
547546
gdb_pos = st_stdout.find(" received signal")
548-
if not gdb_pos == -1:
547+
if gdb_pos != -1:
549548
last_check_pos = st_stdout.rfind('Checking ', 0, gdb_pos)
550549
if last_check_pos == -1:
551550
stacktrace = st_stdout[gdb_pos:]
@@ -765,10 +764,10 @@ def has_include(filedata):
765764
def get_compiler_version():
766765
if __make_cmd == 'msbuild.exe':
767766
_, _, stderr, _ = __run_command('cl.exe', False)
768-
return stderr.split('\n')[0]
767+
return stderr.split('\n', maxsplit=1)[0]
769768

770769
_, stdout, _, _ = __run_command('g++ --version', False)
771-
return stdout.split('\n')[0]
770+
return stdout.split('\n', maxsplit=1)[0]
772771

773772

774773
def get_client_version():

tools/reduce.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def runtool(self, filedata=None):
6464
timeout = self.__elapsed_time * 2
6565
p = subprocess.Popen(self.__cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
6666
try:
67-
comm = self.__communicate(p, timeout=timeout)
67+
stdout, stderr = self.__communicate(p, timeout=timeout)
6868
except TimeoutExpired:
6969
print('timeout')
7070
p.kill()
@@ -78,13 +78,13 @@ def runtool(self, filedata=None):
7878
if p.returncode != 0:
7979
return True
8080
elif p.returncode == 0:
81-
out = comm[0] + '\n' + comm[1]
81+
out = stdout + '\n' + stderr
8282
if self.__expected in out:
8383
return True
8484
else:
8585
# Something could be wrong, for example the command line for Cppcheck (CMD).
8686
# Print the output to give a hint how to fix it.
87-
print('Error: {}\n{}'.format(comm[0], comm[1]))
87+
print('Error: {}\n{}'.format(stdout, stderr))
8888
return False
8989

9090
def __writefile(self, filename, filedata):

tools/trac-keywords.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,9 @@
88
def readdb():
99
cmds = ['sqlite3', TRACDB, 'SELECT id,keywords FROM ticket WHERE status<>"closed";']
1010
with subprocess.Popen(cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
11-
comm = p.communicate()
12-
data = comm[0]
11+
# TODO: handle p.returncode?
12+
stdout, _ = p.communicate()
13+
data = stdout
1314
ret = {}
1415
for line in data.splitlines():
1516
pos1 = line.find('|')

tools/triage_py/triage_version.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,11 @@ def sort_commit_hashes(commits):
3030
git_cmd = 'git rev-list --abbrev-commit --topo-order --no-walk=sorted --reverse ' + ' '.join(commits)
3131
with subprocess.Popen(git_cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=git_repo, universal_newlines=True) as p:
3232
stdout, stderr = p.communicate()
33-
if p.returncode != 0:
34-
print('error: sorting commit hashes failed')
35-
print(stderr)
36-
sys.exit(1)
33+
rc = p.returncode
34+
if rc != 0:
35+
print('error: sorting commit hashes failed')
36+
print(stderr)
37+
sys.exit(1)
3738
return stdout.splitlines()
3839

3940
verbose = args.verbose
@@ -132,6 +133,7 @@ def sort_commit_hashes(commits):
132133
# get version string
133134
version_cmd = exe + ' ' + '--version'
134135
with subprocess.Popen(version_cmd.split(), stdout=subprocess.PIPE, universal_newlines=True) as p:
136+
# TODO: handle p.returncode?
135137
version = p.stdout.read().strip()
136138
# sanitize version
137139
version = version.replace('Cppcheck ', '').replace(' dev', '')
@@ -181,22 +183,23 @@ def sort_commit_hashes(commits):
181183
start = time.time_ns()
182184
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=exe_path, universal_newlines=True)
183185
try:
184-
comm = p.communicate(timeout=args.timeout)
186+
stdout, stderr = p.communicate(timeout=args.timeout)
185187
if args.perf:
186188
end = time.time_ns()
187189
out = ''
188190
if not args.no_stdout:
189-
out += comm[0]
191+
out += stdout
190192
if not args.no_stdout and not args.no_stderr:
191193
out += '\n'
192194
if not args.no_stderr:
193-
out += comm[1]
195+
out += stderr
194196
except subprocess.TimeoutExpired:
195197
out = "timeout"
196198
p.kill()
197-
comm = p.communicate()
199+
p.communicate()
198200

199201
ec = p.returncode
202+
p = None
200203

201204
if not do_compare:
202205
if not use_hashes:

0 commit comments

Comments
 (0)