Skip to contentSkip to conversation

subprocess: cleanup subprocess calls

PATCH Superseded Stephano Cetola 3 participants 7 messages Sep 29, 2016 – Sep 30, 2016

v1 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#0 lore raw

cover subprocess: cleanup subprocess calls

This is the beginning of an effort to move toward a unified way of using the subprocess module. The end goal is somday create a fork of the subprocess.run command intro'd in python 3.5.

The biggest hurdle in these efforts is in testing some of the more obscure code paths that are touched when changing these subprocess calls. With more time, many of the Popen calls that still exist could be moved to either check_output or sub.run.

Stephano Cetola (3):
subprocess: remove strings and migrate to direct arrays utils.py: gut python 2 commands in favor of subprocess.run
subprocess: remove Popen in favor of check_output

 meta/classes/buildstats.bbclass |  6 ++++-
 meta/classes/spdx.bbclass       | 11 ++++----
 meta/lib/oe/distro_check.py     |  2 +-
 meta/lib/oe/package.py          | 13 ++++-----
 meta/lib/oe/package_manager.py  | 59 ++++++++++++++++++++---------------------
 meta/lib/oe/utils.py            | 11 +++-----
 6 files changed, 51 insertions(+), 51 deletions(-)
Signature · 1 line
2.10.0
#1 lore raw

PATCH 1/3 subprocess: remove strings and migrate to direct arrays

When using subprocess call and check_output, it is better to use arrays rather than strings when possible to avoid whitespace and quoting problems.

[ YOCTO #9342 ]

---
 meta/lib/oe/distro_check.py    |  2 +-
 meta/lib/oe/package.py         | 13 +++++-----
 meta/lib/oe/package_manager.py | 59 +++++++++++++++++++++---------------------
 3 files changed, 37 insertions(+), 37 deletions(-)
meta/lib/oe/distro_check.py +1 -1
index 87c52fa..cc973c2 100644
@@ -359,7 +359,7 @@ def create_log_file(d, logname):
             slogfile = os.path.join(logpath, logname)
             if os.path.exists(slogfile):
                     os.remove(slogfile)
-            subprocess.call("touch %s" % logfile, shell=True)
+            subprocess.call(["touch", logfile])
             os.symlink(logfile, slogfile)
             d.setVar('LOG_FILE', logfile)
     return logfile
meta/lib/oe/package.py +7 -6
index 02642f2..ae60a58 100644
@@ -18,23 +18,24 @@ def runstrip(arg):
         newmode = origmode | stat.S_IWRITE | stat.S_IREAD
         os.chmod(file, newmode)
 
-    extraflags = ""
+    stripcmd = [strip]
 
     # kernel module    
     if elftype & 16:
-        extraflags = "--strip-debug --remove-section=.comment --remove-section=.note --preserve-dates"
+        stripcmd.extend(["--strip-debug", "--remove-section=.comment",
+            "--remove-section=.note", "--preserve-dates"])
     # .so and shared library
     elif ".so" in file and elftype & 8:
-        extraflags = "--remove-section=.comment --remove-section=.note --strip-unneeded"
+        stripcmd.extend(["--remove-section=.comment", "--remove-section=.note", "--strip-unneeded"])
     # shared or executable:
     elif elftype & 8 or elftype & 4:
-        extraflags = "--remove-section=.comment --remove-section=.note"
+        stripcmd.extend(["--remove-section=.comment", "--remove-section=.note"])
 
-    stripcmd = "'%s' %s '%s'" % (strip, extraflags, file)
+    stripcmd.append(file)
     bb.debug(1, "runstrip: %s" % stripcmd)
 
     try:
-        output = subprocess.check_output(stripcmd, stderr=subprocess.STDOUT, shell=True)
+        output = subprocess.check_output(stripcmd, stderr=subprocess.STDOUT)
     except subprocess.CalledProcessError as e:
         bb.error("runstrip: '%s' strip command failed with %s (%s)" % (stripcmd, e.returncode, e.output))
 
meta/lib/oe/package_manager.py +29 -30

124 lines not on this page · raw message

Signature · 1 line
2.10.0
#2 lore raw

Re: [PATCH 1/3] subprocess: remove strings and migrate to direct arrays

Quoted 5 lines · Stephano Cetola
meta/lib/oe/package_manager.py +1 -2
-        cmd = "%s %s query --output %s" %  \
-              (self.smart_cmd, self.smart_opt, available_manifest)
+        cmd = [self.smart_cmd, self.smart_opt, 'query', '--output',

available_manifest]

self.smart_opt is a string containing many options, so this needs to be transformed to a list of options and embedded correctly.

Ross

#3 lore raw

PATCH 2/3 utils.py: gut python 2 commands in favor of subprocess.run

In reply to Stephano Cetola

getstatusoutput is a wrapper around subprocess.getstatusouput() in Py3, which is basically deprecated and behaves almost entirely unlike run().

[ YOCTO #9342 ]

---
 meta/lib/oe/utils.py | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)
meta/lib/oe/utils.py +4 -7
index d6545b1..265f733 100644
@@ -1,9 +1,4 @@
-try:
-    # Python 2
-    import commands as cmdstatus
-except ImportError:
-    # Python 3
-    import subprocess as cmdstatus
+import subprocess
 
 def read_file(filename):
     try:
@@ -144,7 +139,9 @@ def packages_filter_out_system(d):
     return pkgs
 
 def getstatusoutput(cmd):
-    return cmdstatus.getstatusoutput(cmd)
+    compproc = subprocess.run(cmd, stdout=subprocess.PIPE,
+            universal_newlines=True, stderr=subprocess.STDOUT, shell=True)
+    return (compproc.returncode, compproc.stdout)
 
 
 def trim_version(version, num_parts=2):
Signature · 1 line
2.10.0
#4 lore raw

Re: [PATCH 2/3] utils.py: gut python 2 commands in favor of subprocess.run

Quoted 27 lines · Stephano Cetola

getstatusoutput is a wrapper around subprocess.getstatusouput() in Py3, which is basically deprecated and behaves almost entirely unlike run().

[ YOCTO #9342 ]

---
 meta/lib/oe/utils.py | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)
meta/lib/oe/utils.py +1 -6
index d6545b1..265f733 100644
@@ -1,9 +1,4 @@
-try:
-    # Python 2
-    import commands as cmdstatus
-except ImportError:
-    # Python 3
-    import subprocess as cmdstatus
+import subprocess
 
 def read_file(filename):
     try:

meta/lib/oe/utils.py def packages_filter_out_system(d): · line 145

Quoted 8 lines
meta/lib/oe/utils.py +3 -1
@@ -144,7 +139,9 @@ def packages_filter_out_system(d):
     return pkgs
 
 def getstatusoutput(cmd):
-    return cmdstatus.getstatusoutput(cmd)
+    compproc = subprocess.run(cmd, stdout=subprocess.PIPE,
+            universal_newlines=True, stderr=subprocess.STDOUT, shell=True)
+    return (compproc.returncode, compproc.stdout)
 

This is wrong, we can’t use subprocess.run until we bump our minimum python version. We only require 3.4, not 3.5.

Signature · 5 lines
Christopher Larson
clarson at kergoth dot com
Founder - BitBake, OpenEmbedded, OpenZaurus
Maintainer - Tslib
Senior Software Engineer, Mentor Graphics
#5 lore raw

Re: [PATCH 2/3] utils.py: gut python 2 commands in favor of subprocess.run

Quoted 32 lines · Christopher Larson
Quoted 29 lines · Stephano Cetola

getstatusoutput is a wrapper around subprocess.getstatusouput() in Py3, which is basically deprecated and behaves almost entirely unlike run().

[ YOCTO #9342 ]

---
 meta/lib/oe/utils.py | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)
meta/lib/oe/utils.py +1 -6
index d6545b1..265f733 100644
@@ -1,9 +1,4 @@
-try:
-    # Python 2
-    import commands as cmdstatus
-except ImportError:
-    # Python 3
-    import subprocess as cmdstatus
+import subprocess
 
 def read_file(filename):
     try:
@@ -144,7 +139,9 @@ def packages_filter_out_system(d):
     return pkgs
 
Quoted 9 lines

meta/lib/oe/utils.py def packages_filter_out_system(d): · line 145

Quoted 6 lines
meta/lib/oe/utils.py +3 -1
 def getstatusoutput(cmd):
-    return cmdstatus.getstatusoutput(cmd)
+    compproc = subprocess.run(cmd, stdout=subprocess.PIPE,
+            universal_newlines=True, stderr=subprocess.STDOUT, shell=True)
+    return (compproc.returncode, compproc.stdout)
 

This is wrong, we can’t use subprocess.run until we bump our minimum python version. We only require 3.4, not 3.5.

Removed this and resubmitted.

--stephano

Quoted 6 lines
Signature · 5 lines
Christopher Larson
clarson at kergoth dot com
Founder - BitBake, OpenEmbedded, OpenZaurus
Maintainer - Tslib
Senior Software Engineer, Mentor Graphics
#6 lore raw

PATCH 3/3 subprocess: remove Popen in favor of check_output

In reply to Stephano Cetola

This begins moving away from the deprecated subprocess calls in an effort to eventually move to some more global abstraction using the run convenience method provided in python 3.5.

[ YOCTO #9342 ]

---
 meta/classes/buildstats.bbclass |  6 +++++-
 meta/classes/spdx.bbclass       | 11 +++++------
 2 files changed, 10 insertions(+), 7 deletions(-)
meta/classes/buildstats.bbclass +5 -1
index 34ecb03..8c2b7b3 100644
@@ -163,7 +163,11 @@ python run_buildstats () {
             bs = os.path.join(bsdir, "build_stats")
             with open(bs, "a") as f:
                 rootfs = d.getVar('IMAGE_ROOTFS', True)
-                rootfs_size = subprocess.Popen(["du", "-sh", rootfs], stdout=subprocess.PIPE).stdout.read()
+                try:
+                    rootfs_size = subprocess.check_output(["du", "-sh", rootfs],
+                            stderr=subprocess.STDOUT).decode('utf-8')
+                except subprocess.CalledProcessError as e:
+                    bb.error("Failed to get rootfs size: %s" % e.output)
                 f.write("Uncompressed Rootfs size: %s" % rootfs_size)
 
     elif isinstance(e, bb.build.TaskFailed):
meta/classes/spdx.bbclass +5 -6
index 0c92765..89394d3 100644
@@ -219,14 +219,13 @@ def hash_string(data):
 def run_fossology(foss_command, full_spdx):
     import string, re
     import subprocess
-    
-    p = subprocess.Popen(foss_command.split(),
-        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
-    foss_output, foss_error = p.communicate()
-    if p.returncode != 0:
+
+    try:
+        foss_output = subprocess.check_output(foss_command.split(),
+                stderr=subprocess.STDOUT).decode('utf-8')
+    except subprocess.CalledProcessError as e:
         return None
 
-    foss_output = unicode(foss_output, "utf-8")
     foss_output = string.replace(foss_output, '\r', '')
 
     # Package info
Signature · 1 line
2.10.0