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)
| 4006 | return text |
| 4007 | |
| 4008 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): |
| 4009 | """Get a code string from history, file, url, or a string or macro. |
| 4010 | |
| 4011 | This is mainly used by magic functions. |
| 4012 | |
| 4013 | Parameters |
| 4014 | ---------- |
| 4015 | target : str |
| 4016 | A string specifying code to retrieve. This will be tried respectively |
| 4017 | as: ranges of input history (see %history for syntax), url, |
| 4018 | corresponding .py file, filename, or an expression evaluating to a |
| 4019 | string or Macro in the user namespace. |
| 4020 | |
| 4021 | If empty string is given, returns complete history of current |
| 4022 | session, without the last line. |
| 4023 | |
| 4024 | raw : bool |
| 4025 | If true (default), retrieve raw history. Has no effect on the other |
| 4026 | retrieval mechanisms. |
| 4027 | |
| 4028 | py_only : bool (default False) |
| 4029 | Only try to fetch python code, do not try alternative methods to decode file |
| 4030 | if unicode fails. |
| 4031 | |
| 4032 | Returns |
| 4033 | ------- |
| 4034 | A string of code. |
| 4035 | ValueError is raised if nothing is found, and TypeError if it evaluates |
| 4036 | to an object of another type. In each case, .args[0] is a printable |
| 4037 | message. |
| 4038 | """ |
| 4039 | code = self.extract_input_lines(target, raw=raw) # Grab history |
| 4040 | if code: |
| 4041 | return code |
| 4042 | try: |
| 4043 | if target.startswith(('http://', 'https://')): |
| 4044 | return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) |
| 4045 | except UnicodeDecodeError as e: |
| 4046 | if not py_only : |
| 4047 | # Deferred import |
| 4048 | from urllib.request import urlopen |
| 4049 | response = urlopen(target) |
| 4050 | return response.read().decode('latin1') |
| 4051 | raise ValueError(("'%s' seem to be unreadable.") % target) from e |
| 4052 | |
| 4053 | potential_target = [target] |
| 4054 | try : |
| 4055 | potential_target.insert(0,get_py_filename(target)) |
| 4056 | except IOError: |
| 4057 | pass |
| 4058 | |
| 4059 | for tgt in potential_target : |
| 4060 | if os.path.isfile(tgt): # Read file |
| 4061 | try : |
| 4062 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) |
| 4063 | except UnicodeDecodeError as e: |
| 4064 | if not py_only : |
| 4065 | with io_open(tgt,'r', encoding='latin1') as f : |
no test coverage detected