Handles calling this module as a script

    :return: None
977406
def main():
    
    log = logging.getLogger(mod_logger + '.main')
    parser = argparse.ArgumentParser(description='This Python module retrieves artifacts from Nexus.')
    parser.add_argument('-u', '--url', help='Nexus Server URL', required=False)
    parser.add_argument('-g', '--groupId', help='Group ID', required=True)
    parser.add_argument('-a', '--artifactId', help='Artifact ID', required=True)
    parser.add_argument('-v', '--version', help='Artifact Version', required=True)
    parser.add_argument('-c', '--classifier', help='Artifact Classifier', required=False)
    parser.add_argument('-p', '--packaging', help='Artifact Packaging', required=True)
    parser.add_argument('-r', '--repo', help='Nexus repository name', required=False)
    parser.add_argument('-d', '--destinationDir', help='Directory to download to', required=True)
    parser.add_argument('-n', '--username', help='Directory to download to', required=True)
    parser.add_argument('-w', '--password', help='Directory to download to', required=True)
    args = parser.parse_args()
    try:
        get_artifact(
            nexus_url=args.url,
            group_id=args.groupId,
            artifact_id=args.artifactId,
            version=args.version,
            classifier=args.classifier,
            packaging=args.packaging,
            repo=args.repo,
            destination_dir=args.destinationDir,
            username=args.username,
            password=args.password
        )
    except Exception as e:
        msg = 'Caught exception {n}, unable for download artifact from Nexus\n{s}'.format(
            n=e.__class__.__name__, s=e)
        log.error(msg)
        return
583556
function ScriptManager() {

  // child process
  this.ps = null;

  // script execution limit in milliseconds
  this._limit = 5000;

  // flag determining if a script is busy executing
  this._busy = false;

  // flag determining if script execution issued
  // any write commands
  this._written = false;

  // currently executing script name
  this._script = null;

  // injected reference to the command handlers
  this._commands = {};

  // script limit timeout listener
  this.onTimeout = this.onTimeout.bind(this);
}
540108
def assert_script_in_current_directory():
  """"""

  script = sys.argv[0]
  assert os.path.abspath(os.path.dirname(script)) == os.path.abspath(
    '.'), f"Change into directory of script {script} and run again."
593847
def run_script_from_macro(self, args):
        
        self.__macroArgs = args["args"].split(',')
        
        try:
            self.run_script(args["name"])
        except Exception as e:
            self.set_return_value("{ERROR: %s}" % str(e))
288331
def write(self, script):
        # type: (str) -> None
        
        if self._closed:
            raise IOError('tried to write to closed connection')
        script = script.strip()
        if script:
            assert self._parentout is not None
            self._parentout.write(script)
            self._parentout.write('\n')
145767
def start_current_script():
    """"""
    current_editor = get_workbench().get_editor_notebook().get_current_editor()
    code = current_editor.get_text_widget().get("1.0", "end")
    try:
        ast.parse(code)
        #Return None, if script is not saved and user closed file saving window, otherwise return file name.
        py_file = get_workbench().get_current_editor().save_file(False)
        if py_file is None:
            return
        start(py_file)
    except Exception:
        error_msg = traceback.format_exc(0)+'\n'
        showerror("Error", error_msg)
474196
def run_script(scriptfile):
    ''''''
    try:
        f = open(scriptfile, mode='r')
    except Exception:
        return
    mpstate.console.writeln("Running script %s" % scriptfile)
    for line in f:
        line = line.strip()
        if line == "" or line.startswith('#'):
            continue
        if line.startswith('@'):
            line = line[1:]
        else:
            mpstate.console.writeln("-> %s" % line)
        process_stdin(line)
    f.close()
1111170
def run_script(self, filename=None, silent=False, set_focus=False,
                   args=None):
        """"""
        if filename is None:
            self.shell.interpreter.restore_stds()
            filename, _selfilter = getopenfilename(
                    self, _("Run Python script"), getcwd_or_home(),
                    _("Python scripts")+" (*.py ; *.pyw ; *.ipy)")
            self.shell.interpreter.redirect_stds()
            if filename:
                os.chdir( osp.dirname(filename) )
                filename = osp.basename(filename)
            else:
                return
        logger.debug("Running script with %s", args)
        filename = osp.abspath(filename)
        rbs = remove_backslashes
        command = "runfile('%s', args='%s')" % (rbs(filename), rbs(args))
        if set_focus:
            self.shell.setFocus()
        if self.dockwidget and not self.ismaximized:
            self.dockwidget.setVisible(True)
            self.dockwidget.raise_()
        self.shell.write(command+'\n')
        self.shell.run_command(command)
806519
def from_caller_module_root():
        ''''''
        import inspect
        all_stack = list(inspect.stack())
        curframe = inspect.currentframe()
        calframe = inspect.getouterframes(curframe, 2)
        module = inspect.getmodule(calframe[1].frame)
        if not module:
            raise RuntimeError('caller is not a module')
        root_module_name = module.__name__.partition('.')[0]
        fullpath = sys.modules[root_module_name].__file__
        return Path(fullpath)
895035
def do_py(self, args: argparse.Namespace) -> bool:
        """"""
        from .pyscript_bridge import PyscriptBridge
        if self._in_py:
            err = "Recursively entering interactive Python consoles is not allowed."
            self.perror(err, traceback_war=False)
            return False

        try:
            self._in_py = True

            # Support the run command even if called prior to invoking an interactive interpreter
            def py_run(filename: str):
                """Run a Python script file in the interactive console.
                :param filename: filename of *.py script file to run
                """
                expanded_filename = os.path.expanduser(filename)

                # cmd_echo defaults to False for scripts. The user can always toggle this value in their script.
                bridge.cmd_echo = False

                try:
                    with open(expanded_filename) as f:
                        interp.runcode(f.read())
                except OSError as ex:
                    error_msg = "Error opening script file '{}': {}".format(expanded_filename, ex)
                    self.perror(error_msg, traceback_war=False)

            def py_quit():
                """Function callable from the interactive Python console to exit that environment"""
                raise EmbeddedConsoleExit

            # Set up Python environment
            bridge = PyscriptBridge(self)
            self.pystate[self.pyscript_name] = bridge
            self.pystate['run'] = py_run
            self.pystate['quit'] = py_quit
            self.pystate['exit'] = py_quit

            if self.locals_in_py:
                self.pystate['self'] = self
            elif 'self' in self.pystate:
                del self.pystate['self']

            localvars = self.pystate
            from code import InteractiveConsole
            interp = InteractiveConsole(locals=localvars)
            interp.runcode('import sys, os;sys.path.insert(0, os.getcwd())')

            # Check if the user is running a Python statement on the command line
            if args.command:
                full_command = args.command
                if args.remainder:
                    full_command += ' ' + ' '.join(args.remainder)

                # Set cmd_echo to True so PyscriptBridge statements like: py app('help')
                # run at the command line will print their output.
                bridge.cmd_echo = True

                # noinspection PyBroadException
                try:
                    interp.runcode(full_command)
                except BaseException:
                    # We don't care about any exception that happened in the interactive console
                    pass

            # If there are no args, then we will open an interactive Python console
            else:
                # Set up readline for Python console
                if rl_type != RlType.NONE:
                    # Save cmd2 history
                    saved_cmd2_history = []
                    for i in range(1, readline.get_current_history_length() + 1):
                        # noinspection PyArgumentList
                        saved_cmd2_history.append(readline.get_history_item(i))

                    readline.clear_history()

                    # Restore py's history
                    for item in self.py_history:
                        readline.add_history(item)

                    if self.use_rawinput and self.completekey:
                        # Set up tab completion for the Python console
                        # rlcompleter relies on the default settings of the Python readline module
                        if rl_type == RlType.GNU:
                            saved_basic_quotes = ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value
                            rl_basic_quote_characters.value = orig_rl_basic_quotes

                            if 'gnureadline' in sys.modules:
                                # rlcompleter imports readline by name, so it won't use gnureadline
                                # Force rlcompleter to use gnureadline instead so it has our settings and history
                                saved_readline = None
                                if 'readline' in sys.modules:
                                    saved_readline = sys.modules['readline']

                                sys.modules['readline'] = sys.modules['gnureadline']

                        saved_delims = readline.get_completer_delims()
                        readline.set_completer_delims(orig_rl_delims)

                        # rlcompleter will not need cmd2's custom display function
                        # This will be restored by cmd2 the next time complete() is called
                        if rl_type == RlType.GNU:
                            readline.set_completion_display_matches_hook(None)
                        elif rl_type == RlType.PYREADLINE:
                            # noinspection PyUnresolvedReferences
                            readline.rl.mode._display_completions = self._display_matches_pyreadline

                        # Save off the current completer and set a new one in the Python console
                        # Make sure it tab completes from its locals() dictionary
                        saved_completer = readline.get_completer()
                        interp.runcode("from rlcompleter import Completer")
                        interp.runcode("import readline")
                        interp.runcode("readline.set_completer(Completer(locals()).complete)")

                # Set up sys module for the Python console
                self._reset_py_display()

                saved_sys_stdout = sys.stdout
                sys.stdout = self.stdout

                saved_sys_stdin = sys.stdin
                sys.stdin = self.stdin

                cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
                instructions = ('End with `Ctrl-D` (Unix) / `Ctrl-Z` (Windows), `quit()`, `exit()`.\n'
                                'Non-Python commands can be issued with: {}("your command")\n'
                                'Run Python code from external script files with: run("script.py")'
                                .format(self.pyscript_name))

                # noinspection PyBroadException
                try:
                    interp.interact(banner="Python {} on {}\n{}\n\n{}\n".
                                    format(sys.version, sys.platform, cprt, instructions))
                except BaseException:
                    # We don't care about any exception that happened in the interactive console
                    pass

                finally:
                    sys.stdout = saved_sys_stdout
                    sys.stdin = saved_sys_stdin

                    # Set up readline for cmd2
                    if rl_type != RlType.NONE:
                        # Save py's history
                        self.py_history.clear()
                        for i in range(1, readline.get_current_history_length() + 1):
                            # noinspection PyArgumentList
                            self.py_history.append(readline.get_history_item(i))

                        readline.clear_history()

                        # Restore cmd2's history
                        for item in saved_cmd2_history:
                            readline.add_history(item)

                        if self.use_rawinput and self.completekey:
                            # Restore cmd2's tab completion settings
                            readline.set_completer(saved_completer)
                            readline.set_completer_delims(saved_delims)

                            if rl_type == RlType.GNU:
                                rl_basic_quote_characters.value = saved_basic_quotes

                                if 'gnureadline' in sys.modules:
                                    # Restore what the readline module pointed to
                                    if saved_readline is None:
                                        del(sys.modules['readline'])
                                    else:
                                        sys.modules['readline'] = saved_readline

        except KeyboardInterrupt:
            pass

        finally:
            self._in_py = False

        return self._should_quit
323628
def script(self):
        """"""
        # The script object is cached, since constructing it may involve
        # a number of string-manipulation operations.
        if getattr(self, '_script', None) is None:
            self._script = self._script__getter()
        return self._script
30677
def run(self):
        
        self.modnames_to_reload = []
        for modname, module in list(sys.modules.items()):
            if modname not in self.previous_modules:
                # Decide if a module can be reloaded or not
                if self.is_module_reloadable(module, modname):
                    self.modnames_to_reload.append(modname)
                    del sys.modules[modname]
                else:
                    continue

        # Report reloaded modules
        if self.verbose and self.modnames_to_reload:
            modnames = self.modnames_to_reload
            _print("\x1b[4;33m%s\x1b[24m%s\x1b[0m"\
                   % ("Reloaded modules", ": "+", ".join(modnames)))
1051013
def script(self, s):
        
        try:
            script = self._network.script.compile(s)
            script_info = self._network.contract.info_for_script(script)
            return Contract(script_info, self._network)
        except Exception:
            return None
1027617
def SoS_exec(script: str, _dict: dict = None,
             return_result: bool = True) -> None:
    ''''''
    if _dict is None:
        _dict = env.sos_dict.dict()

    if not return_result:
        exec(
            compile(script, filename=stmtHash.hash(script), mode='exec'), _dict)
        return None

    try:
        stmts = list(ast.iter_child_nodes(ast.parse(script)))
        if not stmts:
            return
        if isinstance(stmts[-1], ast.Expr):
            # the last one is an expression and we will try to return the results
            # so we first execute the previous statements
            if len(stmts) > 1:
                exec(
                    compile(
                        ast.Module(body=stmts[:-1]),
                        filename=stmtHash.hash(script),
                        mode="exec"), _dict)
            # then we eval the last one
            res = eval(
                compile(
                    ast.Expression(body=stmts[-1].value),
                    filename=stmtHash.hash(script),
                    mode="eval"), _dict)
        else:
            # otherwise we just execute the entire code
            exec(
                compile(script, filename=stmtHash.hash(script), mode='exec'),
                _dict)
            res = None
    except SyntaxError as e:
        raise SyntaxError(f"Invalid code {script}: {e}")

    # if check_readonly:
    #    env.sos_dict.check_readonly_vars()
    return res
1025060
def do_run(self, arg):
        '''  '''
        if not self.arm.is_connected():
            print(self.style.error('Error: ', 'Arm is not connected.'))
            return

        # Load the script.
        try:
            with open(arg) as f:
                lines = [line.strip() for line in f.readlines()]
        except IOError:
            print(self.style.error('Error: ',
                                   'Could not load file \'{}\'.'.format(arg)))
            return

        for line in lines:
            if self.wrapper:
                line = self.wrapper.wrap_input(line)
            self.arm.write(line)
            res = self.arm.read()
            if self.wrapper:
                res = self.wrapper.wrap_output(res)
            print(res)
436496
def run(command=None, *arguments):
    

    if command is None:
        sys.exit('django-shortcuts: No argument was supplied, please specify one.')

    if command in ALIASES:
        command = ALIASES[command]

    if command == 'startproject':
        return call('django-admin.py startproject %s' % ' '.join(arguments), shell=True)

    script_path = os.getcwd()
    while not os.path.exists(os.path.join(script_path, 'manage.py')):
        base_dir = os.path.dirname(script_path)
        if base_dir != script_path:
            script_path = base_dir
        else:
            sys.exit('django-shortcuts: No \'manage.py\' script found in this directory or its parents.')

    return call('%(python)s %(script_path)s %(command)s %(arguments)s' % {
        'python': sys.executable,
        'script_path': os.path.join(script_path, 'manage.py'),
        'command': command or '',
        'arguments': ' '.join(arguments)
    }, shell=True)
1210794
def write_script(self, script_name, contents, mode="t", blockers=()):
        """"""
        self.delete_blockers(  # clean up old .py/.pyw w/o a script
            [os.path.join(self.script_dir, x) for x in blockers]
        )
        log.info("Installing %s script to %s", script_name, self.script_dir)
        target = os.path.join(self.script_dir, script_name)
        self.add_output(target)

        if self.dry_run:
            return

        mask = current_umask()
        ensure_directory(target)
        if os.path.exists(target):
            os.unlink(target)
        with open(target, "w" + mode) as f:
            f.write(contents)
        chmod(target, 0o777 - mask)