[Autotest][PY3] Migrating client/cros (kernel_trace -> rtc)

Migrating client/cros from kernel_trace.py -> rtc.py to python3.

BUG=chromium:990593
TEST= py_compile in py2 and py3. CQ. dummy_Pass. policy_ and network_
test

Change-Id: I8cd48c1ab6d0d71f6fcf2573fda6a5badda957b9
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/third_party/autotest/+/2488642
Reviewed-by: Seewai Fu <seewaifu@google.com>
Reviewed-by: Greg Edelston <gredelston@google.com>
Commit-Queue: Derek Beckett <dbeckett@chromium.org>
Tested-by: Derek Beckett <dbeckett@chromium.org>
diff --git a/client/cros/kernel_trace.py b/client/cros/kernel_trace.py
index d901e55..264cffc 100644
--- a/client/cros/kernel_trace.py
+++ b/client/cros/kernel_trace.py
@@ -167,7 +167,7 @@
 
         fname = os.path.join(self._TRACE_ROOT, 'buffer_size_kb')
         result = utils.read_one_line(fname).strip()
-        if result is '0':
+        if result == '0':
             return True
         return False
 
diff --git a/client/cros/liststorage.py b/client/cros/liststorage.py
index b528d07..9484b22 100644
--- a/client/cros/liststorage.py
+++ b/client/cros/liststorage.py
@@ -15,7 +15,12 @@
 |get_all()| output is human readable (as oppposite to python's data structures)
 """
 
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
 import logging, os, re
+import six
 
 # this script can be run at command line on DUT (ie /usr/local/autotest
 # contains only the client/ subtree), on a normal autotest
@@ -24,6 +29,8 @@
 
 from autotest_lib.client.common_lib import error
 from autotest_lib.client.common_lib import utils
+from autotest_lib.client.common_lib import seven
+
 
 INFO_PATH = "/sys/block"
 UDEV_CMD_FOR_SERIAL_NUMBER = "udevadm info -a -n %s | grep -iE 'ATTRS{" \
@@ -238,7 +245,7 @@
                     # Here an octal unicode '\040' is added to the path
                     # replacing ' ' (space).
                     # Following '.decode('unicode-escape')' handles the same
-                    dev['mountpoint'] = mount.decode('unicode-escape')
+                    dev['mountpoint'] = seven.ensure_text(mount, 'unicode-escape')
                     dev['is_removable'] = is_removable
                     dev['usb_type'], dev['serial'] = \
                             get_usbdevice_type_and_serial(dev['device'],
@@ -345,9 +352,9 @@
 
 def main():
     for device in get_all():
-        print ("%(device)s %(bus)s %(model)s %(size)d %(fs_uuid)s %(fstype)s "
-               "%(is_mounted)d %(mountpoint)s %(usb_type)s %(serial)s" %
-               device)
+        print("%(device)s %(bus)s %(model)s %(size)d %(fs_uuid)s %(fstype)s "
+              "%(is_mounted)d %(mountpoint)s %(usb_type)s %(serial)s" %
+              device)
 
 
 if __name__ == "__main__":
diff --git a/client/cros/login.py b/client/cros/login.py
index 9637c5d..36aaaee 100644
--- a/client/cros/login.py
+++ b/client/cros/login.py
@@ -1,12 +1,16 @@
+# Lint as: python2, python3
 # Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 import logging, os
 
-import constants, cros_logging, cros_ui, cryptohome
 from autotest_lib.client.bin import utils
 from autotest_lib.client.common_lib import error
+from autotest_lib.client.cros import constants
+from autotest_lib.client.cros import cros_logging
+from autotest_lib.client.cros import cros_ui
+from autotest_lib.client.cros import cryptohome
 
 
 class CrashError(error.TestError):
@@ -59,7 +63,7 @@
             condition,
             utils.TimeoutError(timeout_msg),
             timeout=timeout)
-    except utils.TimeoutError, e:
+    except utils.TimeoutError as e:
         # We could fail faster if necessary, but it'd be more complicated.
         if process_crashed(process, log_reader):
             logging.error(crash_msg)
@@ -101,7 +105,7 @@
           process=constants.BROWSER,
           crash_msg=crash_msg)
       return True
-    except utils.TimeoutError, e:
+    except utils.TimeoutError as e:
       return False
 
 
diff --git a/client/cros/mainloop.py b/client/cros/mainloop.py
index d93f94a..091b564 100644
--- a/client/cros/mainloop.py
+++ b/client/cros/mainloop.py
@@ -1,3 +1,4 @@
+# Lint as: python2, python3
 # Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
@@ -5,6 +6,7 @@
 import gobject, logging, sys, traceback
 
 import common
+
 from autotest_lib.client.common_lib import error
 
 # TODO(rochberg): Take another shot at fixing glib to allow this
@@ -20,7 +22,7 @@
   def wrapper(self, *args, **kwargs):
     try:
       return func(self, *args, **kwargs)
-    except Exception, e:
+    except Exception as e:
       logging.warning('Saving exception: %s' % e)
       logging.warning(''.join(traceback.format_exception(*sys.exc_info())))
       self._forwarded_exception = e
diff --git a/client/cros/network.py b/client/cros/network.py
index 83a5d6e..33c6481 100644
--- a/client/cros/network.py
+++ b/client/cros/network.py
@@ -1,12 +1,13 @@
+# Lint as: python2, python3
 # Copyright (c) 2019 The Chromium OS Authors. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 import logging
 import re
+from six.moves import urllib
 import socket
 import time
-import urllib2
 
 import common
 
@@ -95,7 +96,7 @@
     url = url_pattern % bytes_to_fetch
     logging.info('FetchUrl %s', url)
     start_time = time.time()
-    result = urllib2.urlopen(url, timeout=fetch_timeout)
+    result = urllib.request.urlopen(url, timeout=fetch_timeout)
     bytes_fetched = 0
     while bytes_fetched < bytes_to_fetch:
         bytes_left = bytes_to_fetch - bytes_fetched
diff --git a/client/cros/network_chroot.py b/client/cros/network_chroot.py
index d3c6da2..045e2e4 100644
--- a/client/cros/network_chroot.py
+++ b/client/cros/network_chroot.py
@@ -1,10 +1,16 @@
+# Lint as: python2, python3
 # Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
 import errno
 import os
 import shutil
+import six
 import time
 
 from autotest_lib.client.bin import utils
@@ -208,7 +214,7 @@
         try:
             with open(chroot_pid_file) as f:
                 return int(f.read())
-        except IOError, e:
+        except IOError as e:
             if not missing_ok or e.errno != errno.ENOENT:
                 raise e
 
@@ -290,6 +296,6 @@
 
     def write_configs(self):
         """Write out config files"""
-        for config_file, template in self._config_file_templates.iteritems():
+        for config_file, template in six.iteritems(self._config_file_templates):
             with open(self.chroot_path(config_file), 'w') as f:
                 f.write(template % self._config_file_values)
diff --git a/client/cros/p2p_utils.py b/client/cros/p2p_utils.py
index 0a751b1..dee00c9 100644
--- a/client/cros/p2p_utils.py
+++ b/client/cros/p2p_utils.py
@@ -1,3 +1,4 @@
+# Lint as: python2, python3
 # Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
@@ -31,8 +32,8 @@
             shutil.rmtree(backup_path)
         if os.path.exists(P2P_SHARE_PATH):
             os.rename(P2P_SHARE_PATH, backup_path)
-    except OSError, e:
-        raise error.TestError("Error on P2P files backup: %s" % (e.message))
+    except OSError as e:
+        raise error.TestError("Error on P2P files backup: %s" % (str(e)))
 
 
 def p2p_restore_files(backup_path=P2P_SHARE_BACKUP_PATH):
diff --git a/client/cros/pkcs11.py b/client/cros/pkcs11.py
index d385512..9b229cb 100644
--- a/client/cros/pkcs11.py
+++ b/client/cros/pkcs11.py
@@ -1,9 +1,14 @@
+# Lint as: python2, python3
 # Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
 """Utility functions used for PKCS#11 library testing."""
 
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
 import grp, logging, os, pwd, re, stat, sys, shutil, pwd, grp
 
 from autotest_lib.client.bin import utils
@@ -11,7 +16,7 @@
 
 USER_TOKEN_PREFIX = 'User TPM Token '
 TMP_CHAPS_DIR = '/tmp/chaps'
-CHAPS_DIR_PERM = 0750
+CHAPS_DIR_PERM = 0o750
 SYSTEM_TOKEN_NAME = 'System TPM Token'
 SYSTEM_TOKEN_DIR = '/var/lib/chaps'
 INVALID_SLOT_ID = '100'
@@ -197,14 +202,14 @@
     output = __run_cmd('p11_replay --generate --replay_wifi',
                        ignore_status=True)
     if not re.search('Sign: CKR_OK', output):
-        print >> sys.stderr, output
+        print(output, file=sys.stderr)
         return False
     unload_p11_test_token()
     load_p11_test_token()
     output = __run_cmd('p11_replay --replay_wifi --cleanup',
                        ignore_status=True)
     if not re.search('Sign: CKR_OK', output):
-        print >> sys.stderr, output
+        print(output, file=sys.stderr)
         return False
     return True
 
diff --git a/client/cros/radvd_server.py b/client/cros/radvd_server.py
index f0a9ff5..a0704d8 100644
--- a/client/cros/radvd_server.py
+++ b/client/cros/radvd_server.py
@@ -1,3 +1,4 @@
+# Lint as: python2, python3
 # Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
@@ -113,7 +114,8 @@
         associated process.
         """
         if os.path.exists(RADVD_PID_FILE):
-            pid = int(file(RADVD_PID_FILE).read())
+            with open(RADVD_PID_FILE, 'r') as rf:
+                pid = int(rf.read())
             os.remove(RADVD_PID_FILE)
             try:
                 os.kill(pid, signal.SIGTERM)
diff --git a/client/cros/rtc.py b/client/cros/rtc.py
index 505fd71..067eeea 100644
--- a/client/cros/rtc.py
+++ b/client/cros/rtc.py
@@ -1,3 +1,4 @@
+# Lint as: python2, python3
 # Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
 # Use of this source code is governed by a BSD-style license that can
 # be # found in the LICENSE file.
@@ -21,16 +22,17 @@
     """
     Read the current time out of the RTC
     """
-    return int(file('/sys/class/rtc/%s/since_epoch' % rtc_device).readline())
+    with open('/sys/class/rtc/%s/since_epoch' % rtc_device) as rf:
+        seconds = rf.readline()
+    return int(seconds)
 
 
 def write_wake_alarm(alarm_time, rtc_device='rtc0'):
     """
     Write a value to the wake alarm
     """
-    f = file('/sys/class/rtc/%s/wakealarm' % rtc_device, 'w')
-    f.write('%s\n' % str(alarm_time))
-    f.close()
+    with open('/sys/class/rtc/%s/wakealarm' % rtc_device, 'w') as f:
+        f.write('%s\n' % str(alarm_time))
 
 
 def set_wake_alarm(alarm_time, rtc_device='rtc0'):
@@ -39,7 +41,8 @@
     """
     try:
         write_wake_alarm(alarm_time, rtc_device)
-    except IOError as (errnum, strerror):
+    except IOError as errs:
+        (errnum, strerror) = errs.args
         if errnum != errno.EBUSY:
             raise
         write_wake_alarm('0', rtc_device)