Skip to contentSkip to conversation

tools, scripts: refactor error-out statements of Python scripts

PATCH New Masahiro Yamada 3 participants 4 messages Aug 7, 2014 – Aug 8, 2014

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 tools, scripts: refactor error-out statements of Python scripts

In Python, sys.exit() function can also take an object other than an integer.

If an integer is given to the argument, Python exits with the return code of it. If a non-integer argument is given, Python output it to stderr and exits with the return code of 1.

That means,

print >> sys.stderr, "Blah Blah"
sys.exit(1)

is equivalent to

sys.exit("Blah Blah")

The latter is a useful shorthand.

Note:
Some error messages in Buildman and Patman were output to stdout. But they should go to stderr. They are also fixed by this commit. This is a nice side effect.

---

 scripts/mailmapper         |  3 +--
 scripts/multiconfig.py     |  7 +------
 tools/buildman/control.py  | 18 ++++++------------
 tools/genboardscfg.py      | 16 +++++-----------
 tools/patman/checkpatch.py |  5 ++---
 tools/patman/patman.py     |  3 +--
 6 files changed, 16 insertions(+), 36 deletions(-)
scripts/mailmapper +1 -2
index dd1ddf6..922ada6 100755
@@ -59,8 +59,7 @@ MIN_COMMITS = 50
 try:
     toplevel = subprocess.check_output(['git', 'rev-parse', '--show-toplevel'])
 except subprocess.CalledProcessError:
-    print >> sys.stderr, 'Please run in a git repository.'
-    sys.exit(1)
+    sys.exit('Please run in a git repository.')
 
 # strip '\n'
 toplevel = toplevel.rstrip()
scripts/multiconfig.py +1 -6
index 749abcb..69a470e 100755
@@ -194,11 +194,6 @@ def rmdirs(*dirs):
                exception.errno != errno.ENOTEMPTY:
                 raise
 
-def error(msg):
-    """Output the given argument to stderr and exit with return code 1."""
-    print >> sys.stderr, msg
-    sys.exit(1)
-
 def run_command(command, callback_on_error=None):
     """Run the given command in a sub-shell (and exit if it fails).
 
@@ -211,7 +206,7 @@ def run_command(command, callback_on_error=None):
     if retcode:
         if callback_on_error:
             callback_on_error()
-        error("'%s' Failed" % command)
+        sys.exit("'%s' Failed" % command)
 
 def run_make_config(cmd, objdir, callback_on_error=None):
     """Run the make command in a sub-shell (and exit if it fails).
tools/buildman/control.py +6 -12
index 75b6498..962f194 100644
@@ -94,20 +94,17 @@ def DoBuildman(options, args):
     if count == -1:
         if not options.branch:
             str = 'Please use -b to specify a branch to build'
-            print col.Color(col.RED, str)
-            sys.exit(1)
+            sys.exit(col.Color(col.RED, str))
         count = gitutil.CountCommitsInBranch(options.git_dir, options.branch)
         if count is None:
             str = "Branch '%s' not found or has no upstream" % options.branch
-            print col.Color(col.RED, str)
-            sys.exit(1)
+            sys.exit(col.Color(col.RED, str))
         count += 1   # Build upstream commit also
 
     if not count:
         str = ("No commits found to process in branch '%s': "
                "set branch's upstream or use -c flag" % options.branch)
-        print col.Color(col.RED, str)
-        sys.exit(1)
+        sys.exit(col.Color(col.RED, str))
 
     # Work out what subset of the boards we are building
     board_file = os.path.join(options.git, 'boards.cfg')
@@ -116,16 +113,14 @@ def DoBuildman(options, args):
         status = subprocess.call([os.path.join(options.git,
                                                'tools/genboardscfg.py')])
         if status != 0:
-            print >> sys.stderr, "Failed to generate boards.cfg"
-            sys.exit(1)
+            sys.exit("Failed to generate boards.cfg")
 
     boards = board.Boards()
     boards.ReadBoards(os.path.join(options.git, 'boards.cfg'))
     why_selected = boards.SelectBoards(args)
     selected = boards.GetSelected()
     if not len(selected):
-        print col.Color(col.RED, 'No matching boards found')
-        sys.exit(1)
+        sys.exit(col.Color(col.RED, 'No matching boards found'))
 
     # Read the metadata from the commits. First look at the upstream commit,
     # then the ones in the branch. We would like to do something like
@@ -158,8 +153,7 @@ def DoBuildman(options, args):
     gnu_make = command.Output(os.path.join(options.git,
                                            'scripts/show-gnu-make')).rstrip()
     if not gnu_make:
-        print >> sys.stderr, 'GNU Make not found'
-        sys.exit(1)
+        sys.exit('GNU Make not found')
 
     # Create a new builder with the selected options
     output_dir = os.path.join(options.output_dir, options.branch)
tools/genboardscfg.py +5 -11
index 734d90b..99e4e87 100755
@@ -77,16 +77,14 @@ def check_top_directory():
     """Exit if we are not at the top of source directory."""
     for f in ('README', 'Licenses'):
         if not os.path.exists(f):
-            print >> sys.stderr, 'Please run at the top of source directory.'
-            sys.exit(1)
+            sys.exit('Please run at the top of source directory.')
 
 def get_make_cmd():
     """Get the command name of GNU Make."""
     process = subprocess.Popen([SHOW_GNU_MAKE], stdout=subprocess.PIPE)
     ret = process.communicate()
     if process.returncode:
-        print >> sys.stderr, 'GNU Make not found'
-        sys.exit(1)
+        sys.exit('GNU Make not found')
     return ret[0].rstrip()
 
 ### classes ###
@@ -209,9 +207,7 @@ class DotConfigParser:
         # sanity check of '.config' file
         for field in self.must_fields:
             if not field in fields:
-                print >> sys.stderr, 'Error: %s is not defined in %s' % \
-                                                            (field, defconfig)
-                sys.exit(1)
+                sys.exit('Error: %s is not defined in %s' % (field, defconfig))
 
         # fix-up for aarch64 and tegra
         if fields['arch'] == 'arm' and 'cpu' in fields:
@@ -455,8 +451,7 @@ def __gen_boards_cfg(jobs):
     # wait until the reformat tool finishes
     reformat_process.communicate()
     if reformat_process.returncode != 0:
-        print >> sys.stderr, '"%s" failed' % REFORMAT_CMD[0]
-        sys.exit(1)
+        sys.exit('"%s" failed' % REFORMAT_CMD[0])
 
 def gen_boards_cfg(jobs):
     """Generate boards.cfg file.
@@ -489,8 +484,7 @@ def main():
         try:
             jobs = int(options.jobs)
         except ValueError:
-            print >> sys.stderr, 'Option -j (--jobs) takes a number'
-            sys.exit(1)
+            sys.exit('Option -j (--jobs) takes a number')
     else:
         try:
             jobs = int(subprocess.Popen(['getconf', '_NPROCESSORS_ONLN'],
tools/patman/checkpatch.py +2 -3
index 0d4e935..34a3bd2 100644
@@ -34,9 +34,8 @@ def FindCheckPatch():
             return fname
         path = os.path.dirname(path)
 
-    print >> sys.stderr, ('Cannot find checkpatch.pl - please put it in your ' +
-                '~/bin directory or use --no-check')
-    sys.exit(1)
+    sys.exit('Cannot find checkpatch.pl - please put it in your ' +
+             '~/bin directory or use --no-check')
 
 def CheckPatch(fname, verbose=False):
     """Run checkpatch.pl on a file.
tools/patman/patman.py +1 -2
index c60aa5a..ba5dc91 100755
@@ -122,8 +122,7 @@ else:
     col = terminal.Color()
     if not options.count:
         str = 'No commits found to process - please use -c flag'
-        print col.Color(col.RED, str)
-        sys.exit(1)
+        sys.exit(col.Color(col.RED, str))
 
     # Read the metadata from the commits
     if options.count:
Signature · 1 line
1.9.1
#1 lore raw

PATCH 1/1 tools, scripts: refactor error-out statements of Python scripts

Hi Masahiro,

Quoted 18 lines · Masahiro Yamada

In Python, sys.exit() function can also take an object other than an integer.

If an integer is given to the argument, Python exits with the return code of it. If a non-integer argument is given, Python output it to stderr and exits with the return code of 1.

That means,

print >> sys.stderr, "Blah Blah"
sys.exit(1)

is equivalent to

sys.exit("Blah Blah")

The latter is a useful shorthand.

Quoted 7 lines

Note:
Some error messages in Buildman and Patman were output to stdout. But they should go to stderr. They are also fixed by this commit. This is a nice side effect.

Haven't you decided to replace python scripts?

Quoted 4 lines

---

 scripts/mailmapper         |  3 +--
 scripts/multiconfig.py     |  7 +------

At least the ones that are used during the build process.

Quoted 5 lines
 tools/buildman/control.py  | 18 ++++++------------
 tools/genboardscfg.py      | 16 +++++-----------
 tools/patman/checkpatch.py |  5 ++---
 tools/patman/patman.py     |  3 +--
 6 files changed, 16 insertions(+), 36 deletions(-)

[...]

Signature · 2 lines
Regards,
Igor.
#2 lore raw

PATCH 1/1 tools, scripts: refactor error-out statements of Python scripts

Hi Igor,

Quoted 26 lines · On Thu, 07 Aug 2014 09:31:48 +0300 Igor Grinberg <[email protected]>…

Hi Masahiro,

Quoted 23 lines · Masahiro Yamada

In Python, sys.exit() function can also take an object other than an integer.

If an integer is given to the argument, Python exits with the return code of it. If a non-integer argument is given, Python output it to stderr and exits with the return code of 1.

That means,

print >> sys.stderr, "Blah Blah"
sys.exit(1)

is equivalent to

sys.exit("Blah Blah")

The latter is a useful shorthand.

Note:
Some error messages in Buildman and Patman were output to stdout. But they should go to stderr. They are also fixed by this commit. This is a nice side effect.

Quoted 5 lines
Quoted 2 lines

Haven't you decided to replace python scripts?

Not yet.

I'd like to know Tom's option.

Quoted 6 lines
Quoted 3 lines
 scripts/mailmapper         |  3 +--
 scripts/multiconfig.py     |  7 +------

At least the ones that are used during the build process.

Anyway, this patch itself has no problem.

Best Regards
Masahiro Yamada

#3 lore raw

PATCH 1/1 tools, scripts: refactor error-out statements of Python scripts

In reply to Masahiro Yamada

Hi Masahiro,

Quoted 19 lines · Masahiro Yamada

In Python, sys.exit() function can also take an object other than an integer.

If an integer is given to the argument, Python exits with the return code of it. If a non-integer argument is given, Python output it to stderr and exits with the return code of 1.

That means,

print >> sys.stderr, "Blah Blah"
sys.exit(1)

is equivalent to

sys.exit("Blah Blah")

The latter is a useful shorthand.

Quoted 7 lines

Note:
Some error messages in Buildman and Patman were output to stdout. But they should go to stderr. They are also fixed by this commit. This is a nice side effect.

I suppose it is OK to pass ANSI strings to this function.

Regards,
Simon