Get a code string from history, file, url, or a string or macro. This is mainly used by magic functions. Parameters ---------- target : str A string specifying code to retrieve. This will be tried respectively as: ranges of input history (see %
(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False)
| 3664 | return "\n".join(x for _, _, x in lines) |
| 3665 | |
| 3666 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): |
| 3667 | """Get a code string from history, file, url, or a string or macro. |
| 3668 | |
| 3669 | This is mainly used by magic functions. |
| 3670 | |
| 3671 | Parameters |
| 3672 | ---------- |
| 3673 | |
| 3674 | target : str |
| 3675 | |
| 3676 | A string specifying code to retrieve. This will be tried respectively |
| 3677 | as: ranges of input history (see %history for syntax), url, |
| 3678 | corresponding .py file, filename, or an expression evaluating to a |
| 3679 | string or Macro in the user namespace. |
| 3680 | |
| 3681 | raw : bool |
| 3682 | If true (default), retrieve raw history. Has no effect on the other |
| 3683 | retrieval mechanisms. |
| 3684 | |
| 3685 | py_only : bool (default False) |
| 3686 | Only try to fetch python code, do not try alternative methods to decode file |
| 3687 | if unicode fails. |
| 3688 | |
| 3689 | Returns |
| 3690 | ------- |
| 3691 | A string of code. |
| 3692 | |
| 3693 | ValueError is raised if nothing is found, and TypeError if it evaluates |
| 3694 | to an object of another type. In each case, .args[0] is a printable |
| 3695 | message. |
| 3696 | """ |
| 3697 | code = self.extract_input_lines(target, raw=raw) # Grab history |
| 3698 | if code: |
| 3699 | return code |
| 3700 | try: |
| 3701 | if target.startswith(('http://', 'https://')): |
| 3702 | return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) |
| 3703 | except UnicodeDecodeError: |
| 3704 | if not py_only : |
| 3705 | # Deferred import |
| 3706 | from urllib.request import urlopen |
| 3707 | response = urlopen(target) |
| 3708 | return response.read().decode('latin1') |
| 3709 | raise ValueError(("'%s' seem to be unreadable.") % target) |
| 3710 | |
| 3711 | potential_target = [target] |
| 3712 | try : |
| 3713 | potential_target.insert(0,get_py_filename(target)) |
| 3714 | except IOError: |
| 3715 | pass |
| 3716 | |
| 3717 | for tgt in potential_target : |
| 3718 | if os.path.isfile(tgt): # Read file |
| 3719 | try : |
| 3720 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) |
| 3721 | except UnicodeDecodeError : |
| 3722 | if not py_only : |
| 3723 | with io_open(tgt,'r', encoding='latin1') as f : |
no test coverage detected