def main(argsl: Optional[List[str]]=None, args: Optional[argparse.Namespace]=None, job_order_object: Optional[CWLObjectType]=None, stdin: IO[Any]=sys.stdin, stdout: Optional[Union[(TextIO, StreamWriter)]]=None, stderr: IO[Any]=sys.stderr, versionfunc: Callable[([], str)]=versionstring, logger_handler: Optional[logging.Handler]=None, custom_schema_callback: Optional[Callable[([], None)]]=None, executor: Optional[JobExecutor]=None, loadingContext: Optional[LoadingContext]=None, runtimeContext: Optional[RuntimeContext]=None, input_required: bool=True) -> int:
    if (not stdout):
        if (hasattr(sys.stdout, 'encoding') and (sys.stdout.encoding.upper() not in ('UTF-8', 'UTF8'))):
            if hasattr(sys.stdout, 'detach'):
                stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
            else:
                stdout = getwriter('utf-8')(sys.stdout)
        else:
            stdout = sys.stdout
    _logger.removeHandler(defaultStreamHandler)
    stderr_handler = logger_handler
    if (stderr_handler is not None):
        _logger.addHandler(stderr_handler)
    else:
        coloredlogs.install(logger=_logger, stream=stderr)
        stderr_handler = _logger.handlers[(- 1)]
    workflowobj = None
    prov_log_handler: Optional[logging.StreamHandler[ProvOut]] = None
    try:
        if (args is None):
            if (argsl is None):
                argsl = sys.argv[1:]
            addl = []
            if ('CWLTOOL_OPTIONS' in os.environ):
                addl = os.environ['CWLTOOL_OPTIONS'].split(' ')
            parser = arg_parser()
            argcomplete.autocomplete(parser)
            args = parser.parse_args((addl + argsl))
            if args.record_container_id:
                if (not args.cidfile_dir):
                    args.cidfile_dir = os.getcwd()
                del args.record_container_id
        if (runtimeContext is None):
            runtimeContext = RuntimeContext(vars(args))
        else:
            runtimeContext = runtimeContext.copy()
        for (key, val) in get_default_args().items():
            if (not hasattr(args, key)):
                setattr(args, key, val)
        configure_logging(stderr_handler, args.quiet, runtimeContext.debug, args.enable_color, args.timestamps)
        if args.version:
            print(versionfunc(), file=stdout)
            return 0
        _logger.info(versionfunc())
        if args.print_supported_versions:
            print('\n'.join(supported_cwl_versions(args.enable_dev)), file=stdout)
            return 0
        if (not args.workflow):
            if os.path.isfile('CWLFile'):
                args.workflow = 'CWLFile'
            else:
                _logger.error('CWL document required, no input file was provided')
                parser.print_help(stderr)
                return 1
        if args.ga4gh_tool_registries:
            ga4gh_tool_registries[:] = args.ga4gh_tool_registries
        if (not args.enable_ga4gh_tool_registry):
            del ga4gh_tool_registries[:]
        if (args.mpi_config_file is not None):
            runtimeContext.mpi_config = MpiConfig.load(args.mpi_config_file)
        setup_schema(args, custom_schema_callback)
        prov_log_stream: Optional[Union[(io.TextIOWrapper, WritableBagFile)]] = None
        if args.provenance:
            if (argsl is None):
                raise Exception('argsl cannot be None')
            try:
                (prov_log_stream, prov_log_handler) = setup_provenance(args, argsl, runtimeContext)
            except ArgumentException:
                return 1
        loadingContext = setup_loadingContext(loadingContext, runtimeContext, args)
        (uri, tool_file_uri) = resolve_tool_uri(args.workflow, resolver=loadingContext.resolver, fetcher_constructor=loadingContext.fetcher_constructor)
        try_again_msg = ('' if args.debug else ', try again with --debug for more information')
        try:
            (job_order_object, input_basedir, jobloader) = load_job_order(args, stdin, loadingContext.fetcher_constructor, loadingContext.overrides_list, tool_file_uri)
            if args.overrides:
                loadingContext.overrides_list.extend(load_overrides(file_uri(os.path.abspath(args.overrides)), tool_file_uri))
            (loadingContext, workflowobj, uri) = fetch_document(uri, loadingContext)
            if (args.print_deps and loadingContext.loader):
                printdeps(workflowobj, loadingContext.loader, stdout, args.relative_deps, uri)
                return 0
            (loadingContext, uri) = resolve_and_validate_document(loadingContext, workflowobj, uri, preprocess_only=(args.print_pre or args.pack), skip_schemas=args.skip_schemas)
            if (loadingContext.loader is None):
                raise Exception('Impossible code path.')
            (processobj, metadata) = loadingContext.loader.resolve_ref(uri)
            processobj = cast(Union[(CommentedMap, CommentedSeq)], processobj)
            if args.pack:
                print(print_pack(loadingContext, uri), file=stdout)
                return 0
            if (args.provenance and runtimeContext.research_obj):
                runtimeContext.research_obj.packed_workflow(print_pack(loadingContext, uri))
            if args.print_pre:
                print(json_dumps(processobj, indent=4, sort_keys=True, separators=(',', ': '), default=str), file=stdout)
                return 0
            try:
                tool = make_tool(uri, loadingContext)
            except GraphTargetMissingException as main_missing_exc:
                if args.validate:
                    logging.warn('File contains $graph of multiple objects and no default process (#main). Validating all objects:')
                    for entry in workflowobj['$graph']:
                        entry_id = entry['id']
                        make_tool(entry_id, loadingContext)
                        print(f'{entry_id} is valid CWL.', file=stdout)
                else:
                    raise main_missing_exc
            if args.make_template:
                make_template(tool)
                return 0
            if args.validate:
                print(f'{args.workflow} is valid CWL.', file=stdout)
                return 0
            if args.print_rdf:
                print(printrdf(tool, loadingContext.loader.ctx, args.rdf_serializer), file=stdout)
                return 0
            if args.print_dot:
                printdot(tool, loadingContext.loader.ctx, stdout)
                return 0
            if args.print_targets:
                print_targets(tool, stdout, loadingContext)
                return 0
            if args.target:
                ctool = choose_target(args, tool, loadingContext)
                if (ctool is None):
                    return 1
                else:
                    tool = ctool
            elif args.single_step:
                ctool = choose_step(args, tool, loadingContext)
                if (ctool is None):
                    return 1
                else:
                    tool = ctool
            elif args.single_process:
                ctool = choose_process(args, tool, loadingContext)
                if (ctool is None):
                    return 1
                else:
                    tool = ctool
            if args.print_subgraph:
                if ('name' in tool.tool):
                    del tool.tool['name']
                print(json_dumps(tool.tool, indent=4, sort_keys=True, separators=(',', ': '), default=str), file=stdout)
                return 0
        except ValidationException as exc:
            _logger.error('Tool definition failed validation:\n%s', str(exc), exc_info=args.debug)
            return 1
        except (RuntimeError, WorkflowException) as exc:
            _logger.error('Tool definition failed initialization:\n%s', str(exc), exc_info=args.debug)
            return 1
        except Exception as exc:
            _logger.error("I'm sorry, I couldn't load this CWL file%s.\nThe error was: %s", try_again_msg, (str(exc) if (not args.debug) else ''), exc_info=args.debug)
            return 1
        if isinstance(tool, int):
            return tool
        if (sys.platform == 'darwin'):
            default_mac_path = '/private/tmp/docker_tmp'
            if (runtimeContext.tmp_outdir_prefix == DEFAULT_TMP_PREFIX):
                runtimeContext.tmp_outdir_prefix = default_mac_path
            if (runtimeContext.tmpdir_prefix == DEFAULT_TMP_PREFIX):
                runtimeContext.tmpdir_prefix = default_mac_path
        if (check_working_directories(runtimeContext) is not None):
            return 1
        if args.cachedir:
            if (args.move_outputs == 'move'):
                runtimeContext.move_outputs = 'copy'
            runtimeContext.tmp_outdir_prefix = args.cachedir
        runtimeContext.log_dir = args.log_dir
        runtimeContext.secret_store = getdefault(runtimeContext.secret_store, SecretStore())
        runtimeContext.make_fs_access = getdefault(runtimeContext.make_fs_access, StdFsAccess)
        if (not executor):
            if args.parallel:
                temp_executor = MultithreadedJobExecutor()
                runtimeContext.select_resources = temp_executor.select_resources
                real_executor = temp_executor
            else:
                real_executor = SingleJobExecutor()
        else:
            real_executor = executor
        try:
            runtimeContext.basedir = input_basedir
            if isinstance(tool, ProcessGenerator):
                tfjob_order = {}
                if loadingContext.jobdefaults:
                    tfjob_order.update(loadingContext.jobdefaults)
                if job_order_object:
                    tfjob_order.update(job_order_object)
                (tfout, tfstatus) = real_executor(tool.embedded_tool, tfjob_order, runtimeContext)
                if ((not tfout) or (tfstatus != 'success')):
                    raise WorkflowException('ProcessGenerator failed to generate workflow')
                (tool, job_order_object) = tool.result(tfjob_order, tfout, runtimeContext)
                if (not job_order_object):
                    job_order_object = None
            try:
                initialized_job_order_object = init_job_order(job_order_object, args, tool, jobloader, stdout, print_input_deps=args.print_input_deps, relative_deps=args.relative_deps, make_fs_access=runtimeContext.make_fs_access, input_basedir=input_basedir, secret_store=runtimeContext.secret_store, input_required=input_required, runtime_context=runtimeContext)
            except SystemExit as err:
                return err.code
            del args.workflow
            del args.job_order
            conf_file = getattr(args, 'beta_dependency_resolvers_configuration', None)
            use_conda_dependencies = getattr(args, 'beta_conda_dependencies', None)
            if (conf_file or use_conda_dependencies):
                runtimeContext.job_script_provider = DependenciesConfiguration(args)
            else:
                runtimeContext.find_default_container = functools.partial(find_default_container, default_container=runtimeContext.default_container, use_biocontainers=args.beta_use_biocontainers)
            (out, status) = real_executor(tool, initialized_job_order_object, runtimeContext, logger=_logger)
            if (out is not None):
                if (runtimeContext.research_obj is not None):
                    runtimeContext.research_obj.create_job(out, True)

                    def remove_at_id(doc: CWLObjectType) -> None:
                        for key in list(doc.keys()):
                            if (key == '@id'):
                                del doc[key]
                            else:
                                value = doc[key]
                                if isinstance(value, MutableMapping):
                                    remove_at_id(value)
                                elif isinstance(value, MutableSequence):
                                    for entry in value:
                                        if isinstance(entry, MutableMapping):
                                            remove_at_id(entry)
                    remove_at_id(out)
                    visit_class(out, ('File',), functools.partial(add_sizes, runtimeContext.make_fs_access('')))

                def loc_to_path(obj: CWLObjectType) -> None:
                    for field in ('path', 'nameext', 'nameroot', 'dirname'):
                        if (field in obj):
                            del obj[field]
                    if cast(str, obj['location']).startswith('file://'):
                        obj['path'] = uri_file_path(cast(str, obj['location']))
                visit_class(out, ('File', 'Directory'), loc_to_path)
                visit_class(out, ('File',), MutationManager().unset_generation)
                print(json_dumps(out, indent=4, ensure_ascii=False, default=str), file=stdout)
                if hasattr(stdout, 'flush'):
                    stdout.flush()
            if (status != 'success'):
                _logger.warning('Final process status is %s', status)
                return 1
            _logger.info('Final process status is %s', status)
            return 0
        except ValidationException as exc:
            _logger.error('Input object failed validation:\n%s', str(exc), exc_info=args.debug)
            return 1
        except UnsupportedRequirement as exc:
            _logger.error('Workflow or tool uses unsupported feature:\n%s', str(exc), exc_info=args.debug)
            return 33
        except WorkflowException as exc:
            _logger.error('Workflow error%s:\n%s', try_again_msg, strip_dup_lineno(str(exc)), exc_info=args.debug)
            return 1
        except Exception as exc:
            _logger.error('Unhandled error%s:\n  %s', try_again_msg, str(exc), exc_info=args.debug)
            return 1
    finally:
        if (args and runtimeContext and runtimeContext.research_obj and workflowobj and loadingContext):
            research_obj = runtimeContext.research_obj
            if (loadingContext.loader is not None):
                research_obj.generate_snapshot(prov_deps(workflowobj, loadingContext.loader, uri))
            else:
                _logger.warning('Unable to generate provenance snapshot  due to missing loadingContext.loader.')
            if (prov_log_handler is not None):
                _logger.debug('[provenance] Closing provenance log file %s', prov_log_handler)
                _logger.removeHandler(prov_log_handler)
                prov_log_handler.flush()
                if prov_log_stream:
                    prov_log_stream.close()
                prov_log_handler.close()
            research_obj.close(args.provenance)
        _logger.removeHandler(stderr_handler)
        _logger.addHandler(defaultStreamHandler)
def main(argsl: Optional[List[str]]=None, args: Optional[argparse.Namespace]=None, job_order_object: Optional[CWLObjectType]=None, stdin: IO[Any]=sys.stdin, stdout: Optional[Union[(TextIO, StreamWriter)]]=None, stderr: IO[Any]=sys.stderr, versionfunc: Callable[([], str)]=versionstring, logger_handler: Optional[logging.Handler]=None, custom_schema_callback: Optional[Callable[([], None)]]=None, executor: Optional[JobExecutor]=None, loadingContext: Optional[LoadingContext]=None, runtimeContext: Optional[RuntimeContext]=None, input_required: bool=True) -> int:
    if (not stdout):
        if (hasattr(sys.stdout, 'encoding') and (sys.stdout.encoding.upper() not in ('UTF-8', 'UTF8'))):
            if hasattr(sys.stdout, 'detach'):
                stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
            else:
                stdout = getwriter('utf-8')(sys.stdout)
        else:
            stdout = sys.stdout
    _logger.removeHandler(defaultStreamHandler)
    stderr_handler = logger_handler
    if (stderr_handler is not None):
        _logger.addHandler(stderr_handler)
    else:
        coloredlogs.install(logger=_logger, stream=stderr)
        stderr_handler = _logger.handlers[(- 1)]
    workflowobj = None
    prov_log_handler: Optional[logging.StreamHandler[ProvOut]] = None
    try:
        if (args is None):
            if (argsl is None):
                argsl = sys.argv[1:]
            addl = []
            if ('CWLTOOL_OPTIONS' in os.environ):
                addl = os.environ['CWLTOOL_OPTIONS'].split(' ')
            parser = arg_parser()
            argcomplete.autocomplete(parser)
            args = parser.parse_args((addl + argsl))
            if args.record_container_id:
                if (not args.cidfile_dir):
                    args.cidfile_dir = os.getcwd()
                del args.record_container_id
        if (runtimeContext is None):
            runtimeContext = RuntimeContext(vars(args))
        else:
            runtimeContext = runtimeContext.copy()
        for (key, val) in get_default_args().items():
            if (not hasattr(args, key)):
                setattr(args, key, val)
        configure_logging(stderr_handler, args.quiet, runtimeContext.debug, args.enable_color, args.timestamps)
        if args.version:
            print(versionfunc(), file=stdout)
            return 0
        _logger.info(versionfunc())
        if args.print_supported_versions:
            print('\n'.join(supported_cwl_versions(args.enable_dev)), file=stdout)
            return 0
        if (not args.workflow):
            if os.path.isfile('CWLFile'):
                args.workflow = 'CWLFile'
            else:
                _logger.error('CWL document required, no input file was provided')
                parser.print_help(stderr)
                return 1
        if args.ga4gh_tool_registries:
            ga4gh_tool_registries[:] = args.ga4gh_tool_registries
        if (not args.enable_ga4gh_tool_registry):
            del ga4gh_tool_registries[:]
        if (args.mpi_config_file is not None):
            runtimeContext.mpi_config = MpiConfig.load(args.mpi_config_file)
        setup_schema(args, custom_schema_callback)
        prov_log_stream: Optional[Union[(io.TextIOWrapper, WritableBagFile)]] = None
        if args.provenance:
            if (argsl is None):
                raise Exception('argsl cannot be None')
            try:
                (prov_log_stream, prov_log_handler) = setup_provenance(args, argsl, runtimeContext)
            except ArgumentException:
                return 1
        loadingContext = setup_loadingContext(loadingContext, runtimeContext, args)
        (uri, tool_file_uri) = resolve_tool_uri(args.workflow, resolver=loadingContext.resolver, fetcher_constructor=loadingContext.fetcher_constructor)
        try_again_msg = ( if args.debug else ', try again with --debug for more information')
        try:
            (job_order_object, input_basedir, jobloader) = load_job_order(args, stdin, loadingContext.fetcher_constructor, loadingContext.overrides_list, tool_file_uri)
            if args.overrides:
                loadingContext.overrides_list.extend(load_overrides(file_uri(os.path.abspath(args.overrides)), tool_file_uri))
            (loadingContext, workflowobj, uri) = fetch_document(uri, loadingContext)
            if (args.print_deps and loadingContext.loader):
                printdeps(workflowobj, loadingContext.loader, stdout, args.relative_deps, uri)
                return 0
            (loadingContext, uri) = resolve_and_validate_document(loadingContext, workflowobj, uri, preprocess_only=(args.print_pre or args.pack), skip_schemas=args.skip_schemas)
            if (loadingContext.loader is None):
                raise Exception('Impossible code path.')
            (processobj, metadata) = loadingContext.loader.resolve_ref(uri)
            processobj = cast(Union[(CommentedMap, CommentedSeq)], processobj)
            if args.pack:
                print(print_pack(loadingContext, uri), file=stdout)
                return 0
            if (args.provenance and runtimeContext.research_obj):
                runtimeContext.research_obj.packed_workflow(print_pack(loadingContext, uri))
            if args.print_pre:
                print(json_dumps(processobj, indent=4, sort_keys=True, separators=(',', ': '), default=str), file=stdout)
                return 0
            try:
                tool = make_tool(uri, loadingContext)
            except GraphTargetMissingException as main_missing_exc:
                if args.validate:
                    logging.warn('File contains $graph of multiple objects and no default process (#main). Validating all objects:')
                    for entry in workflowobj['$graph']:
                        entry_id = entry['id']
                        make_tool(entry_id, loadingContext)
                        print(f'{entry_id} is valid CWL.', file=stdout)
                else:
                    raise main_missing_exc
            if args.make_template:
                make_template(tool)
                return 0
            if args.validate:
                print(f'{args.workflow} is valid CWL.', file=stdout)
                return 0
            if args.print_rdf:
                print(printrdf(tool, loadingContext.loader.ctx, args.rdf_serializer), file=stdout)
                return 0
            if args.print_dot:
                printdot(tool, loadingContext.loader.ctx, stdout)
                return 0
            if args.print_targets:
                print_targets(tool, stdout, loadingContext)
                return 0
            if args.target:
                ctool = choose_target(args, tool, loadingContext)
                if (ctool is None):
                    return 1
                else:
                    tool = ctool
            elif args.single_step:
                ctool = choose_step(args, tool, loadingContext)
                if (ctool is None):
                    return 1
                else:
                    tool = ctool
            elif args.single_process:
                ctool = choose_process(args, tool, loadingContext)
                if (ctool is None):
                    return 1
                else:
                    tool = ctool
            if args.print_subgraph:
                if ('name' in tool.tool):
                    del tool.tool['name']
                print(json_dumps(tool.tool, indent=4, sort_keys=True, separators=(',', ': '), default=str), file=stdout)
                return 0
        except ValidationException as exc:
            _logger.error('Tool definition failed validation:\n%s', str(exc), exc_info=args.debug)
            return 1
        except (RuntimeError, WorkflowException) as exc:
            _logger.error('Tool definition failed initialization:\n%s', str(exc), exc_info=args.debug)
            return 1
        except Exception as exc:
            _logger.error("I'm sorry, I couldn't load this CWL file%s.\nThe error was: %s", try_again_msg, (str(exc) if (not args.debug) else ), exc_info=args.debug)
            return 1
        if isinstance(tool, int):
            return tool
        if (sys.platform == 'darwin'):
            default_mac_path = '/private/tmp/docker_tmp'
            if (runtimeContext.tmp_outdir_prefix == DEFAULT_TMP_PREFIX):
                runtimeContext.tmp_outdir_prefix = default_mac_path
            if (runtimeContext.tmpdir_prefix == DEFAULT_TMP_PREFIX):
                runtimeContext.tmpdir_prefix = default_mac_path
        if (check_working_directories(runtimeContext) is not None):
            return 1
        if args.cachedir:
            if (args.move_outputs == 'move'):
                runtimeContext.move_outputs = 'copy'
            runtimeContext.tmp_outdir_prefix = args.cachedir
        runtimeContext.log_dir = args.log_dir
        runtimeContext.secret_store = getdefault(runtimeContext.secret_store, SecretStore())
        runtimeContext.make_fs_access = getdefault(runtimeContext.make_fs_access, StdFsAccess)
        if (not executor):
            if args.parallel:
                temp_executor = MultithreadedJobExecutor()
                runtimeContext.select_resources = temp_executor.select_resources
                real_executor = temp_executor
            else:
                real_executor = SingleJobExecutor()
        else:
            real_executor = executor
        try:
            runtimeContext.basedir = input_basedir
            if isinstance(tool, ProcessGenerator):
                tfjob_order = {}
                if loadingContext.jobdefaults:
                    tfjob_order.update(loadingContext.jobdefaults)
                if job_order_object:
                    tfjob_order.update(job_order_object)
                (tfout, tfstatus) = real_executor(tool.embedded_tool, tfjob_order, runtimeContext)
                if ((not tfout) or (tfstatus != 'success')):
                    raise WorkflowException('ProcessGenerator failed to generate workflow')
                (tool, job_order_object) = tool.result(tfjob_order, tfout, runtimeContext)
                if (not job_order_object):
                    job_order_object = None
            try:
                initialized_job_order_object = init_job_order(job_order_object, args, tool, jobloader, stdout, print_input_deps=args.print_input_deps, relative_deps=args.relative_deps, make_fs_access=runtimeContext.make_fs_access, input_basedir=input_basedir, secret_store=runtimeContext.secret_store, input_required=input_required, runtime_context=runtimeContext)
            except SystemExit as err:
                return err.code
            del args.workflow
            del args.job_order
            conf_file = getattr(args, 'beta_dependency_resolvers_configuration', None)
            use_conda_dependencies = getattr(args, 'beta_conda_dependencies', None)
            if (conf_file or use_conda_dependencies):
                runtimeContext.job_script_provider = DependenciesConfiguration(args)
            else:
                runtimeContext.find_default_container = functools.partial(find_default_container, default_container=runtimeContext.default_container, use_biocontainers=args.beta_use_biocontainers)
            (out, status) = real_executor(tool, initialized_job_order_object, runtimeContext, logger=_logger)
            if (out is not None):
                if (runtimeContext.research_obj is not None):
                    runtimeContext.research_obj.create_job(out, True)

                    def remove_at_id(doc: CWLObjectType) -> None:
                        for key in list(doc.keys()):
                            if (key == '@id'):
                                del doc[key]
                            else:
                                value = doc[key]
                                if isinstance(value, MutableMapping):
                                    remove_at_id(value)
                                elif isinstance(value, MutableSequence):
                                    for entry in value:
                                        if isinstance(entry, MutableMapping):
                                            remove_at_id(entry)
                    remove_at_id(out)
                    visit_class(out, ('File',), functools.partial(add_sizes, runtimeContext.make_fs_access()))

                def loc_to_path(obj: CWLObjectType) -> None:
                    for field in ('path', 'nameext', 'nameroot', 'dirname'):
                        if (field in obj):
                            del obj[field]
                    if cast(str, obj['location']).startswith('file://'):
                        obj['path'] = uri_file_path(cast(str, obj['location']))
                visit_class(out, ('File', 'Directory'), loc_to_path)
                visit_class(out, ('File',), MutationManager().unset_generation)
                print(json_dumps(out, indent=4, ensure_ascii=False, default=str), file=stdout)
                if hasattr(stdout, 'flush'):
                    stdout.flush()
            if (status != 'success'):
                _logger.warning('Final process status is %s', status)
                return 1
            _logger.info('Final process status is %s', status)
            return 0
        except ValidationException as exc:
            _logger.error('Input object failed validation:\n%s', str(exc), exc_info=args.debug)
            return 1
        except UnsupportedRequirement as exc:
            _logger.error('Workflow or tool uses unsupported feature:\n%s', str(exc), exc_info=args.debug)
            return 33
        except WorkflowException as exc:
            _logger.error('Workflow error%s:\n%s', try_again_msg, strip_dup_lineno(str(exc)), exc_info=args.debug)
            return 1
        except Exception as exc:
            _logger.error('Unhandled error%s:\n  %s', try_again_msg, str(exc), exc_info=args.debug)
            return 1
    finally:
        if (args and runtimeContext and runtimeContext.research_obj and workflowobj and loadingContext):
            research_obj = runtimeContext.research_obj
            if (loadingContext.loader is not None):
                research_obj.generate_snapshot(prov_deps(workflowobj, loadingContext.loader, uri))
            else:
                _logger.warning('Unable to generate provenance snapshot  due to missing loadingContext.loader.')
            if (prov_log_handler is not None):
                _logger.debug('[provenance] Closing provenance log file %s', prov_log_handler)
                _logger.removeHandler(prov_log_handler)
                prov_log_handler.flush()
                if prov_log_stream:
                    prov_log_stream.close()
                prov_log_handler.close()
            research_obj.close(args.provenance)
        _logger.removeHandler(stderr_handler)
        _logger.addHandler(defaultStreamHandler)