本文整理汇总了Python中IPython.core.magic_arguments.argument方法的典型用法代码示例。如果您正苦于以下问题:Python magic_arguments.argument方法的具体用法?Python magic_arguments.argument怎么用?Python magic_arguments.argument使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IPython.core.magic_arguments
的用法示例。
在下文中一共展示了magic_arguments.argument方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: pycat
# 需要导入模块: from IPython.core import magic_arguments [as 别名]
# 或者: from IPython.core.magic_arguments import argument [as 别名]
def pycat(self, parameter_s=''):
"""Show a syntax-highlighted file through a pager.
This magic is similar to the cat utility, but it will assume the file
to be Python source and will show it with syntax highlighting.
This magic command can either take a local filename, an url,
an history range (see %history) or a macro as argument ::
%pycat myscript.py
%pycat 7-27
%pycat myMacro
%pycat http://www.example.com/myscript.py
"""
if not parameter_s:
raise UsageError('Missing filename, URL, input history range, '
'or macro.')
try :
cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False)
except (ValueError, IOError):
print "Error: no such file, variable, URL, history range or macro"
return
page.page(self.shell.pycolorize(source_to_unicode(cont)))
示例2: exec_args
# 需要导入模块: from IPython.core import magic_arguments [as 别名]
# 或者: from IPython.core.magic_arguments import argument [as 别名]
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
示例3: output_args
# 需要导入模块: from IPython.core import magic_arguments [as 别名]
# 或者: from IPython.core.magic_arguments import argument [as 别名]
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
示例4: script_args
# 需要导入模块: from IPython.core import magic_arguments [as 别名]
# 或者: from IPython.core.magic_arguments import argument [as 别名]
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: pdb
# 需要导入模块: from IPython.core import magic_arguments [as 别名]
# 或者: from IPython.core.magic_arguments import argument [as 别名]
def pdb(self, parameter_s=''):
"""Control the automatic calling of the pdb interactive debugger.
Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
argument it works as a toggle.
When an exception is triggered, IPython can optionally call the
interactive pdb debugger after the traceback printout. %pdb toggles
this feature on and off.
The initial state of this feature is set in your configuration
file (the option is ``InteractiveShell.pdb``).
If you want to just activate the debugger AFTER an exception has fired,
without having to type '%pdb on' and rerunning your code, you can use
the %debug magic."""
par = parameter_s.strip().lower()
if par:
try:
new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
except KeyError:
print ('Incorrect argument. Use on/1, off/0, '
'or nothing for a toggle.')
return
else:
# toggle
new_pdb = not self.shell.call_pdb
# set on the shell
self.shell.call_pdb = new_pdb
print 'Automatic pdb calling has been turned',on_off(new_pdb)
示例6: debug
# 需要导入模块: from IPython.core import magic_arguments [as 别名]
# 或者: from IPython.core.magic_arguments import argument [as 别名]
def debug(self, line='', cell=None):
"""Activate the interactive debugger.
This magic command support two ways of activating debugger.
One is to activate debugger before executing code. This way, you
can set a break point, to step through the code from the point.
You can use this mode by giving statements to execute and optionally
a breakpoint.
The other one is to activate debugger in post-mortem mode. You can
activate this mode simply running %debug without any argument.
If an exception has just occurred, this lets you inspect its stack
frames interactively. Note that this will always work only on the last
traceback that occurred, so you must call this quickly after an
exception that you wish to inspect has fired, because if another one
occurs, it clobbers the previous one.
If you want IPython to automatically do this on every exception, see
the %pdb magic for more details.
"""
args = magic_arguments.parse_argstring(self.debug, line)
if not (args.breakpoint or args.statement or cell):
self._debug_post_mortem()
else:
code = "\n".join(args.statement)
if cell:
code += "\n" + cell
self._debug_exec(code, args.breakpoint)
示例7: _get_variable
# 需要导入模块: from IPython.core import magic_arguments [as 别名]
# 或者: from IPython.core.magic_arguments import argument [as 别名]
def _get_variable(name):
"""Get a variable from the notebook namespace."""
ip = IPython.get_ipython()
if ip is None:
raise ValueError(
"Magic command must be run within an IPython "
"environemnt, in which get_ipython() is defined."
)
if name not in ip.user_ns:
raise NameError(
"argument '{}' does not match the "
"name of any defined variable".format(name)
)
return ip.user_ns[name]
示例8: _shell_cell_magic
# 需要导入模块: from IPython.core import magic_arguments [as 别名]
# 或者: from IPython.core.magic_arguments import argument [as 别名]
def _shell_cell_magic(args, cmd):
"""Run the cell via a shell command, allowing input to be provided.
Also available as a line magic.
Usage:
# Returns a ShellResult.
%%shell
echo "hello"
This is similar to Jupyter's `!` magic, but additionally allows input to be
provided to the subprocess. By default, if the subprocess returns a non-zero
exit code a `subprocess.CalledProcessError` is raised. The provided command
is run within a bash shell.
Args:
args: Optional arguments.
cmd: The shell command to execute.
Returns:
ShellResult containing the results of the executed command.
Raises:
subprocess.CalledProcessError: If the subprocess exited with a non-zero
exit code and the `ignore_errors` argument wasn't provided.
"""
parsed_args = magic_arguments.parse_argstring(_shell_cell_magic, args)
result = _run_command(cmd, clear_streamed_output=False)
if not parsed_args.ignore_errors:
result.check_returncode()
return result
示例9: _repr_pretty_
# 需要导入模块: from IPython.core import magic_arguments [as 别名]
# 或者: from IPython.core.magic_arguments import argument [as 别名]
def _repr_pretty_(self, p, cycle): # pylint:disable=unused-argument
# Note: When invoking the magic and not assigning the result
# (e.g. %shell echo "foo"), Python's default semantics will be used and
# print the string representation of the object. By default, this will
# display the __repr__ of ShellResult. Suppress this representation since
# the output of the command has already been displayed to the output window.
if cycle:
raise NotImplementedError
示例10: _display_stdin_widget
# 需要导入模块: from IPython.core import magic_arguments [as 别名]
# 或者: from IPython.core.magic_arguments import argument [as 别名]
def _display_stdin_widget(delay_millis=0):
"""Context manager that displays a stdin UI widget and hides it upon exit.
Args:
delay_millis: Duration (in milliseconds) to delay showing the widget within
the UI.
Yields:
A callback that can be invoked with a single argument indicating whether
echo is enabled.
"""
shell = _ipython.get_ipython()
display_args = ['cell_display_stdin', {'delayMillis': delay_millis}]
_message.blocking_request(*display_args, parent=shell.parent_header)
def echo_updater(new_echo_status):
# Note: Updating the echo status uses colab_request / colab_reply on the
# stdin socket. Input provided by the user also sends messages on this
# socket. If user input is provided while the blocking_request call is still
# waiting for a colab_reply, the input will be dropped per
# https://github.com/googlecolab/colabtools/blob/56e4dbec7c4fa09fad51b60feb5c786c69d688c6/google/colab/_message.py#L100.
update_args = ['cell_update_stdin', {'echo': new_echo_status}]
_message.blocking_request(*update_args, parent=shell.parent_header)
yield echo_updater
hide_args = ['cell_remove_stdin', {}]
_message.blocking_request(*hide_args, parent=shell.parent_header)
示例11: _getoutput_compat
# 需要导入模块: from IPython.core import magic_arguments [as 别名]
# 或者: from IPython.core.magic_arguments import argument [as 别名]
def _getoutput_compat(shell, cmd, split=True, depth=0):
"""Compatibility function for IPython's built-in getoutput command.
The getoutput command has the following semantics:
* Returns a SList containing an array of output
* SList items are of type "str". In Python 2, the str object is utf-8
encoded. In Python 3, the "str" type already supports Unicode.
* The _exit_code attribute is not set
* If the process was interrupted, "^C" is printed.
Args:
shell: An InteractiveShell instance.
cmd: Command to execute. This is the same as the corresponding argument to
InteractiveShell.getoutput.
split: Same as the corresponding argument to InteractiveShell.getoutput.
depth: Same as the corresponding argument to InteractiveShell.getoutput.
Returns:
The output as a SList if split was true, otherwise an LSString.
"""
# We set a higher depth than the IPython system command since a shell object
# is expected to call this function, thus adding one level of nesting to the
# stack.
result = _run_command(
shell.var_expand(cmd, depth=depth + 2), clear_streamed_output=True)
if -result.returncode in _INTERRUPTED_SIGNALS:
print('^C')
output = result.output
if six.PY2:
# Backwards compatibility. Python 2 getoutput() expects the result as a
# str, not a unicode.
output = output.encode(_ENCODING)
if split:
return text.SList(output.splitlines())
else:
return text.LSString(output)
示例12: _system_compat
# 需要导入模块: from IPython.core import magic_arguments [as 别名]
# 或者: from IPython.core.magic_arguments import argument [as 别名]
def _system_compat(shell, cmd, also_return_output=False):
"""Compatibility function for IPython's built-in system command.
The system command has the following semantics:
* No return value, and thus the "_" variable is not set
* Sets the _exit_code variable to the return value of the called process
* Unicode characters are preserved
* If the process was interrupted, "^C" is printed.
Args:
shell: An InteractiveShell instance.
cmd: Command to execute. This is the same as the corresponding argument to
InteractiveShell.system_piped.
also_return_output: if True, return any output from this function, along
with printing it. Otherwise, print output and return None.
Returns:
LSString if also_return_output=True, else None.
"""
# We set a higher depth than the IPython system command since a shell object
# is expected to call this function, thus adding one level of nesting to the
# stack.
result = _run_command(
shell.var_expand(cmd, depth=2), clear_streamed_output=False)
shell.user_ns['_exit_code'] = result.returncode
if -result.returncode in _INTERRUPTED_SIGNALS:
print('^C')
if also_return_output:
output = result.output
if six.PY2:
# Backwards compatibility. Python 2 getoutput() expects the result as a
# str, not a unicode.
output = output.encode(_ENCODING)
return text.LSString(output)
示例13: put
# 需要导入模块: from IPython.core import magic_arguments [as 别名]
# 或者: from IPython.core.magic_arguments import argument [as 别名]
def put(self, line):
args = magic_arguments.parse_argstring(self.put, line)
if not args.o:
raise UsageError('-o option is mandatory for the invocation')
if not args.o[0].startswith(tuple(string.ascii_letters)):
raise UsageError('The output variable name must be a valid prefix '
'of a python variable, that is, start with a '
'letter')
if not args.storlet:
raise UsageError('--storlet option is mandatory '
'for the invocation')
if not args.input:
raise UsageError('--input option is mandatory for the invocation')
if not args.input.startswith('/'):
raise UsageError('--input argument must be a full path')
if not args.output:
raise UsageError('--output option is mandatory for the invocation')
dst_container, dst_obj = self._parse_input_path(args.output)
headers = {'X-Run-Storlet': '%s' % args.storlet}
# pick -i option and translate the params to
# X-Storlet-Parameter-x headers
storlet_headers = self._generate_params_headers(
self.shell.user_ns[args.i] if args.i else {})
headers.update(storlet_headers)
# invoke storlet app on copy
conn = get_swift_connection()
response_dict = dict()
with open(args.input, 'rb') as content:
conn.put_object(
dst_container, dst_obj,
content,
headers=headers,
response_dict=response_dict)
res = Response(int(response_dict['status']),
response_dict['headers'])
self.shell.user_ns[args.o] = res
示例14: precision
# 需要导入模块: from IPython.core import magic_arguments [as 别名]
# 或者: from IPython.core.magic_arguments import argument [as 别名]
def precision(self, s=''):
"""Set floating point precision for pretty printing.
Can set either integer precision or a format string.
If numpy has been imported and precision is an int,
numpy display precision will also be set, via ``numpy.set_printoptions``.
If no argument is given, defaults will be restored.
Examples
--------
::
In [1]: from math import pi
In [2]: %precision 3
Out[2]: u'%.3f'
In [3]: pi
Out[3]: 3.142
In [4]: %precision %i
Out[4]: u'%i'
In [5]: pi
Out[5]: 3
In [6]: %precision %e
Out[6]: u'%e'
In [7]: pi**10
Out[7]: 9.364805e+04
In [8]: %precision
Out[8]: u'%r'
In [9]: pi**10
Out[9]: 93648.047476082982
"""
ptformatter = self.shell.display_formatter.formatters['text/plain']
ptformatter.float_precision = s
return ptformatter.float_format
示例15: fc
# 需要导入模块: from IPython.core import magic_arguments [as 别名]
# 或者: from IPython.core.magic_arguments import argument [as 别名]
def fc(self, line, cell=None):
"""Define or replace a C++ include definition
- Without any argument, lists all existing definitions
- In line mode, stores a one-line function, variable, or structure definition
- In block mode, stores a multiline function, struct, or class definition
The key for the includes ditcionary is automatically chosen. In cell mode,
it's a whitespace-normalized version of the header line. In line mode, it
extends until the first '{' or '=' character.
The underlying dictionary is 'includes'. You can remove all includes with:
includes.clear()
Example:
fill _100 1 100
wr _100 abcdef
rd _100
fc uint32_t* words = (uint32_t*) buffer
buffer = pad + 0x100
ec words[0]
%%fc uint32_t sum(uint32_t* values, int count)
uint32_t result = 0;
while (count--) {
result += *(values++);
}
return result;
ec sum(words, 10)
It's also worth noting that include files are re-read every time you evaluate
a C++ expression, so a command like this will allow you to edit code in one
window and interactively run expressions in another:
fc #include "my_functions.h"
"""
if cell:
dict_key = ' '.join(line.split())
body = "%s {\n%s;\n};\n" % (line, cell)
includes[dict_key] = body
elif not line.strip():
for key, value in includes.items():
sys.stdout.write('%s %s %s\n%s\n\n' % (
'=' * 10,
key,
'=' * max(0, 70 - len(key)),
value
))
else:
dict_key = ' '.join(line.split()).split('{')[0].split('=')[0]
includes[dict_key] = line + ';'