Paste & execute a pre-formatted code block from clipboard. The text is pulled directly from the clipboard without user intervention and printed back on the screen before execution (unless the -q flag is given to force quiet mode). The block is dedented prior to exec
(self, parameter_s='')
| 139 | |
| 140 | @line_magic |
| 141 | def paste(self, parameter_s=''): |
| 142 | """Paste & execute a pre-formatted code block from clipboard. |
| 143 | |
| 144 | The text is pulled directly from the clipboard without user |
| 145 | intervention and printed back on the screen before execution (unless |
| 146 | the -q flag is given to force quiet mode). |
| 147 | |
| 148 | The block is dedented prior to execution to enable execution of method |
| 149 | definitions. '>' and '+' characters at the beginning of a line are |
| 150 | ignored, to allow pasting directly from e-mails, diff files and |
| 151 | doctests (the '...' continuation prompt is also stripped). The |
| 152 | executed block is also assigned to variable named 'pasted_block' for |
| 153 | later editing with '%edit pasted_block'. |
| 154 | |
| 155 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
| 156 | This assigns the pasted block to variable 'foo' as string, without |
| 157 | executing it (preceding >>> and + is still stripped). |
| 158 | |
| 159 | Options: |
| 160 | |
| 161 | -r: re-executes the block previously entered by cpaste. |
| 162 | |
| 163 | -q: quiet mode: do not echo the pasted text back to the terminal. |
| 164 | |
| 165 | IPython statements (magics, shell escapes) are not supported (yet). |
| 166 | |
| 167 | See also |
| 168 | -------- |
| 169 | cpaste: manually paste code into terminal until you mark its end. |
| 170 | """ |
| 171 | opts, name = self.parse_options(parameter_s, 'rq', mode='string') |
| 172 | if 'r' in opts: |
| 173 | self.rerun_pasted() |
| 174 | return |
| 175 | try: |
| 176 | block = self.shell.hooks.clipboard_get() |
| 177 | except TryNext as clipboard_exc: |
| 178 | message = getattr(clipboard_exc, 'args') |
| 179 | if message: |
| 180 | error(message[0]) |
| 181 | else: |
| 182 | error('Could not get text from the clipboard.') |
| 183 | return |
| 184 | except ClipboardEmpty: |
| 185 | raise UsageError("The clipboard appears to be empty") |
| 186 | |
| 187 | # By default, echo back to terminal unless quiet mode is requested |
| 188 | if 'q' not in opts: |
| 189 | write = self.shell.write |
| 190 | write(self.shell.pycolorize(block)) |
| 191 | if not block.endswith('\n'): |
| 192 | write('\n') |
| 193 | write("## -- End pasted text --\n") |
| 194 | |
| 195 | self.store_or_execute(block, name) |
| 196 | |
| 197 | # Class-level: add a '%cls' magic only on Windows |
| 198 | if sys.platform == 'win32': |
nothing calls this directly
no test coverage detected