| 108 | |
| 109 | @classmethod |
| 110 | def wrap_script(cls, script, *, stdout=True, stderr=False, exc=False): |
| 111 | script = dedent(script).strip(os.linesep) |
| 112 | imports = [ |
| 113 | f'import {__name__} as _interp_utils', |
| 114 | ] |
| 115 | wrapped = script |
| 116 | |
| 117 | # Handle exc. |
| 118 | if exc: |
| 119 | exc = os.pipe() |
| 120 | r_exc, w_exc = exc |
| 121 | indented = wrapped.replace('\n', '\n ') |
| 122 | wrapped = cls.EXC.format( |
| 123 | w_pipe=w_exc, |
| 124 | indented=indented, |
| 125 | ) |
| 126 | else: |
| 127 | exc = None |
| 128 | |
| 129 | # Handle stdout. |
| 130 | if stdout: |
| 131 | imports.extend([ |
| 132 | 'import contextlib, io', |
| 133 | ]) |
| 134 | stdout = os.pipe() |
| 135 | r_out, w_out = stdout |
| 136 | indented = wrapped.replace('\n', '\n ') |
| 137 | wrapped = cls.STDIO.format( |
| 138 | w_pipe=w_out, |
| 139 | indented=indented, |
| 140 | stream='out', |
| 141 | ) |
| 142 | else: |
| 143 | stdout = None |
| 144 | |
| 145 | # Handle stderr. |
| 146 | if stderr == 'stdout': |
| 147 | stderr = None |
| 148 | elif stderr: |
| 149 | if not stdout: |
| 150 | imports.extend([ |
| 151 | 'import contextlib, io', |
| 152 | ]) |
| 153 | stderr = os.pipe() |
| 154 | r_err, w_err = stderr |
| 155 | indented = wrapped.replace('\n', '\n ') |
| 156 | wrapped = cls.STDIO.format( |
| 157 | w_pipe=w_err, |
| 158 | indented=indented, |
| 159 | stream='err', |
| 160 | ) |
| 161 | else: |
| 162 | stderr = None |
| 163 | |
| 164 | if wrapped == script: |
| 165 | raise NotImplementedError |
| 166 | else: |
| 167 | for line in imports: |