예제 #1
0
def common_doctest_arguments(func):
    commons = [
        argument(
            "-x",
            "--stop",
            default=False,
            action="store_true",
            help="""
            Stop running tests after the first error or failure.
            When this option is specified, the error is recorded
            in IPython shell so that you can debug the error by
            turning on pdb flag before doctest (see ``%%pdb``) or
            use ``%%debug`` magic command afterward.
            """,
        ),
        argument(
            "-v", "--verbose", default=False, action="store_true", help="See :func:`doctest.run_docstring_examples`."
        ),
        argument("-n", "--name", default="NoName", help="See :func:`doctest.run_docstring_examples`."),
        argument("-f", "--file", default="", action="store_true", help="The object to be tested is a file"),
        argument(
            "-o",
            "--options",
            default=0,
            help="""
            Use these doctest options, e.g.
                %%doctest --options=doctest.ELLIPSIS object
            """,
        ),
    ]
    for c in commons:
        func = c(func)
    return func
예제 #2
0
def exec_args(f):
    """decorator for adding block/targets args for execution
    
    applied to %pxconfig and %%px
    """
    args = [
        magic_arguments.argument('-b', '--block', action="store_const",
            const=True, dest='block',
            help="use blocking (sync) execution",
        ),
        magic_arguments.argument('-a', '--noblock', action="store_const",
            const=False, dest='block',
            help="use non-blocking (async) execution",
        ),
        magic_arguments.argument('-t', '--targets', type=str,
            help="specify the targets on which to execute",
        ),
        magic_arguments.argument('--verbose', action="store_const",
            const=True, dest="set_verbose",
            help="print a message at each execution",
        ),
        magic_arguments.argument('--no-verbose', action="store_const",
            const=False, dest="set_verbose",
            help="don't print any messages",
        ),
    ]
    for a in args:
        f = a(f)
    return f
예제 #3
0
def script_args(f):
    """single decorator for adding script args"""
    args = [
        magic_arguments.argument(
            '--out', type=str,
            help="""The variable in which to store stdout from the script.
            If the script is backgrounded, this will be the stdout *pipe*,
            instead of the stderr text itself.
            """
        ),
        magic_arguments.argument(
            '--err', type=str,
            help="""The variable in which to store stderr from the script.
            If the script is backgrounded, this will be the stderr *pipe*,
            instead of the stderr text itself.
            """
        ),
        magic_arguments.argument(
            '--bg', action="store_true",
            help="""Whether to run the script in the background.
            If given, the only way to see the output of the command is
            with --out/err.
            """
        ),
        magic_arguments.argument(
            '--proc', type=str,
            help="""The variable in which to store Popen instance.
            This is used only when --bg option is given.
            """
        ),
    ]
    for arg in args:
        f = arg(f)
    return f
예제 #4
0
def script_args(f):
    """single decorator for adding script args"""
    args = [
        magic_arguments.argument(
            '--out',
            type=str,
            help="""The variable in which to store stdout from the script.
            If the script is backgrounded, this will be the stdout *pipe*,
            instead of the stderr text itself.
            """),
        magic_arguments.argument(
            '--err',
            type=str,
            help="""The variable in which to store stderr from the script.
            If the script is backgrounded, this will be the stderr *pipe*,
            instead of the stderr text itself.
            """),
        magic_arguments.argument(
            '--bg',
            action="store_true",
            help="""Whether to run the script in the background.
            If given, the only way to see the output of the command is
            with --out/err.
            """),
        magic_arguments.argument(
            '--proc',
            type=str,
            help="""The variable in which to store Popen instance.
            This is used only when --bg option is given.
            """),
    ]
    for arg in args:
        f = arg(f)
    return f
예제 #5
0
def common_doctest_arguments(func):
    commons = [
        argument(
            '-x', '--stop', default=False, action='store_true',
            help="""
            Stop running tests after the first error or failure.
            When this option is specified, the error is recorded
            in IPython shell so that you can debug the error by
            turning on pdb flag before doctest (see ``%%pdb``) or
            use ``%%debug`` magic command afterward.
            """,
        ),
        argument(
            '-v', '--verbose', default=False, action='store_true',
            help='See :func:`doctest.run_docstring_examples`.',
        ),
        argument(
            '-n', '--name', default='NoName',
            help='See :func:`doctest.run_docstring_examples`.',
        ),
        argument(
            '-f', '--file', default='', action='store_true',
            help='The object to be tested is a file'
        ),
        argument(
            '-o', '--options', default=0,
            help="""
            Use these doctest options, e.g.
                %%doctest --options=doctest.ELLIPSIS object
            """
        ),
    ]
    for c in commons:
        func = c(func)
    return func
예제 #6
0
파일: magics.py 프로젝트: chebee7i/ipython
def output_args(f):
    """decorator for output-formatting args
    
    applied to %pxresult and %%px
    """
    args = [
        magic_arguments.argument(
            "-r",
            action="store_const",
            dest="groupby",
            const="order",
            help="collate outputs in order (same as group-outputs=order)",
        ),
        magic_arguments.argument(
            "-e",
            action="store_const",
            dest="groupby",
            const="engine",
            help="group outputs by engine (same as group-outputs=engine)",
        ),
        magic_arguments.argument(
            "--group-outputs",
            dest="groupby",
            type=str,
            choices=["engine", "order", "type"],
            default="type",
            help="""Group the outputs in a particular way.
            
            Choices are:
            
            type: group outputs of all engines by type (stdout, stderr, displaypub, etc.).
            
            engine: display all output for each engine together.

            order: like type, but individual displaypub output from each engine is collated.
                For example, if multiple plots are generated by each engine, the first
                figure of each engine will be displayed, then the second of each, etc.
            """,
        ),
        magic_arguments.argument(
            "-o",
            "--out",
            dest="save_name",
            type=str,
            help="""store the AsyncResult object for this computation
                 in the global namespace under this name.
            """,
        ),
    ]
    for a in args:
        f = a(f)
    return f
예제 #7
0
def output_args(f):
    """decorator for output-formatting args

    applied to %pxresult and %%px
    """
    args = [
        magic_arguments.argument(
            '-r',
            action="store_const",
            dest='groupby',
            const='order',
            help="collate outputs in order (same as group-outputs=order)",
        ),
        magic_arguments.argument(
            '-e',
            action="store_const",
            dest='groupby',
            const='engine',
            help="group outputs by engine (same as group-outputs=engine)",
        ),
        magic_arguments.argument(
            '--group-outputs',
            dest='groupby',
            type=str,
            choices=['engine', 'order', 'type'],
            default='type',
            help="""Group the outputs in a particular way.
            
            Choices are:
            
            **type**: group outputs of all engines by type (stdout, stderr, displaypub, etc.).
            **engine**: display all output for each engine together.
            **order**: like type, but individual displaypub output from each engine is collated.
              For example, if multiple plots are generated by each engine, the first
              figure of each engine will be displayed, then the second of each, etc.
            """,
        ),
        magic_arguments.argument(
            '-o',
            '--out',
            dest='save_name',
            type=str,
            help="""store the AsyncResult object for this computation
                 in the global namespace under this name.
            """,
        ),
    ]
    for a in args:
        f = a(f)
    return f
예제 #8
0
    def param_arguments(cls, ggb_ipython_magic):
        # TODO: everything referring to ipython should be removed from this file
        """Arguments common for GeoGebra applets (including
        Java applets, HTML5 applets, etc).
        """
        @functools.wraps(ggb_ipython_magic)
        @argument('--width',
                  type=int,
                  default=1000,
                  help="Width of applet, in pixels")
        @argument('--height',
                  type=int,
                  default=600,
                  help="Height of applet, in pixels")
        @argument('--java_arguments',
                  '--java',
                  default='',
                  help="Arguments to pass to java")
        def wrapped_magic(self, line, cell=None):
            return ggb_ipython_magic(self, line, cell)

        for param in cls.bool_params:
            wrapped_magic = argument('--' + param,
                                     metavar='0/1',
                                     type=int,
                                     help=param)(wrapped_magic)

        return wrapped_magic
예제 #9
0
def script_args(f):
    """single decorator for adding script args"""
    args = [
        magic_arguments.argument(
            "--out",
            type=str,
            help="""The variable in which to store stdout from the script.
            If the script is backgrounded, this will be the stdout *pipe*,
            instead of the stderr text itself and will not be auto closed.
            """,
        ),
        magic_arguments.argument(
            "--err",
            type=str,
            help="""The variable in which to store stderr from the script.
            If the script is backgrounded, this will be the stderr *pipe*,
            instead of the stderr text itself and will not be autoclosed.
            """,
        ),
        magic_arguments.argument(
            "--bg",
            action="store_true",
            help="""Whether to run the script in the background.
            If given, the only way to see the output of the command is
            with --out/err.
            """,
        ),
        magic_arguments.argument(
            "--proc",
            type=str,
            help="""The variable in which to store Popen instance.
            This is used only when --bg option is given.
            """,
        ),
        magic_arguments.argument(
            "--no-raise-error",
            action="store_false",
            dest="raise_error",
            help="""Whether you should raise an error message in addition to 
            a stream on stderr if you get a nonzero exit code.
            """,
        ),
    ]
    for arg in args:
        f = arg(f)
    return f
예제 #10
0
def exec_args(f):
    """decorator for adding block/targets args for execution
    
    applied to %pxconfig and %%px
    """
    args = [
        magic_arguments.argument(
            '-b',
            '--block',
            action="store_const",
            const=True,
            dest='block',
            help="use blocking (sync) execution",
        ),
        magic_arguments.argument(
            '-a',
            '--noblock',
            action="store_const",
            const=False,
            dest='block',
            help="use non-blocking (async) execution",
        ),
        magic_arguments.argument(
            '-t',
            '--targets',
            type=str,
            help="specify the targets on which to execute",
        ),
        magic_arguments.argument(
            '--verbose',
            action="store_const",
            const=True,
            dest="set_verbose",
            help="print a message at each execution",
        ),
        magic_arguments.argument(
            '--no-verbose',
            action="store_const",
            const=False,
            dest="set_verbose",
            help="don't print any messages",
        ),
    ]
    for a in args:
        f = a(f)
    return f
예제 #11
0
파일: script.py 프로젝트: dalejung/ipython
def script_args(f):
    """single decorator for adding script args"""
    args = [
        magic_arguments.argument(
            '--out', type=str,
            help="""The variable in which to store stdout from the script.
            If the script is backgrounded, this will be the stdout *pipe*,
            instead of the stderr text itself and will not be auto closed.
            """
        ),
        magic_arguments.argument(
            '--err', type=str,
            help="""The variable in which to store stderr from the script.
            If the script is backgrounded, this will be the stderr *pipe*,
            instead of the stderr text itself and will not be autoclosed.
            """
        ),
        magic_arguments.argument(
            '--bg', action="store_true",
            help="""Whether to run the script in the background.
            If given, the only way to see the output of the command is
            with --out/err.
            """
        ),
        magic_arguments.argument(
            '--proc', type=str,
            help="""The variable in which to store Popen instance.
            This is used only when --bg option is given.
            """
        ),
        magic_arguments.argument(
            '--raise-error', action="store_true",
            help="""Whether you should raise an error message in addition to 
            a stream on stderr if you get a nonzero exit code.
            """
        )
    ]
    for arg in args:
        f = arg(f)
    return f
예제 #12
0
파일: magics.py 프로젝트: chebee7i/ipython
def exec_args(f):
    """decorator for adding block/targets args for execution
    
    applied to %pxconfig and %%px
    """
    args = [
        magic_arguments.argument(
            "-b", "--block", action="store_const", const=True, dest="block", help="use blocking (sync) execution"
        ),
        magic_arguments.argument(
            "-a",
            "--noblock",
            action="store_const",
            const=False,
            dest="block",
            help="use non-blocking (async) execution",
        ),
        magic_arguments.argument("-t", "--targets", type=str, help="specify the targets on which to execute"),
        magic_arguments.argument(
            "--local",
            action="store_const",
            const=True,
            dest="local",
            help="also execute the cell in the local namespace",
        ),
        magic_arguments.argument(
            "--verbose", action="store_const", const=True, dest="set_verbose", help="print a message at each execution"
        ),
        magic_arguments.argument(
            "--no-verbose", action="store_const", const=False, dest="set_verbose", help="don't print any messages"
        ),
    ]
    for a in args:
        f = a(f)
    return f
예제 #13
0
def output_args(f):
    """decorator for output-formatting args
    
    applied to %pxresult and %%px
    """
    args = [
        magic_arguments.argument('-r', action="store_const", dest='groupby',
            const='order',
            help="collate outputs in order (same as group-outputs=order)"
        ),
        magic_arguments.argument('-e', action="store_const", dest='groupby',
            const='engine',
            help="group outputs by engine (same as group-outputs=engine)"
        ),
        magic_arguments.argument('--group-outputs', dest='groupby', type=str,
            choices=['engine', 'order', 'type'], default='type',
            help="""Group the outputs in a particular way.
            
            Choices are:
            
            **type**: group outputs of all engines by type (stdout, stderr, displaypub, etc.).
            **engine**: display all output for each engine together.
            **order**: like type, but individual displaypub output from each engine is collated.
              For example, if multiple plots are generated by each engine, the first
              figure of each engine will be displayed, then the second of each, etc.
            """
        ),
        magic_arguments.argument('-o', '--out', dest='save_name', type=str,
            help="""store the AsyncResult object for this computation
                 in the global namespace under this name.
            """
        ),
    ]
    for a in args:
        f = a(f)
    return f
예제 #14
0
def script_args(f):
    """single decorator for adding script args"""
    args = [
        magic_arguments.argument(
            '--out',
            type=str,
            help="""The variable in which to store stdout from the script.
            If the script is backgrounded, this will be the stdout *pipe*,
            instead of the stderr text itself.
            """),
        magic_arguments.argument(
            '--dir',
            type=str,
            help="""The directory to run the macro commands.
            """),
        magic_arguments.argument('--anybodycon',
                                 type=str,
                                 help="""The the path to to the anybodycon.
            """),
        magic_arguments.argument(
            '--bg',
            action="store_true",
            help="""Whether to run the script in the background.
            If given, the only way to see the output of the command is
            with --out/err.
            """),
        magic_arguments.argument(
            '--proc',
            type=str,
            help="""The variable in which to store Popen instance.
            This is used only when --bg option is given.
            """),
        magic_arguments.argument(
            '--dump',
            action="store_true",
            help="""This will move all 'dump'ed varialbes to the ipython name
            space.
            """),
        magic_arguments.argument(
            '--pager',
            action="store_true",
            help=
            """This will open AnyBody console output in the pager instead of the cell
            """),
    ]
    for arg in args:
        f = arg(f)
    return f
예제 #15
0
def script_args(f):
    """single decorator for adding script args"""
    args = [
        magic_arguments.argument(
            '--out', type=str,
            help="""The variable in which to store stdout from the script.
            If the script is backgrounded, this will be the stdout *pipe*,
            instead of the stderr text itself.
            """
        ),
        magic_arguments.argument(
            '--dir', type=str,
            help="""The directory to run the macro commands.
            """
        ),
        magic_arguments.argument(
            '--anybodycon', type=str,
            help="""The the path to to the anybodycon.
            """
        ),
        magic_arguments.argument(
            '--bg', action="store_true",
            help="""Whether to run the script in the background.
            If given, the only way to see the output of the command is
            with --out/err.
            """
        ),
        magic_arguments.argument(
            '--proc', type=str,
            help="""The variable in which to store Popen instance.
            This is used only when --bg option is given.
            """
        ),
        magic_arguments.argument(
            '--dump', action="store_true",
            help="""This will move all 'dump'ed varialbes to the ipython name
            space.
            """
        ),
        magic_arguments.argument(
            '--pager', action="store_true",
            help="""This will open AnyBody console output in the pager instead of the cell
            """
        ),
    ]
    for arg in args:
        f = arg(f)
    return f
예제 #16
0
 def _html5iframe_args(ggb_ipython_magic):
     """Arguments common for GeoGebra applets (including
     Java applets, HTML5 applets, etc).
     """
 
     @functools.wraps(ggb_ipython_magic)
     @argument(
         '--width', type=int, default=1000,
         help="Width of applet, in pixels")
     @argument(
         '--height', type=int, default=600,
         help="Height of applet, in pixels")
     def wrapped_magic(self, line, cell=None):
         return ggb_ipython_magic(self, line, cell)
     for long_arg, short_arg, help in applet.HTML5IFrame.bool_params:
         wrapped_magic = argument('--' + long_arg, '--' + short_arg,
                                  metavar='0/1', type=int, help=help)(wrapped_magic)
     
     return wrapped_magic
예제 #17
0
    def param_arguments(cls, ggb_ipython_magic):
        # TODO: everything referring to ipython should be removed from this file
        """Arguments common for GeoGebra applets (including
        Java applets, HTML5 applets, etc).
        """

        @functools.wraps(ggb_ipython_magic)
        @argument(
            '--width', type=int, default=1000,
            help="Width of applet, in pixels")
        @argument(
            '--height', type=int, default=600,
            help="Height of applet, in pixels")
        @argument(
            '--java_arguments', '--java', default='',
            help="Arguments to pass to java")
        def wrapped_magic(self, line, cell=None):
            return ggb_ipython_magic(self, line, cell)
        for param in cls.bool_params:
            wrapped_magic = argument('--' + param, metavar='0/1', type=int, help=param)(wrapped_magic)

        return wrapped_magic
예제 #18
0
파일: magics.py 프로젝트: cphyc/ipyparallel
def exec_args(f):
    """decorator for adding block/targets args for execution

    applied to %pxconfig and %%px
    """
    args = [
        magic_arguments.argument(
            '-b',
            '--block',
            action="store_const",
            const=True,
            dest='block',
            help="use blocking (sync) execution",
        ),
        magic_arguments.argument(
            '-a',
            '--noblock',
            action="store_const",
            const=False,
            dest='block',
            help="use non-blocking (async) execution",
        ),
        magic_arguments.argument(
            '--stream',
            action="store_const",
            const=True,
            dest='stream',
            help=
            "stream stdout/stderr in real-time (only valid when using blocking execution)",
        ),
        magic_arguments.argument(
            '--no-stream',
            action="store_const",
            const=False,
            dest='stream',
            help="do not stream stdout/stderr in real-time",
        ),
        magic_arguments.argument(
            '-t',
            '--targets',
            type=str,
            help="specify the targets on which to execute",
        ),
        magic_arguments.argument(
            '--local',
            action="store_const",
            const=True,
            dest="local",
            help="also execute the cell in the local namespace",
        ),
        magic_arguments.argument(
            '--verbose',
            action="store_const",
            const=True,
            dest="set_verbose",
            help="print a message at each execution",
        ),
        magic_arguments.argument(
            '--no-verbose',
            action="store_const",
            const=False,
            dest="set_verbose",
            help="don't print any messages",
        ),
    ]
    for a in args:
        f = a(f)
    return f
예제 #19
0
 def add_argument(self, *args, **kwargs):
     """Add argument to parser available for both IPython magic and cmd"""
     self.args.append(magic_arguments.argument(*args, **kwargs))
예제 #20
0
def rest_arguments(func):
    """Magic arguments shared by `rest` and `rest_root` commands.
    """
    args = (
        magic_arguments.magic_arguments(),
        magic_arguments.argument(
            '--verbose', '-v',
            action='store_true',
            help='Dump full HTTP session log.',
            default=None
        ),
        magic_arguments.argument(
            '--quiet', '-q',
            action='store_true',
            help='Do not print HTTP request and response.',
            default=None
        ),
        magic_arguments.argument(
            '--insecure', '-k',
            action='store_true',
            help='Disable SSL certificate verification.',
            default=None
        ),
        magic_arguments.argument(
            '--proxy',
            type=str,
            action='store',
            dest='proxy',
            help='Sets the proxy server to use for HTTP and HTTPS.',
            default=None
        ),
        magic_arguments.argument(
            '--max-redirects',
            type=int,
            action='store',
            dest='max_redirects',
            help=("Set the maximum number of redirects allowed, "
                  "{0} by default.".format(DEFAULT_REDIRECT_LIMIT)),
            default=None
        ),
        magic_arguments.argument(
            '--timeout',
            type=float,
            action='store',
            dest='timeout',
            help=("Set the maximum number of seconds to wait for a response, "
                  "{0} by default.".format(DEFAULT_TIMEOUT)),
            default=None
        ),
        magic_arguments.argument(
            '--extract', '-e',
            type=str,
            action='store',
            dest='parser_expression',
            metavar='expression',
            help='Extract parts of a response content with the given Xpath/JSONPath expression.',
            default=None
        ),
        magic_arguments.argument(
            '--parser',
            type=str,
            action='store',
            dest='parser',
            help='Set which parser to use to extract parts of a response content.',
            choices=ResponseParser.parsers,
            default=None
        ),
        func
    )
    return functools.reduce(lambda res, f: f(res), reversed(args))
예제 #21
0
class FortranMagics(Magics):

    allowed_fcompilers = sorted(fcompiler.fcompiler_class.keys())
    allowed_compilers = sorted(compiler_class.keys())

    my_magic_arguments = compose(
        magic_arguments.magic_arguments(),
        magic_arguments.argument("-v",
                                 "--verbosity",
                                 action="count",
                                 default=0,
                                 help="increase output verbosity"),
        magic_arguments.argument(
            '--fcompiler',
            choices=allowed_fcompilers,
            help="""Specify Fortran compiler type by vendor.
                 See %%f2py_help --fcompiler""",
        ),
        magic_arguments.argument(
            '--compiler',
            choices=allowed_compilers,
            help="""Specify C compiler type (as defined by distutils).
                    See %%f2py_help --compiler"""),
        magic_arguments.argument('--f90flags',
                                 help="Specify F90 compiler flags"),
        magic_arguments.argument('--f77flags',
                                 help="Specify F77 compiler flags"),
        magic_arguments.argument('--opt', help="Specify optimization flags"),
        magic_arguments.argument(
            '--arch', help="Specify architecture specific optimization flags"),
        magic_arguments.argument('--noopt',
                                 action="store_true",
                                 help="Compile without optimization"),
        magic_arguments.argument('--noarch',
                                 action="store_true",
                                 help="Compile without "
                                 "arch-dependent optimization"),
        magic_arguments.argument('--debug',
                                 action="store_true",
                                 help="Compile with debugging "
                                 "information"),
        magic_arguments.argument(
            '--link',
            action='append',
            default=[],
            help="""Link extension module with LINK resource, as defined
                    by numpy.distutils/system_info.py. E.g. to link
                    with optimized LAPACK libraries (vecLib on MacOSX,
                    ATLAS elsewhere), use --link lapack_opt.
                    See also %%f2py_help --resources switch."""),
        magic_arguments.argument(
            '--extra',
            action='append',
            default=[],
            help=
            """Use --extra to pass any other argument in the f2py call. For example
                    --extra '-L/path/to/lib/ -l<libname>'
                    --extra '-D<define> -U<name>'
                    --extra '-DPREPEND_FORTRAN -DUPPERCASE_FORTRAN'
                    etc. """))

    def __init__(self, shell):
        super(FortranMagics, self).__init__(shell=shell)
        self._reloads = {}
        self._code_cache = {}
        self._lib_dir = os.path.join(get_ipython_cache_dir(), 'fortran')
        if not os.path.exists(self._lib_dir):
            os.makedirs(self._lib_dir)

    def _import_all(self, module, verbosity=0):
        imported = []
        for k, v in module.__dict__.items():
            if not k.startswith('__'):
                self.shell.push({k: v})
                imported.append(k)
        if verbosity > 0 and imported:
            print("\nOk. The following fortran objects "
                  "are ready to use: %s" % ", ".join(imported))

    def _run_f2py(self, argv, show_captured=False, verbosity=0):
        """
        Here we directly call the numpy.f2py.f2py2e.run_compile() entry point,
        after some small amount of setup to get sys.argv and the current
        working directory set appropriately.
        """
        old_argv = sys.argv
        old_cwd = os.getcwdu() if sys.version_info[0] == 2 else os.getcwd()
        try:
            sys.argv = ['f2py'] + list(map(str, argv))
            if verbosity > 1:
                print("Running...\n   %s" % ' '.join(sys.argv))

            os.chdir(self._lib_dir)
            try:
                with capture_output() as captured:
                    #subprocess.call(sys.argv)
                    # Refactor subprocess call to work with jupyterhub
                    try:
                        p = Popen(sys.argv,
                                  stdout=PIPE,
                                  stderr=PIPE,
                                  stdin=PIPE)
                    except OSError as e:
                        if e.errno == errno.ENOENT:
                            print("Couldn't find program: %r" % sys.argv[0])
                            return
                        else:
                            raise
                    try:
                        out, err = p.communicate(input=None)
                    except:
                        pass
                    if err:
                        sys.stderr.write(err)
                        sys.stderr.flush()
                if show_captured or verbosity > 2:
                    if out:
                        sys.stdout.write(out)
                        sys.stdout.flush()
                    captured()
            except SystemExit as e:
                captured()
                raise UsageError(str(e))
        finally:
            sys.argv = old_argv
            os.chdir(old_cwd)

    @magic_arguments.magic_arguments()
    @magic_arguments.argument(
        '--resources',
        action="store_true",
        help="""List system resources found by system_info.py.

                See also
                %%f2py_help --link <resource> switch.
                """)
    @magic_arguments.argument('--link',
                              help="""Given a resource name, show what it foun.
                E.g. try '--link lapack.

                See also
                %%f2py_help --link <resource> switch.
                """)
    @magic_arguments.argument(
        '--fcompiler',
        action="store_true",
        help="List available Fortran compilers",
    )
    @magic_arguments.argument(
        '--compiler',
        action="store_true",
        help="List available C compilers",
    )
    @line_magic
    def f2py_help(self, line):
        args = magic_arguments.parse_argstring(self.f2py_help, line)
        if args.fcompiler:
            self._run_f2py(['-c', '--help-fcompiler'], True)
        elif args.compiler:
            self._run_f2py(['-c', '--help-compiler'], True)
        elif args.resources:
            self._run_f2py(['--help-link'], True)
        elif args.link:
            self._run_f2py(['--help-link', args.link], True)

    @my_magic_arguments
    @magic_arguments.argument('--defaults',
                              action="store_true",
                              help="Delete custom configuration "
                              "and back to default")
    @line_magic
    def fortran_config(self, line):
        """
        View and handle the custom configuration for %%fortran magic.

            %fortran_config

                Show the current custom configuration

            %fortran_config --defaults

                Delete the current configuration and back to defaults

            %fortran_config <other options>

                Save <other options> to use with %%fortran
        """

        args = magic_arguments.parse_argstring(self.fortran_config, line)
        if args.defaults:
            try:
                del self.shell.db['fortran']
                print(
                    "Deleted custom config. Back to default arguments for %%fortran"
                )
            except KeyError:
                print("No custom config found for %%fortran")
        elif not line:
            try:
                line = self.shell.db['fortran']
            except KeyError:
                print("No custom config found for %%fortran")
            print("Current defaults arguments for %%fortran:\n\t%s" % line)
        else:
            self.shell.db['fortran'] = line
            print("New default arguments for %%fortran:\n\t%s" % line)

    @my_magic_arguments
    @cell_magic
    def fortran(self, line, cell):
        """Compile and import everything from a Fortran code cell, using f2py.

        The content of the cell is written to a `.f90` file in the
        directory `IPYTHONDIR/fortran` using a filename with the hash of the
        code. This file is then compiled. The resulting module
        is imported and all of its symbols are injected into the user's
        namespace.


        Usage
        =====
        Prepend ``%%fortran`` to your fortran code in a cell::

        ``%%fortran

        ! put your code here.
        ``


        """

        try:
            # custom saved arguments
            saved_defaults = vars(
                magic_arguments.parse_argstring(self.fortran,
                                                self.shell.db['fortran']))
            self.fortran.parser.set_defaults(**saved_defaults)
        except KeyError:
            saved_defaults = {'verbosity': 0}

        # verbosity is a "count" argument were each ocurrence is
        # added implicit.
        # so, for instance, -vv in %fortran_config and -vvv in %%fortran means
        # a nonsense verbosity=5.
        # To override: if verbosity is given for the magic cell
        # we ignore the saved config.
        if '-v' in line:
            self.fortran.parser.set_defaults(verbosity=0)

        args = magic_arguments.parse_argstring(self.fortran, line)

        # boolean flags
        f2py_args = ['--%s' % k for k, v in vars(args).items() if v is True]

        try:
            base_str_class = basestring
        except NameError:
            # py3
            base_str_class = str

        kw = [
            '--%s=%s' % (k, v) for k, v in vars(args).items()
            if isinstance(v, base_str_class)
        ]

        f2py_args.extend(kw)

        # link resource
        if args.link:
            resources = ['--link-%s' % r for r in args.link]
            f2py_args.extend(resources)

        if args.extra:
            extras = ' '.join(map(unquote, args.extra))
            extras = extras.split()
            f2py_args.extend(extras)

        code = cell if cell.endswith('\n') else cell + '\n'
        key = code, line, sys.version_info, sys.executable, f2py2e.f2py_version

        module_name = "_fortran_magic_" + \
                      hashlib.md5(str(key).encode('utf-8')).hexdigest()

        module_path = os.path.join(self._lib_dir, module_name + self.so_ext)

        f90_file = os.path.join(self._lib_dir, module_name + '.f90')
        f90_file = py3compat.cast_bytes_py2(
            f90_file, encoding=sys.getfilesystemencoding())
        with io.open(f90_file, 'w', encoding='utf-8') as f:
            f.write(code)

        self._run_f2py(f2py_args + ['-m', module_name, '-c', f90_file],
                       verbosity=args.verbosity)

        self._code_cache[key] = module_name
        module = imp.load_dynamic(module_name, module_path)
        self._import_all(module, verbosity=args.verbosity)

    @property
    def so_ext(self):
        """The extension suffix for compiled modules."""
        try:
            return self._so_ext
        except AttributeError:

            dist = Distribution()
            config_files = dist.find_config_files()
            try:
                config_files.remove('setup.cfg')
            except ValueError:
                pass
            dist.parse_config_files(config_files)
            build_extension = build_ext(dist)
            build_extension.finalize_options()
            self._so_ext = build_extension.get_ext_filename('')
            return self._so_ext
예제 #22
0
 def add_argument(self, *args, **kwargs):
     self.args.append(
         magic_arguments.argument(*args, **kwargs)
     )
예제 #23
0
파일: pylab.py 프로젝트: 9G1IC/ipython
# Our own packages
from traitlets.config.application import Application
from IPython.core import magic_arguments
from IPython.core.magic import Magics, magics_class, line_magic
from IPython.testing.skipdoctest import skip_doctest
from IPython.utils.warn import warn
from IPython.core.pylabtools import backends

#-----------------------------------------------------------------------------
# Magic implementation classes
#-----------------------------------------------------------------------------

magic_gui_arg = magic_arguments.argument(
        'gui', nargs='?',
        help="""Name of the matplotlib backend to use %s.
        If given, the corresponding matplotlib backend is used,
        otherwise it will be matplotlib's default
        (which you can set in your matplotlib config file).
        """ % str(tuple(sorted(backends.keys())))
)


@magics_class
class PylabMagics(Magics):
    """Magics related to matplotlib's pylab support"""
    
    @skip_doctest
    @line_magic
    @magic_arguments.magic_arguments()
    @magic_gui_arg
    def matplotlib(self, line=''):
        """Set up matplotlib to work interactively.
예제 #24
0
 def add_argument(self, *args, **kwargs):
     """Add argument to parser available for both IPython magic and cmd"""
     self.args.append(
         magic_arguments.argument(*args, **kwargs)
     )
예제 #25
0
파일: pylab.py 프로젝트: wangyan716/ipython
# Our own packages
from IPython.config.application import Application
from IPython.core import magic_arguments
from IPython.core.magic import Magics, magics_class, line_magic
from IPython.testing.skipdoctest import skip_doctest
from IPython.utils.warn import warn
from IPython.core.pylabtools import backends

#-----------------------------------------------------------------------------
# Magic implementation classes
#-----------------------------------------------------------------------------

magic_gui_arg = magic_arguments.argument(
        'gui', nargs='?',
        help="""Name of the matplotlib backend to use %s.
        If given, the corresponding matplotlib backend is used,
        otherwise it will be matplotlib's default
        (which you can set in your matplotlib config file).
        """ % str(tuple(sorted(backends.keys())))
)


@magics_class
class PylabMagics(Magics):
    """Magics related to matplotlib's pylab support"""
    
    @skip_doctest
    @line_magic
    @magic_arguments.magic_arguments()
    @magic_gui_arg
    def matplotlib(self, line=''):
        """Set up matplotlib to work interactively.
예제 #26
0
from IPython.core import magic_arguments
from IPython.core.magic import Magics, magics_class, cell_magic, line_cell_magic, line_magic
from .pyamzi import Engine
from .utils import find_files

name_argument = magic_arguments.argument(
    '-n', '--name', help='Specify a name for logic server engine')


@magics_class
class AmziMagics(Magics):
    def __init__(self, shell):
        super(AmziMagics, self).__init__(shell)
        self.engines = {}

    def get_engine(self, args):
        if isinstance(args, dict):
            name = args.get("name", None)
        else:
            name = getattr(args, "name", None)
        if name is None:
            name = "default"

        if name not in self.engines:
            self.engines[name] = eng = Engine(name, load_init=True)
        return self.engines[name]

    @magic_arguments.magic_arguments()
    @name_argument
    @cell_magic
    def consult(self, line, cell):
예제 #27
0
def exec_args(f):
    """decorator for adding block/targets args for execution

    applied to %pxconfig and %%px
    """
    args = [
        magic_arguments.argument(
            '-b',
            '--block',
            action="store_const",
            const=True,
            dest='block',
            help="use blocking (sync) execution",
        ),
        magic_arguments.argument(
            '-a',
            '--noblock',
            action="store_const",
            const=False,
            dest='block',
            help="use non-blocking (async) execution",
        ),
        magic_arguments.argument(
            '--stream',
            action="store_const",
            const=True,
            dest='stream',
            help=
            "stream stdout/stderr in real-time (only valid when using blocking execution)",
        ),
        magic_arguments.argument(
            '--no-stream',
            action="store_const",
            const=False,
            dest='stream',
            help="do not stream stdout/stderr in real-time",
        ),
        magic_arguments.argument(
            '-t',
            '--targets',
            type=str,
            help="specify the targets on which to execute",
        ),
        magic_arguments.argument(
            '--local',
            action="store_const",
            const=True,
            dest="local",
            help="also execute the cell in the local namespace",
        ),
        magic_arguments.argument(
            '--verbose',
            action="store_const",
            const=True,
            dest="set_verbose",
            help="print a message at each execution",
        ),
        magic_arguments.argument(
            '--no-verbose',
            action="store_const",
            const=False,
            dest="set_verbose",
            help="don't print any messages",
        ),
        magic_arguments.argument(
            '--progress-after',
            dest="progress_after_seconds",
            type=float,
            default=None,
            help=
            """Wait this many seconds before showing a progress bar for task completion.

            Use -1 for no progress, 0 for always showing progress immediately.
            """,
        ),
        magic_arguments.argument(
            '--signal-on-interrupt',
            dest='signal_on_interrupt',
            type=str,
            default=None,
            help=
            """Send signal to engines on Keyboard Interrupt. By default a SIGINT is sent.
            Note that this is only applicable when running in blocking mode.
            Choices: SIGINT, 2, SIGKILL, 9, 0 (nop), etc.
            """,
        ),
    ]
    for a in args:
        f = a(f)
    return f
예제 #28
0
"""


import itertools
import sqlite3

from IPython.core.magic import Magics, magics_class, line_magic, cell_magic
from IPython.core.magic_arguments import (argument, magic_arguments,
                                          parse_argstring)
import texttable


common_show_arguments = argument(
    '--limit', '-l', type=int, default=10,
    help="""
    Maximum rows to print as table.  -1 means no limit.
    (default: %(default)s)
    """)


@magics_class
class SQLiteMagic(Magics):

    @line_magic('sqlite_create')
    def create(self, line):
        """
        Create in-memory SQLite DB with SQLite magic-friendly setup.
        """
        conn = sqlite3.connect(":memory:")
        conn.row_factory = sqlite3.Row
        return conn