remove use of very old file() function that is no longer available
authorparmentelat <thierry.parmentelat@inria.fr>
Wed, 12 Dec 2018 18:01:31 +0000 (19:01 +0100)
committerparmentelat <thierry.parmentelat@inria.fr>
Wed, 12 Dec 2018 18:01:37 +0000 (19:01 +0100)
PLC/Methods/GetBootMedium.py
PLC/Shell.py
db-config.d/002-system_site
migrations/extract-views.py
plcsh

index 289fdf4..1e58b98 100644 (file)
@@ -1,3 +1,5 @@
+# pylint: disable=c0111, c0103
+
 import random
 import base64
 import os
@@ -16,7 +18,7 @@ from PLC.NodeTags import NodeTag, NodeTags
 
 from PLC.Logger import logger
 
-from PLC.Accessors.Accessors_standard import *                  # import node accessors
+from PLC.Accessors.Accessors_standard import *              # node accessors
 
 # could not define this in the class..
 # create a dict with the allowed actions for each type of node
@@ -287,7 +289,8 @@ class GetBootMedium(Method):
 
     def bootcd_version (self):
         try:
-            return file(self.BOOTCDDIR + "/build/version.txt").readline().strip()
+            with open(self.BOOTCDDIR + "/build/version.txt") as feed:
+                return feed.readline().strip()
         except:
             raise Exception("Unknown boot cd version - probably wrong bootcd dir : {}"\
                             .format(self.BOOTCDDIR))
@@ -364,7 +367,7 @@ class GetBootMedium(Method):
         if node_type not in [ 'regular', 'reservable' ]:
             logger.error("GetBootMedium.build_command: unexpected node_type {}".format(node_type))
             return command, None
-        
+
         build_sh_options=""
         if "cramfs" in build_sh_spec:
             type += "_cramfs"
@@ -389,7 +392,7 @@ class GetBootMedium(Method):
                           type,
                           build_sh_options,
                           log_file)
-        
+
         logger.info("The build command line is {}".format(command))
 
         return command, log_file
@@ -520,7 +523,8 @@ class GetBootMedium(Method):
                                               .format(generic_path, filename))
             else:
                 ### return the generic medium content as-is, just base64 encoded
-                return base64.b64encode(file(generic_path).read())
+                with open(generic_path) as feed:
+                    return base64.b64encode(feed.read())
 
         ### config file preview or regenerated
         if action == 'node-preview' or action == 'node-floppy':
@@ -528,7 +532,8 @@ class GetBootMedium(Method):
             floppy = self.floppy_contents (node,renew_key)
             if filename:
                 try:
-                    file(filename,'w').write(floppy)
+                    with open(filename, 'w') as writer:
+                        writer.write(floppy)
                 except:
                     raise PLCPermissionDenied("Could not write into {}".format(filename))
                 return filename
@@ -564,7 +569,8 @@ class GetBootMedium(Method):
                 # store it
                 floppy_file = "{}/{}.txt".format(self.WORKDIR, nodename)
                 try:
-                    file(floppy_file,"w").write(floppy_text)
+                    with open(floppy_file, "w") as writer:
+                        writer.write(floppy_text)
                 except:
                     raise PLCPermissionDenied("Could not write into {}".format(floppy_file))
 
@@ -583,7 +589,7 @@ class GetBootMedium(Method):
                     raise PLCAPIError("{} failed Command line was: {} See logs in {}"\
                                       .format(self.BOOTCDBUILD, command, log_file))
 
-                if not os.path.isfile (node_image):
+                if not os.path.isfile(node_image):
                     raise PLCAPIError("Unexpected location of build.sh output - {}".format(node_image))
 
                 # handle result
@@ -597,7 +603,8 @@ class GetBootMedium(Method):
                     self.cleantrash()
                     return filename
                 else:
-                    result = file(node_image).read()
+                    with open(node_image) as feed:
+                        result = feed.read()
                     self.trash.append(node_image)
                     self.cleantrash()
                     logger.info("GetBootMedium - done with build.sh")
index 4118401..25bb0d5 100644 (file)
@@ -146,7 +146,8 @@ class Shell:
                 raise Exception("Must specify session")
 
             if os.path.exists(session):
-                session = file(session).read()
+                with open(session) as feed:
+                    session = feed.read()
 
             self.auth = {'AuthMethod': "session", 'session': session}
         else:
index 4a60581..1564694 100644 (file)
@@ -1,5 +1,5 @@
 # -*-python-*-
-#################### 
+####################
 # Create/update and populate the default site (should be site_id 1)
 
 ### plc_www holds the contents of the PLC_WWW configuration category
@@ -47,9 +47,8 @@ keyfile=plc['root_ssh_key_pub']
 person = GetPersons(the_admin_id)[0]
 keys = GetKeys(person['key_ids'])
 if os.path.exists(keyfile):
-    sshkeyfp = file(keyfile,"r")
-    sshkey = sshkeyfp.read()
-    sshkeyfp.close()
+    with open(keyfile) as feed:
+        sshkey = feed.read()
 
     found=False
     for key in keys:
index 8add67c..9424644 100755 (executable)
@@ -10,48 +10,49 @@ class Schema:
         self.output=output
 
     # left part is non-greedy
-    comment=re.compile("(.*?)--.*")
-    spaces=re.compile("^\s+(\S.*)")
-    view=re.compile("(?i)\s*create\s+(or\s+replace)?\s+view.*")
+    comment = re.compile("(.*?)--.*")
+    spaces = re.compile("^\s+(\S.*)")
+    view = re.compile("(?i)\s*create\s+(or\s+replace)?\s+view.*")
 
     def parse (self):
         if self.output:
             outfile = open(self.output, "a")
         else:
             outfile = sys.stdout
-        contents = file(self.input).read()
-        parts=contents.split(";")
+        with open(self.input) as feed:
+            contents = feed.read()
+        parts = contents.split(";")
         for part in parts:
             # normalize: remove comments, linebreaks, trailing spaces..
             normalized=''
             lines=part.split('\n');
-            out_lines=[]
+            out_lines = []
             for line in lines:
                 # remove comment
-                match=Schema.comment.match(line)
+                match = Schema.comment.match(line)
                 if match:
-                    line=match.group(1)
+                    line = match.group(1)
                 out_lines.append(line)
             # get them together
             out_line = " ".join(out_lines)
             # remove trailing spaces
-            match=Schema.spaces.match(out_line)
+            match = Schema.spaces.match(out_line)
             if match:
-                out_line=match.group(1)
-            match=Schema.view.match(out_line)
+                out_line = match.group(1)
+            match = Schema.view.match(out_line)
             if match:
                 outfile.write("{};\n".format(out_line))
         if outfile != sys.stdout:
             outfile.close()
 
 if __name__ == '__main__':
-    if len(sys.argv) not in [2,3]:
-        print('Usage:',sys.argv[0],'input [output]')
+    if len(sys.argv) not in [2, 3]:
+        print('Usage:', sys.argv[0], 'input [output]')
         sys.exit(1)
-    input=sys.argv[1]
+    input = sys.argv[1]
     try:
-        output=sys.argv[2]
+        output = sys.argv[2]
     except:
-        output=None
-    Schema(input,output).parse()
+        output = None
+    Schema(input, output).parse()
 
diff --git a/plcsh b/plcsh
index ef434ac..4387372 100755 (executable)
--- a/plcsh
+++ b/plcsh
@@ -40,7 +40,7 @@ parser.add_option("--help", action = "store_true", dest="help", default=False,
 
 if not args and options.help:
     parser.print_help()
-    sys.exit(1)    
+    sys.exit(1)
 
 # If user is specified but password is not
 if options.user is not None and options.password is None:
@@ -69,7 +69,7 @@ except Exception as err:
     parser.print_help()
     sys.exit(1)
 
-# If called by a script 
+# If called by a script
 if args:
     if not os.path.exists(args[0]):
         print('File %s not found'%args[0])
@@ -82,7 +82,7 @@ if args:
         # use args as sys.argv for the next shell, so our own options get removed for the next script
         sys.argv = args
         script = sys.argv[0]
-        # Add of script to sys.path 
+        # Add of script to sys.path
         path = os.path.dirname(os.path.abspath(script))
         sys.path.append(path)
         exec(compile(open(script).read(), script, 'exec'))
@@ -114,7 +114,9 @@ else:
     # Load command history
     history_path = os.path.join(os.environ["HOME"], ".plcapi_history")
     try:
-        file(history_path, 'a').close()
+        # check directory: pretend to open
+        with open(history_path, 'a') as check:
+            pass
         readline.read_history_file(history_path)
         atexit.register(readline.write_history_file, history_path)
     except IOError: