Improve Python 3 support in policycoreutils
Hello,
These patches try to add Python 3 support to the following places under policycoreutils/:
audit2allow/
sandbox/scripts/
semanage/ (except seobject.py)
Patch for the seobject.py should follow later.
Thanks
Michal
PATCH 1/4 policycoreutils/audit2allow: improve compatibility with Python 3
- replace print statement with print function
- use reserved word as in try-except
- replace deprecated assert_() method with assertTrue() in unit tests
--- policycoreutils/audit2allow/audit2allow | 66 ++++++++++++------------- policycoreutils/audit2allow/audit2why | 64 ++++++++++++------------ policycoreutils/audit2allow/sepolgen-ifgen | 12 ++--- policycoreutils/audit2allow/test_audit2allow.py | 8 +-- 4 files changed, 75 insertions(+), 75 deletions(-)
policycoreutils/audit2allow/audit2allow +33 -33
@@ -135,13 +135,13 @@ class AuditToPolicy: elif self.__options.audit: try: messages = audit.get_audit_msgs() - except OSError, e: + except OSError as e: sys.stderr.write('could not run ausearch - "%s"\n' % str(e)) sys.exit(1) elif self.__options.boot: try: messages = audit.get_audit_boot_msgs() - except OSError, e: + except OSError as e: sys.stderr.write('could not run ausearch - "%s"\n' % str(e)) sys.exit(1) else:
@@ -152,7 +152,7 @@ class AuditToPolicy: if filename is not None: try: f = open(filename) - except IOError, e: + except IOError as e: sys.stderr.write('could not open file %s - "%s"\n' % (filename, str(e))) sys.exit(1)
@@ -214,7 +214,7 @@ class AuditToPolicy: try: fd = open(filename, "w") - except IOError, e: + except IOError as e: sys.stderr.write("could not write output file: %s\n" % str(e)) sys.exit(1)
@@ -225,8 +225,8 @@ class AuditToPolicy: try: mc.create_module_package(filename, self.__options.refpolicy) - except RuntimeError, e: - print e + except RuntimeError as e: + print(e) sys.exit(1) sys.stdout.write(_("******************** IMPORTANT ***********************\n"))
@@ -240,44 +240,44 @@ class AuditToPolicy: rc = i.type data = i.data if rc >= 0: - print "%s\n\tWas caused by:" % i.message + print("%s\n\tWas caused by:" % i.message) if rc == audit2why.ALLOW: - print "\t\tUnknown - would be allowed by active policy\n", - print "\t\tPossible mismatch between this policy and the one under which the audit message was generated.\n" - print "\t\tPossible mismatch between current in-memory boolean settings vs. permanent ones.\n" + print("\t\tUnknown - would be allowed by active policy") + print("\t\tPossible mismatch between this policy and the one under which the audit message was generated.\n") + print("\t\tPossible mismatch between current in-memory boolean settings vs. permanent ones.\n") continue if rc == audit2why.DONTAUDIT: - print "\t\tUnknown - should be dontaudit'd by active policy\n", - print "\t\tPossible mismatch between this policy and the one under which the audit message was generated.\n" - print "\t\tPossible mismatch between current in-memory boolean settings vs. permanent ones.\n" + print("\t\tUnknown - should be dontaudit'd by active policy") + print("\t\tPossible mismatch between this policy and the one under which the audit message was generated.\n") + print("\t\tPossible mismatch between current in-memory boolean settings vs. permanent ones.\n") continue if rc == audit2why.BOOLEAN: if len(data) > 1: - print "\tOne of the following booleans was set incorrectly." + print("\tOne of the following booleans was set incorrectly.") for b in data: - print "\tDescription:\n\t%s\n" % seobject.boolean_desc(b[0]) - print "\tAllow access by executing:\n\t# setsebool -P %s %d" % (b[0], b[1]) + print("\tDescription:\n\t%s\n" % seobject.boolean_desc(b[0])) + print("\tAllow access by executing:\n\t# setsebool -P %s %d" % (b[0], b[1])) else: - print "\tThe boolean %s was set incorrectly. " % (data[0][0]) - print "\tDescription:\n\t%s\n" % seobject.boolean_desc(data[0][0]) - print "\tAllow access by executing:\n\t# setsebool -P %s %d" % (data[0][0], data[0][1]) + print("\tThe boolean %s was set incorrectly. " % (data[0][0])) + print("\tDescription:\n\t%s\n" % seobject.boolean_desc(data[0][0])) + print("\tAllow access by executing:\n\t# setsebool -P %s %d" % (data[0][0], data[0][1])) continue if rc == audit2why.TERULE: - print "\t\tMissing type enforcement (TE) allow rule.\n" - print "\t\tYou can use audit2allow to generate a loadable module to allow this access.\n" + print("\t\tMissing type enforcement (TE) allow rule.\n") + print("\t\tYou can use audit2allow to generate a loadable module to allow this access.\n") continue if rc == audit2why.CONSTRAINT: - print #!!!! This avc is a constraint violation. You would need to modify the attributes of either the source or target types to allow this access.\n" - print "#Constraint rule:" - print "\n\t" + data[0] + print() #!!!! This avc is a constraint violation. You would need to modify the attributes of either the source or target types to allow this access.\n" + print("#Constraint rule:") + print("\n\t" + data[0]) for reason in data[1:]: - print "#\tPossible cause is the source %s and target %s are different.\n" % reason + print("#\tPossible cause is the source %s and target %s are different.\n" % reason) if rc == audit2why.RBAC: - print "\t\tMissing role allow rule.\n" - print "\t\tAdd an allow rule for the role pair.\n" + print("\t\tMissing role allow rule.\n") + print("\t\tAdd an allow rule for the role pair.\n") continue audit2why.finish()
@@ -288,8 +288,8 @@ class AuditToPolicy: if self.__options.audit2why: try: return self.__output_audit2why() - except RuntimeError, e: - print e + except RuntimeError as e: + print(e) sys.exit(1) g = policygen.PolicyGenerator()
@@ -348,11 +348,11 @@ class AuditToPolicy: self.__output() except KeyboardInterrupt: sys.exit(0) - except ValueError, e: - print e + except ValueError as e: + print(e) sys.exit(1) - except IOError, e: - print e + except IOError as e: + print(e) sys.exit(1) if __name__ == "__main__":
policycoreutils/audit2allow/audit2why +32 -32
129 lines not on this page · raw message
policycoreutils/audit2allow/sepolgen-ifgen +6 -6
@@ -82,7 +82,7 @@ def get_attrs(policy_path): sys.stderr.write("No installed policy to check\n") return None outfile = tempfile.NamedTemporaryFile() - except IOError, e: + except IOError as e: sys.stderr.write("could not open attribute output file\n") return None except OSError:
@@ -100,7 +100,7 @@ def get_attrs(policy_path): try: attrs.from_file(outfile) except: - print "error parsing attribute info" + print("error parsing attribute info") return None return attrs
@@ -111,7 +111,7 @@ def main(): # Open the output first to generate errors before parsing try: f = open(options.output, "w") - except IOError, e: + except IOError as e: sys.stderr.write("could not open output file [%s]\n" % options.output) return 1
@@ -130,9 +130,9 @@ def main(): # Parse the headers try: headers = refparser.parse_headers(options.headers, output=log, debug=options.debug) - except ValueError, e: - print "error parsing headers" - print str(e) + except ValueError as e: + print("error parsing headers") + print(str(e)) return 1 if_set = interfaces.InterfaceSet(output=log)
policycoreutils/audit2allow/test_audit2allow.py +4 -4
@@ -4,18 +4,18 @@ from subprocess import Popen, PIPE class Audit2allowTests(unittest.TestCase): def assertDenied(self, err): - self.assert_('Permission denied' in err, + self.assertTrue('Permission denied' in err, '"Permission denied" not found in %r' % err) def assertNotFound(self, err): - self.assert_('not found' in err, + self.assertTrue('not found' in err, '"not found" not found in %r' % err) def assertFailure(self, status): - self.assert_(status != 0, + self.assertTrue(status != 0, '"Succeeded when it should have failed') def assertSuccess(self, cmd, status, err): - self.assert_(status == 0, + self.assertTrue(status == 0, '"%s should have succeeded for this test %r' % (cmd, err)) def test_sepolgen_ifgen(self):
Signature · 1 line
2.4.3
PATCH 2/4 policycoreutils/sandbox: improve compatibility with Python 3
In reply to Michal Srb- gettext.install() only takes optional "unicode" keyword argument in Python 2, and its default value is "False". This keyword argument doesn't exist in Python 3
- __builtin__ module has been renamed to "builtins" in Python 3
- raw_input() has been renamed to input() in Python 3
- specify octal literals in form compatible with both Python 2 and 3
- migrate from commands to subprocess
- replace print statement with print function
- use reserved word as in try-except
- replace deprecated assert_() method with assertTrue() in unit tests
--- policycoreutils/sandbox/sandbox | 38 +++++++++++++++++++-------------- policycoreutils/sandbox/start | 6 +++--- policycoreutils/sandbox/test_sandbox.py | 12 +++++------ 3 files changed, 31 insertions(+), 25 deletions(-)
policycoreutils/sandbox/sandbox +22 -16
@@ -25,7 +25,6 @@ import selinux import signal from tempfile import mkdtemp import pwd -import commands import sepolicy PROGNAME = "policycoreutils"
@@ -36,13 +35,16 @@ gettext.bindtextdomain(PROGNAME, "/usr/share/locale") gettext.textdomain(PROGNAME) try: - gettext.install(PROGNAME, - localedir = "/usr/share/locale", - unicode=False, - codeset = 'utf-8') + gettext.install(PROGNAME, + localedir = "/usr/share/locale", + codeset = 'utf-8') except IOError: - import __builtin__ - __builtin__.__dict__['_'] = unicode + try: + import builtins + builtins.__dict__['_'] = str + except ImportError: + import __builtin__ + __builtin__.__dict__['_'] = unicode DEFAULT_WINDOWSIZE = "1000x700" DEFAULT_TYPE = "sandbox_t"
@@ -86,7 +88,7 @@ def copyfile(file, srcdir, dest): else: shutil.copy2(file, dest) - except shutil.Error, elist: + except shutil.Error as elist: for e in elist.message: sys.stderr.write(e[2])
@@ -107,7 +109,11 @@ def savefile(new, orig, X_ind): if rc == gtk.RESPONSE_YES: copy = True else: - ans = raw_input(_("Do you want to save changes to '%s' (y/N): ") % orig) + try: + input = raw_input + except NameError: + pass + ans = input(_("Do you want to save changes to '%s' (y/N): ") % orig) if(re.match(_("[yY]"),ans)): copy = True if(copy):
@@ -228,9 +234,9 @@ class Sandbox: for i in fd.readlines(): try: self.__include(option, opt, i[:-1], parser) - except IOError, e: + except IOError as e: sys.stderr.write(str(e)) - except TypeError, e: + except TypeError as e: sys.stderr.write(str(e)) fd.close()
@@ -263,7 +269,7 @@ dbus-launch --exit-with-session %s kill -TERM $WM_PID 2> /dev/null """ % (command, wm, command)) fd.close() - os.chmod(execfile, 0700) + os.chmod(execfile, 0o700) def usage(self, message = ""): error_exit("%s\n%s" % (self.__parser.usage, message))
@@ -492,13 +498,13 @@ if __name__ == '__main__': try: sandbox = Sandbox() rc = sandbox.main() - except OSError, error: + except OSError as error: error_exit(error) - except ValueError, error: + except ValueError as error: error_exit(error.args[0]) - except KeyError, error: + except KeyError as error: error_exit(_("Invalid value %s") % error.args[0]) - except IOError, error: + except IOError as error: error_exit(error) except KeyboardInterrupt: rc = 0
policycoreutils/sandbox/start +3 -3
@@ -1,9 +1,9 @@ #! /usr/bin/python -Es -import gtk, commands, sys +import gtk, subprocess, sys rc = [-1,''] try: - rc=commands.getstatusoutput(sys.argv[1]) + rc=subprocess.getstatusoutput(sys.argv[1]) except: pass if rc[0] == 0: - print rc[1] + print(rc[1])
policycoreutils/sandbox/test_sandbox.py +6 -6
@@ -4,18 +4,18 @@ from subprocess import Popen, PIPE class SandboxTests(unittest.TestCase): def assertDenied(self, err): - self.assert_('Permission denied' in err, + self.assertTrue(b'Permission denied' in err, '"Permission denied" not found in %r' % err) def assertNotFound(self, err): - self.assert_('not found' in err, + self.assertTrue(b'not found' in err, '"not found" not found in %r' % err) def assertFailure(self, status): - self.assert_(status != 0, + self.assertTrue(status != 0, '"Succeeded when it should have failed') def assertSuccess(self, status, err): - self.assert_(status == 0, + self.assertTrue(status == 0, '"Sandbox should have succeeded for this test %r' % err) def test_simple_success(self):
@@ -23,7 +23,7 @@ class SandboxTests(unittest.TestCase): p1 = Popen(['cat', '/etc/passwd'], stdout = PIPE) p2 = Popen(['sandbox', 'grep', 'root'], stdin = p1.stdout, stdout=PIPE) out, err = p2.communicate() - self.assert_('root' in out) + self.assertTrue(b'root' in out) def test_cant_kill(self): "Verify that we cannot send kill signal in the sandbox"
@@ -95,4 +95,4 @@ if __name__ == "__main__": if selinux.security_getenforce() == 1: unittest.main() else: - print "SELinux must be in enforcing mode for this test" + print("SELinux must be in enforcing mode for this test")
Signature · 1 line
2.4.3
PATCH 3/4 policycoreutils/semanage: improve compatibility with Python 3
In reply to Michal Srb- gettext.install() only takes "unicode" keyword argument in Python 2
- __builtin__ module has been renamed to "builtins" in Python 3
- use reserved word as in try-except
- replace print statement with print function
--- policycoreutils/semanage/semanage | 59 +++++++++++++++++-------------- policycoreutils/semanage/test-semanage.py | 4 +-- 2 files changed, 35 insertions(+), 28 deletions(-)
policycoreutils/semanage/semanage +33 -26
@@ -29,13 +29,20 @@ import sys import gettext PROGNAME="policycoreutils" try: - gettext.install(PROGNAME, - localedir="/usr/share/locale", - unicode=True, - codeset = 'utf-8') + kwargs = {} + if sys.version_info < (3,): + kwargs['unicode'] = True + gettext.install(PROGNAME, + localedir="/usr/share/locale", + codeset = 'utf-8', + **kwarg) except IOError: - import __builtin__ - __builtin__.__dict__['_'] = unicode + try: + import builtins + builtins.__dict__['_'] = str + except ImportError: + import __builtin__ + __builtin__.__dict__['_'] = unicode # define custom usages for selected main actions usage_login = "semanage login [-h] [-n] [-N] [-s STORE] ["
@@ -103,7 +110,7 @@ class SetImportFile(argparse.Action): if values and values is not "-": try: sys.stdin = open(values, 'r') - except IOError,e: + except IOError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) setattr(namespace, self.dest, values)
@@ -207,7 +214,7 @@ def handleLogin(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "login %s" % (str(i)) + print("login %s" % (str(i))) def parser_add_store(parser, name): parser.add_argument('-S', '--store', action=SetStore, help=_("Select an alternate SELinux Policy Store to manage"))
@@ -323,7 +330,7 @@ def handleFcontext(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "fcontext %s" % str(i) + print("fcontext %s" % str(i)) def setupFcontextParser(subparsers): ftype_help = '''
@@ -381,7 +388,7 @@ def handleUser(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "user %s" % str(i) + print("user %s" % str(i)) def setupUserParser(subparsers): generated_usage = generate_custom_usage(usage_user, usage_user_dict)
@@ -430,7 +437,7 @@ def handlePort(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "port %s" % str(i) + print("port %s" % str(i)) def setupPortParser(subparsers): generated_usage = generate_custom_usage(usage_port, usage_port_dict)
@@ -473,7 +480,7 @@ def handleInterface(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "interface %s" % str(i) + print("interface %s" % str(i)) def setupInterfaceParser(subparsers): generated_usage = generate_custom_usage(usage_interface, usage_interface_dict)
@@ -512,7 +519,7 @@ def handleModule(args): OBJECT.list(args.noheading, args.locallist) if args.action is "extract": for i in OBJECT.customized(): - print "module %s" % str(i) + print("module %s" % str(i)) def setupModuleParser(subparsers): moduleParser = subparsers.add_parser('module', help=_('Manage SELinux policy modules'))
@@ -552,7 +559,7 @@ def handleNode(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "node %s" % str(i) + print("node %s" % str(i)) def setupNodeParser(subparsers): generated_usage = generate_custom_usage(usage_node, usage_node_dict)
@@ -584,10 +591,10 @@ def handleBoolean(args): sys.exit(2) # TODO: should be added to handle_opts logic elif args.action is "modify" and not args.boolean: - print "boolean name required " + print("boolean name required ") sys.exit(1) elif args.action is "modify" and args.boolean and not args.state: - print "state option is needed" + print("state option is needed") sys.exit(1) else: handle_opts(args,boolean_args,args.action)
@@ -604,7 +611,7 @@ def handleBoolean(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "boolean %s" % str(i) + print("boolean %s" % str(i)) def setupBooleanParser(subparsers): generated_usage = generate_custom_usage(usage_boolean, usage_boolean_dict)
@@ -670,11 +677,11 @@ def setupDontauditParser(subparsers): def handleExport(args): manageditems=[ "boolean", "login", "interface", "user", "port", "node", "fcontext", "module"] for i in manageditems: - print "%s -D" % i + print("%s -D" % i) for i in manageditems: OBJECT = object_dict[i]() for c in OBJECT.customized(): - print "%s %s" % (i, str(c)) + print("%s %s" % (i, str(c))) sys.exit(0)
@@ -743,10 +750,10 @@ def handleImport(args): commandParser = createCommandParser() args = commandParser.parse_args(mkargv(l)) args.func(args) - except ValueError,e: + except ValueError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) - except IOError,e: + except IOError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) except KeyboardInterrupt:
@@ -822,21 +829,21 @@ def do_parser(): args = commandParser.parse_args(make_args(sys.argv)) args.func(args) sys.exit(0) - except IOError,e: + except IOError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) except KeyboardInterrupt: sys.exit(0) - except ValueError, e: + except ValueError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, e.args[0])) sys.exit(1) - except KeyError, e: + except KeyError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, e.args[0])) sys.exit(1) - except OSError, e: + except OSError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, e.args[1])) sys.exit(1) - except RuntimeError, e: + except RuntimeError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, e.args[0])) sys.exit(1)
policycoreutils/semanage/test-semanage.py +2 -2
@@ -273,10 +273,10 @@ if __name__ == "__main__": args = parser.parse_args() args.func(args) sys.exit(0) - except ValueError,e: + except ValueError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) - except IOError,e: + except IOError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) except KeyboardInterrupt:
Signature · 1 line
2.4.3
Re: [PATCH 3/4] policycoreutils/semanage: improve compatibility with Python 3
Quoted 20 lines · Michal Srb
-
gettext.install()only takes "unicode" keyword argument in Python 2
-__builtin__module has been renamed to "builtins" in Python 3
- use reserved wordasin try-except
- replace print statement with print functionSigned-off-by Michal Srb <[email protected]>--- policycoreutils/semanage/semanage | 59 +++++++++++++++++-------------- policycoreutils/semanage/test-semanage.py | 4 +-- 2 files changed, 35 insertions(+), 28 deletions(-)policycoreutils/semanage/semanage +0
-1@@ -29,13 +29,20 @@ import sys import gettext PROGNAME="policycoreutils" try: - gettext.install(PROGNAME,
policycoreutils/semanage/semanage import sys · line 38
Quoted 10 lines
policycoreutils/semanage/semanage +7
-3- localedir="/usr/share/locale", - unicode=True, - codeset = 'utf-8') + kwargs = {} + if sys.version_info < (3,): + kwargs['unicode'] = True + gettext.install(PROGNAME, + localedir="/usr/share/locale", + codeset = 'utf-8', + **kwarg)
I had to fix this (kwarg -> kwargs). Not tested?
Quoted 178 lines
policycoreutils/semanage/semanage +26
-22except IOError: - import __builtin__ - __builtin__.__dict__['_'] = unicode + try: + import builtins + builtins.__dict__['_'] = str + except ImportError: + import __builtin__ + __builtin__.__dict__['_'] = unicode # define custom usages for selected main actions usage_login = "semanage login [-h] [-n] [-N] [-s STORE] ["@@ -103,7 +110,7 @@ class SetImportFile(argparse.Action): if values and values is not "-": try: sys.stdin = open(values, 'r') - except IOError,e: + except IOError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) setattr(namespace, self.dest, values)@@ -207,7 +214,7 @@ def handleLogin(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "login %s" % (str(i)) + print("login %s" % (str(i))) def parser_add_store(parser, name): parser.add_argument('-S', '--store', action=SetStore, help=_("Select an alternate SELinux Policy Store to manage"))@@ -323,7 +330,7 @@ def handleFcontext(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "fcontext %s" % str(i) + print("fcontext %s" % str(i)) def setupFcontextParser(subparsers): ftype_help = '''@@ -381,7 +388,7 @@ def handleUser(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "user %s" % str(i) + print("user %s" % str(i)) def setupUserParser(subparsers): generated_usage = generate_custom_usage(usage_user, usage_user_dict)@@ -430,7 +437,7 @@ def handlePort(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "port %s" % str(i) + print("port %s" % str(i)) def setupPortParser(subparsers): generated_usage = generate_custom_usage(usage_port, usage_port_dict)@@ -473,7 +480,7 @@ def handleInterface(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "interface %s" % str(i) + print("interface %s" % str(i)) def setupInterfaceParser(subparsers): generated_usage = generate_custom_usage(usage_interface, usage_interface_dict)@@ -512,7 +519,7 @@ def handleModule(args): OBJECT.list(args.noheading, args.locallist) if args.action is "extract": for i in OBJECT.customized(): - print "module %s" % str(i) + print("module %s" % str(i)) def setupModuleParser(subparsers): moduleParser = subparsers.add_parser('module', help=_('Manage SELinux policy modules'))@@ -552,7 +559,7 @@ def handleNode(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "node %s" % str(i) + print("node %s" % str(i)) def setupNodeParser(subparsers): generated_usage = generate_custom_usage(usage_node, usage_node_dict)@@ -584,10 +591,10 @@ def handleBoolean(args): sys.exit(2) # TODO: should be added to handle_opts logic elif args.action is "modify" and not args.boolean: - print "boolean name required " + print("boolean name required ") sys.exit(1) elif args.action is "modify" and args.boolean and not args.state: - print "state option is needed" + print("state option is needed") sys.exit(1) else: handle_opts(args,boolean_args,args.action)@@ -604,7 +611,7 @@ def handleBoolean(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "boolean %s" % str(i) + print("boolean %s" % str(i)) def setupBooleanParser(subparsers): generated_usage = generate_custom_usage(usage_boolean, usage_boolean_dict)@@ -670,11 +677,11 @@ def setupDontauditParser(subparsers): def handleExport(args): manageditems=[ "boolean", "login", "interface", "user", "port", "node", "fcontext", "module"] for i in manageditems: - print "%s -D" % i + print("%s -D" % i) for i in manageditems: OBJECT = object_dict[i]() for c in OBJECT.customized(): - print "%s %s" % (i, str(c)) + print("%s %s" % (i, str(c))) sys.exit(0)@@ -743,10 +750,10 @@ def handleImport(args): commandParser = createCommandParser() args = commandParser.parse_args(mkargv(l)) args.func(args) - except ValueError,e: + except ValueError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) - except IOError,e: + except IOError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) except KeyboardInterrupt:@@ -822,21 +829,21 @@ def do_parser(): args = commandParser.parse_args(make_args(sys.argv)) args.func(args) sys.exit(0) - except IOError,e: + except IOError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) except KeyboardInterrupt: sys.exit(0) - except ValueError, e: + except ValueError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, e.args[0])) sys.exit(1) - except KeyError, e: + except KeyError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, e.args[0])) sys.exit(1) - except OSError, e: + except OSError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, e.args[1])) sys.exit(1) - except RuntimeError, e: + except RuntimeError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, e.args[0])) sys.exit(1)policycoreutils/semanage/test-semanage.py +2
-2@@ -273,10 +273,10 @@ if __name__ == "__main__": args = parser.parse_args() args.func(args) sys.exit(0) - except ValueError,e: + except ValueError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) - except IOError,e: + except IOError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) except KeyboardInterrupt:
Re: [PATCH 3/4] policycoreutils/semanage: improve compatibility with Python 3
Quoted 24 lines · Stephen Smalley
Quoted 23 lines · Michal Srb
-
gettext.install()only takes "unicode" keyword argument in Python 2
-__builtin__module has been renamed to "builtins" in Python 3
- use reserved wordasin try-except
- replace print statement with print functionSigned-off-by Michal Srb <[email protected]>--- policycoreutils/semanage/semanage | 59 +++++++++++++++++-------------- policycoreutils/semanage/test-semanage.py | 4 +-- 2 files changed, 35 insertions(+), 28 deletions(-)policycoreutils/semanage/semanage +0
-4@@ -29,13 +29,20 @@ import sys import gettext PROGNAME="policycoreutils" try: - gettext.install(PROGNAME, - localedir="/usr/share/locale", - unicode=True, - codeset = 'utf-8')
Quoted 8 lines
policycoreutils/semanage/semanage import sys · line 38
Quoted 7 lines
policycoreutils/semanage/semanage +7
-0+ kwargs = {} + if sys.version_info < (3,): + kwargs['unicode'] = True + gettext.install(PROGNAME, + localedir="/usr/share/locale", + codeset = 'utf-8', + **kwarg)I had to fix this (kwarg -> kwargs). Not tested?
Oops, sorry about that. I remember doing minor changes in this part just before sending the patches - and I probably forgot to run tests on it after editing :/
Michal
Quoted 179 lines
Quoted 179 lines
policycoreutils/semanage/semanage +26
-22except IOError: - import __builtin__ - __builtin__.__dict__['_'] = unicode + try: + import builtins + builtins.__dict__['_'] = str + except ImportError: + import __builtin__ + __builtin__.__dict__['_'] = unicode # define custom usages for selected main actions usage_login = "semanage login [-h] [-n] [-N] [-s STORE] ["@@ -103,7 +110,7 @@ class SetImportFile(argparse.Action): if values and values is not "-": try: sys.stdin = open(values, 'r') - except IOError,e: + except IOError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) setattr(namespace, self.dest, values)@@ -207,7 +214,7 @@ def handleLogin(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "login %s" % (str(i)) + print("login %s" % (str(i))) def parser_add_store(parser, name): parser.add_argument('-S', '--store', action=SetStore, help=_("Select an alternate SELinux Policy Store to manage"))@@ -323,7 +330,7 @@ def handleFcontext(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "fcontext %s" % str(i) + print("fcontext %s" % str(i)) def setupFcontextParser(subparsers): ftype_help = '''@@ -381,7 +388,7 @@ def handleUser(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "user %s" % str(i) + print("user %s" % str(i)) def setupUserParser(subparsers): generated_usage = generate_custom_usage(usage_user, usage_user_dict)@@ -430,7 +437,7 @@ def handlePort(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "port %s" % str(i) + print("port %s" % str(i)) def setupPortParser(subparsers): generated_usage = generate_custom_usage(usage_port, usage_port_dict)@@ -473,7 +480,7 @@ def handleInterface(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "interface %s" % str(i) + print("interface %s" % str(i)) def setupInterfaceParser(subparsers): generated_usage = generate_custom_usage(usage_interface, usage_interface_dict)@@ -512,7 +519,7 @@ def handleModule(args): OBJECT.list(args.noheading, args.locallist) if args.action is "extract": for i in OBJECT.customized(): - print "module %s" % str(i) + print("module %s" % str(i)) def setupModuleParser(subparsers): moduleParser = subparsers.add_parser('module', help=_('Manage SELinux policy modules'))@@ -552,7 +559,7 @@ def handleNode(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "node %s" % str(i) + print("node %s" % str(i)) def setupNodeParser(subparsers): generated_usage = generate_custom_usage(usage_node, usage_node_dict)@@ -584,10 +591,10 @@ def handleBoolean(args): sys.exit(2) # TODO: should be added to handle_opts logic elif args.action is "modify" and not args.boolean: - print "boolean name required " + print("boolean name required ") sys.exit(1) elif args.action is "modify" and args.boolean and not args.state: - print "state option is needed" + print("state option is needed") sys.exit(1) else: handle_opts(args,boolean_args,args.action)@@ -604,7 +611,7 @@ def handleBoolean(args): OBJECT.deleteall() if args.action is "extract": for i in OBJECT.customized(): - print "boolean %s" % str(i) + print("boolean %s" % str(i)) def setupBooleanParser(subparsers): generated_usage = generate_custom_usage(usage_boolean, usage_boolean_dict)@@ -670,11 +677,11 @@ def setupDontauditParser(subparsers): def handleExport(args): manageditems=[ "boolean", "login", "interface", "user", "port", "node", "fcontext", "module"] for i in manageditems: - print "%s -D" % i + print("%s -D" % i) for i in manageditems: OBJECT = object_dict[i]() for c in OBJECT.customized(): - print "%s %s" % (i, str(c)) + print("%s %s" % (i, str(c))) sys.exit(0)@@ -743,10 +750,10 @@ def handleImport(args): commandParser = createCommandParser() args = commandParser.parse_args(mkargv(l)) args.func(args) - except ValueError,e: + except ValueError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) - except IOError,e: + except IOError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) except KeyboardInterrupt:@@ -822,21 +829,21 @@ def do_parser(): args = commandParser.parse_args(make_args(sys.argv)) args.func(args) sys.exit(0) - except IOError,e: + except IOError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) except KeyboardInterrupt: sys.exit(0) - except ValueError, e: + except ValueError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, e.args[0])) sys.exit(1) - except KeyError, e: + except KeyError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, e.args[0])) sys.exit(1) - except OSError, e: + except OSError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, e.args[1])) sys.exit(1) - except RuntimeError, e: + except RuntimeError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, e.args[0])) sys.exit(1)policycoreutils/semanage/test-semanage.py +2
-2@@ -273,10 +273,10 @@ if __name__ == "__main__": args = parser.parse_args() args.func(args) sys.exit(0) - except ValueError,e: + except ValueError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) - except IOError,e: + except IOError as e: sys.stderr.write("%s: %s\n" % (e.__class__.__name__, str(e))) sys.exit(1) except KeyboardInterrupt:
PATCH 4/4 policycoreutils/scripts: improve compatibility with Python 3
In reply to Michal Srb- __builtin__ module has been renamed to "builtins" in Python 3
- use reserved word as in try-except
- replace print statement with print function
- migrate from commands to subprocess
- fix formatting
--- policycoreutils/scripts/chcat | 80 +++++++++++++++++++++++-------------------- 1 file changed, 42 insertions(+), 38 deletions(-)
policycoreutils/scripts/chcat +42 -38
@@ -22,15 +22,19 @@ # 02111-1307 USA # # -import commands, sys, os, pwd, string, getopt, selinux +import subprocess, sys, os, pwd, string, getopt, selinux import seobject import gettext try: gettext.install('policycoreutils') except IOError: - import __builtin__ - __builtin__.__dict__['_'] = unicode + try: + import builtins + builtins.__dict__['_'] = str + except ImportError: + import __builtin__ + __builtin__.__dict__['_'] = unicode def errorExit(error): sys.stderr.write("%s: " % sys.argv[0])
@@ -80,9 +84,9 @@ def chcat_user_add(newcat, users): cmd = "semanage login -a -r %s -s %s %s" % (new_serange, user[0], u) else: cmd = "semanage login -m -r %s -s %s %s" % (new_serange, user[0], u) - rc = commands.getstatusoutput(cmd) + rc = subprocess.getstatusoutput(cmd) if rc[0] != 0: - print rc[1] + print(rc[1]) errors += 1 return errors
@@ -107,7 +111,7 @@ def chcat_add(orig, newcat, objects,login_ind): if len(clist) > 1: if cat in clist[1:]: - print _("%s is already in %s") % (f, orig) + print(_("%s is already in %s") % (f, orig)) continue clist.append(cat) cats = clist[1:]
@@ -118,9 +122,9 @@ def chcat_add(orig, newcat, objects,login_ind): else: cat_string = cat cmd = 'chcon -l %s:%s %s' % (sensitivity, cat_string, f) - rc = commands.getstatusoutput(cmd) + rc = subprocess.getstatusoutput(cmd) if rc[0] != 0: - print rc[1] + print(rc[1]) errors += 1 return errors
@@ -158,9 +162,9 @@ def chcat_user_remove(newcat, users): cmd = "semanage login -a -r %s -s %s %s" % (new_serange, user[0], u) else: cmd = "semanage login -m -r %s -s %s %s" % (new_serange, user[0], u) - rc = commands.getstatusoutput(cmd) + rc = subprocess.getstatusoutput(cmd) if rc[0] != 0: - print rc[1] + print(rc[1]) errors += 1 return errors
@@ -185,7 +189,7 @@ def chcat_remove(orig, newcat, objects, login_ind): if len(clist) > 1: if cat not in clist[1:]: - print _("%s is not in %s") % (f, orig) + print(_("%s is not in %s") % (f, orig)) continue clist.remove(cat) if len(clist) > 1:
@@ -195,16 +199,16 @@ def chcat_remove(orig, newcat, objects, login_ind): else: cat = "" else: - print _("%s is not in %s") % (f, orig) + print(_("%s is not in %s") % (f, orig)) continue if len(cat) == 0: cmd = 'chcon -l %s %s' % (sensitivity, f) else: cmd = 'chcon -l %s:%s %s' % (sensitivity,cat, f) - rc = commands.getstatusoutput(cmd) + rc = subprocess.getstatusoutput(cmd) if rc[0] != 0: - print rc[1] + print(rc[1]) errors += 1 return errors
@@ -229,9 +233,9 @@ def chcat_user_replace(newcat, users): cmd = "semanage login -a -r %s -s %s %s" % (new_serange, user[0], u) else: cmd = "semanage login -m -r %s -s %s %s" % (new_serange, user[0], u) - rc = commands.getstatusoutput(cmd) + rc = subprocess.getstatusoutput(cmd) if rc[0] != 0: - print rc[1] + print(rc[1]) errors += 1 return errors
@@ -251,9 +255,9 @@ def chcat_replace(newcat, objects, login_ind): for f in objects: cmd = "%s %s" % (cmd, f) - rc = commands.getstatusoutput(cmd) + rc = subprocess.getstatusoutput(cmd) if rc[0] != 0: - print rc[1] + print(rc[1]) errors += 1 return errors
@@ -322,18 +326,18 @@ def translate(cats): return newcat def usage(): - print _("Usage %s CATEGORY File ...") % sys.argv[0] - print _("Usage %s -l CATEGORY user ...") % sys.argv[0] - print _("Usage %s [[+|-]CATEGORY],...]q File ...") % sys.argv[0] - print _("Usage %s -l [[+|-]CATEGORY],...]q user ...") % sys.argv[0] - print _("Usage %s -d File ...") % sys.argv[0] - print _("Usage %s -l -d user ...") % sys.argv[0] - print _("Usage %s -L") % sys.argv[0] - print _("Usage %s -L -l user") % sys.argv[0] - print _("Use -- to end option list. For example") - print _("chcat -- -CompanyConfidential /docs/businessplan.odt") - print _("chcat -l +CompanyConfidential juser") - sys.exit(1) + print(_("Usage %s CATEGORY File ...") % sys.argv[0]) + print(_("Usage %s -l CATEGORY user ...") % sys.argv[0]) + print(_("Usage %s [[+|-]CATEGORY],...]q File ...") % sys.argv[0]) + print(_("Usage %s -l [[+|-]CATEGORY],...]q user ...") % sys.argv[0]) + print(_("Usage %s -d File ...") % sys.argv[0]) + print(_("Usage %s -l -d user ...") % sys.argv[0]) + print(_("Usage %s -L") % sys.argv[0]) + print(_("Usage %s -L -l user") % sys.argv[0]) + print(_("Use -- to end option list. For example")) + print(_("chcat -- -CompanyConfidential /docs/businessplan.odt")) + print(_("chcat -l +CompanyConfidential juser")) + sys.exit(1) def listcats(): fd = open(selinux.selinux_translations_path())
@@ -342,7 +346,7 @@ def listcats(): continue if l.find("=") != -1: rec = l.split("=") - print "%-30s %s" % tuple(rec) + print("%-30s %s" % tuple(rec)) fd.close() return 0
@@ -356,12 +360,12 @@ def listusercats(users): cats = seobject.translate(selinux.getseuserbyname(u)[2]) cats = cats.split("-") if len(cats) > 1 and cats[1] != "s0": - print "%s: %s" % (u, cats[1]) + print("%s: %s" % (u, cats[1])) else: - print "%s: %s" % (u, cats[0]) + print("%s: %s" % (u, cats[0])) def error(msg): - print "%s: %s" % (sys.argv[0], msg) + print("%s: %s" % (sys.argv[0], msg)) sys.exit(1) if __name__ == '__main__':
@@ -395,10 +399,10 @@ if __name__ == '__main__': if list_ind == 0 and len(cmds) < 1: usage() - except getopt.error, error: + except getopt.error as error: errorExit(_("Options Error %s ") % error.msg) - except ValueError, e: + except ValueError as e: usage() if delete_ind:
@@ -433,9 +437,9 @@ if __name__ == '__main__': if len(c) > 0 and c[0] == "-": errors += chcat_remove(c[1:],translate(l), objects, login_ind) continue - except ValueError, e: + except ValueError as e: error(e) - except OSError, e: + except OSError as e: error(e) sys.exit(errors)
Signature · 1 line
2.4.3
Stephen Smalley
AppliedQuoted 11 lines · Michal Srb
Hello,
These patches try to add Python 3 support to the following places under policycoreutils/:
audit2allow/
sandbox/scripts/
semanage/ (exceptseobject.py)Patch for the
seobject.pyshould follow later.
Thanks, applied.