Coverage for pyquickhelper/ipythonhelper/magic_class.py: 100%
32 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
1# -*- coding: utf-8 -*-
2"""
3@file
4@brief Magic command to handle files
5"""
6from __future__ import print_function
7import warnings
8with warnings.catch_warnings():
9 warnings.simplefilter("ignore")
10 from IPython.core.magic import Magics, magics_class
13@magics_class
14class MagicClassWithHelpers(Magics):
16 """
17 Provides some functions reused in others classes inherited from *Magics*.
18 The class should not be registered as it is but should be
19 used as an ancestor for another class.
20 It can be registered this way::
22 def register_file_magics():
23 from IPython import get_ipython
24 ip = get_ipython()
25 ip.register_magics(MagicFile)
26 """
28 _parser_store = {}
30 @property
31 def Context(self):
32 """
33 return the context or None
34 """
35 if self.shell is None:
36 return None
37 return self.shell.user_ns
39 def add_context(self, context):
40 """
41 add context to the class, mostly for debug purpose
43 @param context dictionary
44 """
45 if self.shell is None:
46 class EmptyClass:
48 def __init__(self):
49 self.user_ns = {}
50 self.shell = EmptyClass()
51 for k, v in context.items():
52 self.shell.user_ns[k] = v
54 def get_parser(self, parser_class, name):
55 """
56 Returns a parser for a magic command, initializes it
57 if it does not exists, it creates it. The parsers are stored
58 in static member *_parser_store*.
60 @param parser_class the parser to use for this magic command
61 @param name name of the static variable which will contain the parser
63 See method @see me get_args
64 """
65 res = MagicClassWithHelpers._parser_store.get(name, None)
66 if res is None:
67 MagicClassWithHelpers._parser_store[name] = parser_class()
68 return MagicClassWithHelpers._parser_store[name]
69 return res
71 def get_args(self, line, parser, print_function=print):
72 """
73 parser a command line with a given parser
75 @param line string (command line)
76 @param parser parser which has to be used to parse *line*
77 @param print_function function to use to display the help
78 @return results
80 If the line cannot be parsed, the function displays the help
81 using function print.
83 Example::
85 @line_magic
86 def custom_magic_command(self, line):
87 parser = self.get_parser(MagicClass.custom_magic_command_parser, "custom_magic_command")
88 args = self.get_args(line, parser)
89 if args is not None:
90 param = args.param
92 # ....
93 """
94 try:
95 args = parser.parse_cmd(line, context=self.Context)
96 except SystemExit: # pragma: no cover
97 print_function(parser.format_usage())
98 args = None
100 return args