当前位置: 首页>>代码示例>>Python>>正文


Python BackgroundJobManager.new方法代码示例

本文整理汇总了Python中IPython.lib.backgroundjobs.BackgroundJobManager.new方法的典型用法代码示例。如果您正苦于以下问题:Python BackgroundJobManager.new方法的具体用法?Python BackgroundJobManager.new怎么用?Python BackgroundJobManager.new使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IPython.lib.backgroundjobs.BackgroundJobManager的用法示例。


在下文中一共展示了BackgroundJobManager.new方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: AnyBodyMagics

# 需要导入模块: from IPython.lib.backgroundjobs import BackgroundJobManager [as 别名]
# 或者: from IPython.lib.backgroundjobs.BackgroundJobManager import new [as 别名]

#.........这里部分代码省略.........
        else:
            folder = os.getcwd()
              
        cell = cell.encode('utf8', 'replace')
        macro = cell if cell.endswith('\n') else cell+'\n'
        macrofile = NamedTemporaryFile(mode='w+b',
                                         prefix ='macro_',
                                         suffix='.anymcr',
                                         dir= folder,
                                         delete = False)
        
        macrofile.write(macro)
        macrofile.flush()

        
        
        
        cmd = [abcpath ,'/d',folder, '--macro=', macrofile.name, '/ni', "1>&2"]        
        
        try:
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, shell= True)
        except OSError as e:
            if e.errno == errno.ENOENT:
                print "Couldn't find program: %r" % cmd[0]
                return
            else:
                raise
        
        if args.bg:
            self.bg_processes.append(p)
            self._gc_bg_processes()
            if args.out:
                self.shell.user_ns[args.out] = p.stderr
            self.job_manager.new(self._run_script, p, macrofile, daemon=True)
            if args.proc:
                self.shell.user_ns[args.proc] = p
            return
        
        random_tag = ''.join( random.sample(string.ascii_uppercase,6) )
        def htmlbox(text):
            raw_html = """<div id="anyscriptbox_{0}" style="height: 120px ; width : auto; border:1px dotted black;padding:0.5em;overflow:auto;background-color:#E0E0E0 ; font:3px Geogia"><font size="2px" face="courier"> {1} </font></div> <script> var myDiv = document.getElementById("anyscriptbox_{0}");
            myDiv.scrollTop = myDiv.scrollHeight;</script> """.format(random_tag, text )
            return HTML(raw_html)
        
        try:
            raw_out = []
            for line in iter(p.stderr.readline,b''):
                line = py3compat.bytes_to_str( line )
                raw_out.append(line)
                if not args.pager:
                    clear_output()
                    display(  htmlbox("<br/>".join( raw_out ) ) )
                #sys.stdout.flush()
                
            if args.pager:
                page("".join(raw_out))
            p.communicate();
                
        except KeyboardInterrupt:
            try:
                p.send_signal(signal.SIGINT)
                time.sleep(0.1)
                if p.poll() is not None:
                    print "Process is interrupted."
                    return
                p.terminate()
开发者ID:melund,项目名称:anybodymagic,代码行数:70,代码来源:anybodymagic.py

示例2: ScriptMagics

# 需要导入模块: from IPython.lib.backgroundjobs import BackgroundJobManager [as 别名]
# 或者: from IPython.lib.backgroundjobs.BackgroundJobManager import new [as 别名]

#.........这里部分代码省略.........
        
        Examples
        --------
        ::
        
            In [1]: %%script bash
               ...: for i in 1 2 3; do
               ...:   echo $i
               ...: done
            1
            2
            3
        """
        argv = arg_split(line, posix = not sys.platform.startswith('win'))
        args, cmd = self.shebang.parser.parse_known_args(argv)
        
        try:
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE)
        except OSError as e:
            if e.errno == errno.ENOENT:
                print("Couldn't find program: %r" % cmd[0])
                return
            else:
                raise
        
        cell = cell.encode('utf8', 'replace')
        if args.bg:
            self.bg_processes.append(p)
            self._gc_bg_processes()
            if args.out:
                self.shell.user_ns[args.out] = p.stdout
            if args.err:
                self.shell.user_ns[args.err] = p.stderr
            self.job_manager.new(self._run_script, p, cell, daemon=True)
            if args.proc:
                self.shell.user_ns[args.proc] = p
            return
        
        try:
            out, err = p.communicate(cell)
        except KeyboardInterrupt:
            try:
                p.send_signal(signal.SIGINT)
                time.sleep(0.1)
                if p.poll() is not None:
                    print("Process is interrupted.")
                    return
                p.terminate()
                time.sleep(0.1)
                if p.poll() is not None:
                    print("Process is terminated.")
                    return
                p.kill()
                print("Process is killed.")
            except OSError:
                pass
            except Exception as e:
                print("Error while terminating subprocess (pid=%i): %s" \
                    % (p.pid, e))
            return
        out = py3compat.bytes_to_str(out)
        err = py3compat.bytes_to_str(err)
        if args.out:
            self.shell.user_ns[args.out] = out
        else:
            sys.stdout.write(out)
开发者ID:pykomke,项目名称:Kurz_Python_KE,代码行数:70,代码来源:script.py

示例3: ScriptMagics

# 需要导入模块: from IPython.lib.backgroundjobs import BackgroundJobManager [as 别名]
# 或者: from IPython.lib.backgroundjobs.BackgroundJobManager import new [as 别名]

#.........这里部分代码省略.........
        help="""Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby'
        
        Only necessary for items in script_magics where the default path will not
        find the right interpreter.
        """
    )
    
    def __init__(self, shell=None):
        Configurable.__init__(self, config=shell.config)
        self._generate_script_magics()
        Magics.__init__(self, shell=shell)
        self.job_manager = BackgroundJobManager()
    
    def _generate_script_magics(self):
        cell_magics = self.magics['cell']
        for name in self.script_magics:
            cell_magics[name] = self._make_script_magic(name)
    
    def _make_script_magic(self, name):
        """make a named magic, that calls %%script with a particular program"""
        # expand to explicit path if necessary:
        script = self.script_paths.get(name, name)
        
        @magic_arguments.magic_arguments()
        @script_args
        def named_script_magic(line, cell):
            # if line, add it as cl-flags
            if line:
                 line = "%s %s" % (script, line)
            else:
                line = script
            return self.shebang(line, cell)
        
        # write a basic docstring:
        named_script_magic.__doc__ = \
        """%%{name} script magic
        
        Run cells with {script} in a subprocess.
        
        This is a shortcut for `%%script {script}`
        """.format(**locals())
        
        return named_script_magic
    
    @magic_arguments.magic_arguments()
    @script_args
    @cell_magic("script")
    def shebang(self, line, cell):
        """Run a cell via a shell command
        
        The `%%script` line is like the #! line of script,
        specifying a program (bash, perl, ruby, etc.) with which to run.
        
        The rest of the cell is run by that program.
        
        Examples
        --------
        ::
        
            In [1]: %%script bash
               ...: for i in 1 2 3; do
               ...:   echo $i
               ...: done
            1
            2
            3
        """
        argv = arg_split(line, posix = not sys.platform.startswith('win'))
        args, cmd = self.shebang.parser.parse_known_args(argv)

        p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE)
        
        cell = cell.encode('utf8', 'replace')
        if args.bg:
            if args.out:
                self.shell.user_ns[args.out] = p.stdout
            if args.err:
                self.shell.user_ns[args.err] = p.stderr
            self.job_manager.new(self._run_script, p, cell)
            return
        
        out, err = p.communicate(cell)
        out = py3compat.bytes_to_str(out)
        err = py3compat.bytes_to_str(err)
        if args.out:
            self.shell.user_ns[args.out] = out
        else:
            sys.stdout.write(out)
            sys.stdout.flush()
        if args.err:
            self.shell.user_ns[args.err] = err
        else:
            sys.stderr.write(err)
            sys.stderr.flush()
    
    def _run_script(self, p, cell):
        """callback for running the script in the background"""
        p.stdin.write(cell)
        p.stdin.close()
        p.wait()
开发者ID:catchmrbharath,项目名称:ipython,代码行数:104,代码来源:script.py


注:本文中的IPython.lib.backgroundjobs.BackgroundJobManager.new方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。