def test_edge_conditions_statements(): ''' Test that we get correct behaviour using statements (INTEGER, REAL, TYPE, CALL, SUBROUTINE and USE) when the input line equals the max line length, or multiples thereof and lengths one larger and one smaller. This is to make sure we don't have issues like ending up with a continuation but no following line.''' input_string = ("INTEGER INTEG\n" "INTEGER INTEGE\n" "INTEGER INTEGER\n") expected_output = ("INTEGER INTEG\n" "INTEGER INTEGE\n" "INTEGER &\n&INTEGER\n") fll = FortLineLength(line_length=len("INTEGER INTEGE")) output_string = fll.process(input_string) print output_string print expected_output assert output_string == expected_output input_string = ("INTEGER INTEGER INTEG\n" "INTEGER INTEGER INTEGE\n" "INTEGER INTEGER INTEGER\n") expected_output = ("INTEGER &\n&INTEGER INTEG\n" "INTEGER &\n&INTEGER INTEGE\n" "INTEGER &\n&INTEGER &\n&INTEGER\n") fll = FortLineLength(line_length=len("INTEGER INTEGER")) output_string = fll.process(input_string) print output_string print expected_output assert output_string == expected_output
def test_comment(): ''' Tests that a long comment line wrapped as expected ''' input_file = " ! this is a comment" expected_output = " ! this is a \n!& comment" fll = FortLineLength(line_length=len(input_file) - 5) output_file = fll.process(input_file) assert output_file == expected_output
def test_wrapped(): ''' Tests that a file whose lines are longer than the specified line length is wrapped appropriately by the FortLineLength class ''' fll = FortLineLength(line_length=30) output_file = fll.process(INPUT_FILE) print "(" + EXPECTED_OUTPUT + ")" print "(" + output_file + ")" assert output_file == EXPECTED_OUTPUT, "output and expected output differ "
def test_multiple_lines_comment(): ''' test that multiple lines works as expected for comments ''' input_file = ("! blahdeblah, blahdeblah, blahdeblah, blahdeblah\n") expected_output = ( "! blahdeblah, \n!& blahdeblah, \n!& blahdeblah, \n!& blahdeblah\n") fll = FortLineLength(line_length=18) output_file = fll.process(input_file) assert output_file == expected_output
def test_fail_to_wrap(): ''' Tests that we raise an error if we can't find anywhere to wrap the line''' input_file = "!$OMPPARALLELDO" with pytest.raises(Exception) as excinfo: fll = FortLineLength(line_length=len(input_file) - 1) _ = fll.process(input_file) assert 'No suitable break point found' in str(excinfo.value)
def test_acc_directive(): ''' Tests that we deal with an OpenACC directive appropriately when its needs to be line wrapped ''' input_file = " !$ACC kernels loop gang(32), vector(16)\n" expected_output = " !$ACC kernels loop gang(32), &\n!$acc& vector(16)\n" fll = FortLineLength(line_length=len(input_file) - 5) output_file = fll.process(input_file) assert output_file == expected_output
def test_openmp_directive(): ''' Tests that we successfully break an OpenMP directive line on a space ''' input_file = " !$OMP PARALLEL LOOP\n" expected_output = " !$OMP PARALLEL &\n!$omp& LOOP\n" fll = FortLineLength(line_length=len(input_file) - 3) output_file = fll.process(input_file) assert output_file == expected_output
def _code_compiles(self, psy_ast): '''Attempts to build the Fortran code supplied as an AST of f2pygen objects. Returns True for success, False otherwise. It is meant for internal test uses only, and must only be called when compilation is actually enabled (use code_compiles otherwse). All files produced are deleted. :param psy_ast: The AST of the generated PSy layer :type psy_ast: Instance of :py:class:`psyclone.psyGen.PSy` :return: True if generated code compiles, False otherwise :rtype: bool ''' kernel_modules = set() # Get the names of the modules associated with the kernels. # By definition, built-ins do not have associated Fortran modules. for invoke in psy_ast.invokes.invoke_list: for call in invoke.schedule.coded_kernels(): kernel_modules.add(call.module_name) # Change to the temporary directory passed in to us from # pytest. (This is a LocalPath object.) old_pwd = self._tmpdir.chdir() # Create a file containing our generated PSy layer. psy_filename = "psy.f90" with open(psy_filename, 'w') as psy_file: # We limit the line lengths of the generated code so that # we don't trip over compiler limits. from psyclone.line_length import FortLineLength fll = FortLineLength() psy_file.write(fll.process(str(psy_ast.gen))) success = True try: # Build the kernels. We allow kernels to also be located in # the temporary directory that we have been passed. for fort_file in kernel_modules: # Skip file if it is not Fortran. TODO #372: Add support # for C/OpenCL compiling as part of the test suite. if fort_file.endswith(".cl"): continue name = self.find_fortran_file( [self.base_path, str(self._tmpdir)], fort_file) self.compile_file(name) # Finally, we can build the psy file we have generated self.compile_file(psy_filename) except CompileError: # Failed to compile one of the files success = False finally: old_pwd.chdir() return success
def test_multiple_lines_acc(): ''' test that multiple lines works as expected for OpenACC directives ''' input_file = ("!$acc blahdeblah, blahdeblah, blahdeblah, blahdeblah\n") expected_output = ( "!$acc blahdeblah, &\n!$acc& blahdeblah, &\n!$acc& blahdeblah," " &\n!$acc& blahdeblah\n") fll = FortLineLength(line_length=24) output_file = fll.process(input_file) assert output_file == expected_output
def test_multiple_lines_statements(): ''' test that multiple lines works as expected for statements (INTEGER, REAL, TYPE, CALL, SUBROUTINE and USE) ''' input_file = ("INTEGER blahdeblah, blahdeblah, blahdeblah, blahdeblah\n") expected_output = ( "INTEGER &\n&blahdeblah, &\n&blahdeblah, &\n&blahdeblah," " &\n&blahdeblah\n") fll = FortLineLength(line_length=18) output_file = fll.process(input_file) assert output_file == expected_output
def test_wrapped_lower(): ''' Tests that a lower case file whose lines are longer than the specified line length is wrapped appropriately by the FortLineLength class''' fll = FortLineLength(line_length=30) output_file = fll.process(INPUT_FILE.lower()) print("(" + EXPECTED_OUTPUT.lower() + ")") print("(" + output_file + ")") assert output_file == EXPECTED_OUTPUT.lower(), \ "output and expected output differ "
def test_exception_line_too_long(): ''' Test that output lines are not longer than the maximum specified''' input_file = ("INTEGER stuffynostrils, blahdeblah,blahdeblah blahdeblah\n" "!$omp stuffynostrils,(blahdeblah)blahdeblah=(blahdeblah)\n" "!$acc stuffynostrils,(blahdeblah)blahdeblah=(blahdeblah)\n" "! stuffynostrils,blahdeblah.blahdeblah blahdeblah).\n") fll = FortLineLength(line_length=24) output_file = fll.process(input_file) for line in output_file.split('\n'): assert len(line) <= 24, \ "Error, output line is longer than the maximum allowed"
def test_long_line_continuator(): '''Tests that an input algorithm file with long lines of a type not recognised by FortLineLength (assignments in this case), which already have continuators to make the code conform to the line length limit, does not cause an error. ''' alg, _ = generate(os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_files", "dynamo0p3", "13.2_alg_long_line_continuator.f90"), api="dynamo0.3") input_string = str(alg) fll = FortLineLength() _ = fll.process(input_string)
def run(): ''' Top-level driver for the kernel-stub generator. Handles command-line flags, calls generate() and applies line-length limiting to the output (if requested). ''' import argparse parser = argparse.ArgumentParser(description="Create Kernel stub code from" " Kernel metadata") parser.add_argument("-o", "--outfile", help="filename of output") parser.add_argument( "-api", default=Config.get().default_stub_api, help="choose a particular api from {0}, default {1}".format( str(Config.get().supported_stub_apis), Config.get().default_stub_api)) parser.add_argument('filename', help='Kernel metadata') parser.add_argument('-l', '--limit', dest='limit', action='store_true', default=False, help='limit the fortran line length to 132 characters') args = parser.parse_args() try: stub = generate(args.filename, api=args.api) except (IOError, ParseError, GenerationError, RuntimeError) as error: print("Error:", error) exit(1) except Exception as error: # pylint: disable=broad-except print("Error, unexpected exception:\n") exc_type, exc_value, exc_traceback = sys.exc_info() print(exc_type) print(exc_value) traceback.print_tb(exc_traceback) exit(1) if args.limit: fll = FortLineLength() stub_str = fll.process(str(stub)) else: stub_str = str(stub) if args.outfile is not None: my_file = open(args.outfile, "w") my_file.write(stub_str) my_file.close() else: print("Kernel stub code:\n", stub_str)
def test_unchanged(): ''' Tests that a file whose lines are shorter than the specified line length is unchanged by the FortLineLength class ''' input_file = (" INTEGER stuff\n" " REAL stuff\n" " TYPE stuff\n" " CALL stuff\n" " SUBROUTINE stuff\n" " USE stuff\n" " !$OMP stuff\n" " !$ACC stuff\n" " ! stuff\n" " stuff\n") fll = FortLineLength(line_length=25) output_file = fll.process(input_file) print "(" + input_file + ")" print "(" + output_file + ")" assert input_file == output_file, "input should remain unchanged"
def test_edge_conditions_comments(): '''Test that we get correct behaviour with comments when the input line equals the max line length, or multiples thereof and lengths one larger and one smaller. This is to make sure we don't have issues like ending up with a continuation but no following line.''' input_string = ("! COMMENT COMME\n" "! COMMENT COMMEN\n" "! COMMENT COMMENT\n" "! COMMENT COMMENT COMME\n" "! COMMENT COMMENT COMMEN\n" "! COMMENT COMMENT COMMENT\n") expected_output = ("! COMMENT COMME\n" "! COMMENT COMMEN\n" "! COMMENT \n!& COMMENT\n" "! COMMENT \n!& COMMENT COMME\n" "! COMMENT \n!& COMMENT COMMEN\n" "! COMMENT \n!& COMMENT \n!& COMMENT\n") fll = FortLineLength(line_length=len("! COMMENT COMMEN")) output_string = fll.process(input_string) assert output_string == expected_output
def test_edge_conditions_omp(): '''Test that we get correct behaviour using OpenMP directives when the input line equals the max line length, or multiples thereof and lengths one larger and one smaller. This is to make sure we don't have issues like ending up with a continuation but no following line. ''' input_string = ("!$OMP OPENMP OPEN\n" "!$OMP OPENMP OPENM\n" "!$OMP OPENMP OPENMP\n" "!$OMP OPENMP OPENMP OPEN\n" "!$OMP OPENMP OPENMP OPENM\n" "!$OMP OPENMP OPENMP OPENMP\n") expected_output = ("!$OMP OPENMP OPEN\n" "!$OMP OPENMP OPENM\n" "!$OMP OPENMP &\n!$omp& OPENMP\n" "!$OMP OPENMP &\n!$omp& OPENMP OPEN\n" "!$OMP OPENMP &\n!$omp& OPENMP OPENM\n" "!$OMP OPENMP &\n!$omp& OPENMP &\n!$omp& OPENMP\n") fll = FortLineLength(line_length=len("!$OMP OPENMP OPENM")) output_string = fll.process(input_string) assert output_string == expected_output
def test_break_types_multi_line(): ''' Test the different supported line breaks.''' input_file = ("INTEGER stuffynostrils, blahdeblah,blahdeblah blahdeblah\n" "!$omp stuffynostrils,(blahdeblah)blahdeblah=(blahdeblah)\n" "!$acc stuffynostrils,(blahdeblah)blahdeblah=(blahdeblah)\n" "! stuffynostrils,blahdeblah.blahdeblah blahdeblah).\n") expected_output = ( "INTEGER stuffynostrils,&\n& blahdeblah,&\n&blahdeblah" " blahdeblah\n" "!$omp &\n!$omp& stuffynostrils, &\n!$omp& (blahdeblah) &\n!$omp&" " blahdeblah= &\n!$omp& (blahdeblah)\n" "!$acc &\n!$acc& stuffynostrils, &\n!$acc& (blahdeblah) &\n!$acc&" " blahdeblah= &\n!$acc& (blahdeblah)\n" "! \n!& stuffynostrils,\n!& blahdeblah.\n!& blahdeblah \n!&" " blahdeblah).\n") fll = FortLineLength(line_length=24) output_file = fll.process(input_file) print "(" + output_file + ")" print expected_output assert output_file == expected_output
''' Script to demonstrate the use on the line wrapping support in PSyclone''' from __future__ import print_function from psyclone.generator import generate from psyclone.line_length import FortLineLength # long_lines=True checks whether the input fortran conforms to the 132 line # length limit ALG, PSY = generate( "longlines.f90", kernel_path="../../src/psyclone/tests/test_files/dynamo0p3", line_length=True) LINE_LENGTH = FortLineLength() ALG_STR = LINE_LENGTH.process(str(ALG)) print(ALG_STR) PSY_STR = LINE_LENGTH.process(str(PSY)) print(PSY_STR)
def code_compiles(api, psy_ast, tmpdir, f90, f90flags): '''Attempts to build the Fortran code supplied as an AST of f2pygen objects. Returns True for success, False otherwise. If no Fortran compiler is available then returns True. All files produced are deleted. :param api: Which PSyclone API the supplied code is using :type api: string :param psy_ast: The AST of the generated PSy layer :type psy_ast: Instance of :py:class:`psyGen.PSy` :param tmpdir: py.test-supplied temporary directory. Can contain \ transformed kernel source. :type tmpdir: :py:class:`LocalPath` :param f90: The command to invoke the Fortran compiler :type f90: string :param f90flags: Flags to pass to the Fortran compiler :type f90flags: string :return: True if generated code compiles, False otherwise :rtype: bool ''' if not TEST_COMPILE: # Compilation testing is not enabled return True # API-specific set-up - where to find infrastructure source files # and which ones to build supported_apis = ["dynamo0.3"] if api not in supported_apis: raise CompileError("Unsupported API in code_compiles. Got {0} but " "only support {1}".format(api, supported_apis)) if api == "dynamo0.3": base_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_files", "dynamo0p3") from dynamo0p3_build import INFRASTRUCTURE_MODULES as module_files kernel_modules = set() # Get the names of the modules associated with the kernels. By definition, # built-ins do not have associated Fortran modules. for invoke in psy_ast.invokes.invoke_list: for call in invoke.schedule.kern_calls(): kernel_modules.add(call.module_name) # Change to the temporary directory passed in to us from # pytest. (This is a LocalPath object.) old_pwd = tmpdir.chdir() # Create a file containing our generated PSy layer. psy_filename = "psy.f90" with open(psy_filename, 'w') as psy_file: # We limit the line lengths of the generated code so that # we don't trip over compiler limits. from psyclone.line_length import FortLineLength fll = FortLineLength() psy_file.write(fll.process(str(psy_ast.gen))) # Infrastructure modules are in the 'infrastructure' directory module_path = os.path.join(base_path, "infrastructure") kernel_path = base_path success = False try: # First build the infrastructure modules for fort_file in module_files: name = find_fortran_file([module_path], fort_file) # We don't have to copy the source file - just compile it in the # current working directory. success = compile_file(name, f90, f90flags) # Next, build the kernels. We allow kernels to also be located in # the temporary directory that we have been passed. for fort_file in kernel_modules: name = find_fortran_file([kernel_path, str(tmpdir)], fort_file) success = compile_file(name, f90, f90flags) # Finally, we can build the psy file we have generated success = compile_file(psy_filename, f90, f90flags) except CompileError: # Failed to compile one of the files success = False finally: # Clean-up - delete all generated files. This permits this routine # to be called multiple times from within the same test. os.chdir(str(old_pwd)) for ofile in tmpdir.listdir(): ofile.remove() return success
def main(args): ''' Parses and checks the command line arguments, calls the generate function if all is well, catches any errors and outputs the results. :param list args: the list of command-line arguments that PSyclone has \ been invoked with. ''' # pylint: disable=too-many-statements,too-many-branches # Make sure we have the supported APIs defined in the Config singleton, # but postpone loading the config file till the command line was parsed # in case that the user specifies a different config file. Config.get(do_not_load_file=True) parser = argparse.ArgumentParser( description='Run the PSyclone code generator on a particular file') parser.add_argument('-oalg', help='filename of transformed algorithm code') parser.add_argument('-opsy', help='filename of generated PSy code') parser.add_argument('-okern', help='directory in which to put transformed kernels, ' 'default is the current working directory.') parser.add_argument('-api', help='choose a particular api from {0}, ' 'default \'{1}\'.'.format( str(Config.get().supported_apis), Config.get().default_api)) parser.add_argument('filename', help='algorithm-layer source code') parser.add_argument('-s', '--script', help='filename of a PSyclone' ' optimisation script') parser.add_argument('-d', '--directory', default="", help='path to root of directory ' 'structure containing kernel source code') # Make the default an empty list so that we can check whether the # user has supplied a value(s) later parser.add_argument('-I', '--include', default=[], action="append", help='path to Fortran INCLUDE files (nemo API only)') parser.add_argument('-l', '--limit', dest='limit', action='store_true', default=False, help='limit the fortran line length to 132 characters') parser.add_argument('-dm', '--dist_mem', dest='dist_mem', action='store_true', help='generate distributed memory code') parser.add_argument('-nodm', '--no_dist_mem', dest='dist_mem', action='store_false', help='do not generate distributed memory code') parser.add_argument( '--kernel-renaming', default="multiple", choices=configuration.VALID_KERNEL_NAMING_SCHEMES, help="Naming scheme to use when re-naming transformed kernels") parser.add_argument( '--profile', '-p', action="append", choices=Profiler.SUPPORTED_OPTIONS, help="Add profiling hooks for either 'kernels' or 'invokes'") parser.add_argument( '--force-profile', action="append", choices=Profiler.SUPPORTED_OPTIONS, help="Add profiling hooks for either 'kernels' or 'invokes' even if a " "transformation script is used. Use at your own risk.") parser.set_defaults(dist_mem=Config.get().distributed_memory) parser.add_argument("--config", help="Config file with " "PSyclone specific options.") parser.add_argument( '-v', '--version', dest='version', action="store_true", help='Display version information ({0})'.format(__VERSION__)) args = parser.parse_args(args) if args.version: print("PSyclone version: {0}".format(__VERSION__)) if args.script is not None and args.profile is not None: print( "Error: use of automatic profiling in combination with an\n" "optimisation script is not recommended since it may not work\n" "as expected.\n" "You can use --force-profile instead of --profile if you \n" "really want to use both options at the same time.", file=sys.stderr) exit(1) if args.profile is not None and args.force_profile is not None: print("Specify only one of --profile and --force-profile.", file=sys.stderr) exit(1) if args.profile: Profiler.set_options(args.profile) elif args.force_profile: Profiler.set_options(args.force_profile) # If an output directory has been specified for transformed kernels # then check that it is valid if args.okern: if not os.path.exists(args.okern): print("Specified kernel output directory ({0}) does not exist.". format(args.okern), file=sys.stderr) exit(1) if not os.access(args.okern, os.W_OK): print("Cannot write to specified kernel output directory ({0}).". format(args.okern), file=sys.stderr) exit(1) kern_out_path = args.okern else: # We write any transformed kernels to the current working directory kern_out_path = os.getcwd() # If no config file name is specified, args.config is none # and config will load the default config file. Config.get().load(args.config) # Check API, if none is specified, take the setting from the config file if args.api is None: # No command line option, use the one specified in Config - which # is either based on a parameter in the config file, or otherwise # the default: api = Config.get().api elif args.api not in Config.get().supported_apis: print("Unsupported API '{0}' specified. Supported API's are " "{1}.".format(args.api, Config.get().supported_apis), file=sys.stderr) exit(1) else: # There is a valid API specified on the command line. Set it # as API in the config object as well. api = args.api Config.get().api = api # Store the search path(s) for include files if args.include and api != 'nemo': # We only support passing include paths to fparser2 and it's # only the NEMO API that uses fparser2 currently. print( "Setting the search path for Fortran include files " "(-I/--include) is only supported for the 'nemo' API.", file=sys.stderr) exit(1) # The Configuration manager checks that the supplied path(s) is/are # valid so protect with a try try: if args.include: Config.get().include_paths = args.include else: # Default is to instruct fparser2 to look in the directory # containing the file being parsed Config.get().include_paths = ["./"] except ConfigurationError as err: print(str(err), file=sys.stderr) exit(1) try: alg, psy = generate(args.filename, api=api, kernel_path=args.directory, script_name=args.script, line_length=args.limit, distributed_memory=args.dist_mem, kern_out_path=kern_out_path, kern_naming=args.kernel_renaming) except NoInvokesError: _, exc_value, _ = sys.exc_info() print("Warning: {0}".format(exc_value)) # no invoke calls were found in the algorithm file so we need # not need to process it, or generate any psy layer code so # output the original algorithm file and set the psy file to # be empty alg_file = open(args.filename) alg = alg_file.read() psy = "" except (OSError, IOError, ParseError, GenerationError, RuntimeError): _, exc_value, _ = sys.exc_info() print(exc_value, file=sys.stderr) exit(1) except Exception: # pylint: disable=broad-except print("Error, unexpected exception, please report to the authors:", file=sys.stderr) exc_type, exc_value, exc_tb = sys.exc_info() print("Description ...", file=sys.stderr) print(exc_value, file=sys.stderr) print("Type ...", file=sys.stderr) print(exc_type, file=sys.stderr) print("Stacktrace ...", file=sys.stderr) traceback.print_tb(exc_tb, limit=20, file=sys.stderr) exit(1) if args.limit: fll = FortLineLength() psy_str = fll.process(str(psy)) alg_str = fll.process(str(alg)) else: psy_str = str(psy) alg_str = str(alg) if args.oalg is not None: my_file = open(args.oalg, "w") my_file.write(alg_str) my_file.close() else: print("Transformed algorithm code:\n%s" % alg_str) if not psy_str: # empty file so do not output anything pass elif args.opsy is not None: my_file = open(args.opsy, "w") my_file.write(psy_str) my_file.close() else: print("Generated psy layer code:\n", psy_str)
def main(args): ''' Parses and checks the command line arguments, calls the generate function if all is well, catches any errors and outputs the results ''' # pylint: disable=too-many-statements parser = argparse.ArgumentParser( description='Run the PSyclone code generator on a particular file') parser.add_argument('-oalg', help='filename of transformed algorithm code') parser.add_argument('-opsy', help='filename of generated PSy code') parser.add_argument('-api', default=DEFAULTAPI, help='choose a particular api from {0}, ' 'default {1}'.format(str(SUPPORTEDAPIS), DEFAULTAPI)) parser.add_argument('filename', help='algorithm-layer source code') parser.add_argument('-s', '--script', help='filename of a PSyclone' ' optimisation script') parser.add_argument('-d', '--directory', default="", help='path to root of directory ' 'structure containing kernel source code') parser.add_argument('-l', '--limit', dest='limit', action='store_true', default=False, help='limit the fortran line length to 132 characters') parser.add_argument('-dm', '--dist_mem', dest='dist_mem', action='store_true', help='generate distributed memory code') parser.add_argument('-nodm', '--no_dist_mem', dest='dist_mem', action='store_false', help='do not generate distributed memory code') parser.set_defaults(dist_mem=DISTRIBUTED_MEMORY) parser.add_argument( '-v', '--version', dest='version', action="store_true", help='Display version information ({0})'.format(__VERSION__)) args = parser.parse_args(args) if args.api not in SUPPORTEDAPIS: print "Unsupported API '{0}' specified. Supported API's are "\ "{1}.".format(args.api, SUPPORTEDAPIS) exit(1) if args.version: print "PSyclone version: {0}".format(__VERSION__) # pylint: disable=broad-except try: alg, psy = generate(args.filename, api=args.api, kernel_path=args.directory, script_name=args.script, line_length=args.limit, distributed_memory=args.dist_mem) except NoInvokesError: _, exc_value, _ = sys.exc_info() print "Warning: {0}".format(exc_value) # no invoke calls were found in the algorithm file so we need # not need to process it, or generate any psy layer code so # output the original algorithm file and set the psy file to # be empty alg_file = open(args.filename) alg = alg_file.read() psy = "" except (OSError, IOError, ParseError, GenerationError, RuntimeError): _, exc_value, _ = sys.exc_info() print exc_value exit(1) except Exception: print "Error, unexpected exception, please report to the authors:" exc_type, exc_value, exc_tb = sys.exc_info() print "Description ..." print exc_value print "Type ..." print exc_type print "Stacktrace ..." traceback.print_tb(exc_tb, limit=10, file=sys.stdout) exit(1) if args.limit: fll = FortLineLength() psy_str = fll.process(str(psy)) alg_str = fll.process(str(alg)) else: psy_str = str(psy) alg_str = str(alg) if args.oalg is not None: my_file = open(args.oalg, "w") my_file.write(alg_str) my_file.close() else: print "Transformed algorithm code:\n", alg_str if not psy_str: # empty file so do not output anything pass elif args.opsy is not None: my_file = open(args.opsy, "w") my_file.write(psy_str) my_file.close() else: print "Generated psy layer code:\n", psy_str