Determine how the script was executed, and return the args needed to execute it again in a new process.
()
| 167 | |
| 168 | |
| 169 | def _get_args_for_reloading() -> list[str]: |
| 170 | """Determine how the script was executed, and return the args needed |
| 171 | to execute it again in a new process. |
| 172 | """ |
| 173 | if sys.version_info >= (3, 10): |
| 174 | # sys.orig_argv, added in Python 3.10, contains the exact args used to invoke |
| 175 | # Python. Still replace argv[0] with sys.executable for accuracy. |
| 176 | return [sys.executable, *sys.orig_argv[1:]] |
| 177 | |
| 178 | rv = [sys.executable] |
| 179 | py_script = sys.argv[0] |
| 180 | args = sys.argv[1:] |
| 181 | # Need to look at main module to determine how it was executed. |
| 182 | __main__ = sys.modules["__main__"] |
| 183 | |
| 184 | # The value of __package__ indicates how Python was called. It may |
| 185 | # not exist if a setuptools script is installed as an egg. It may be |
| 186 | # set incorrectly for entry points created with pip on Windows. |
| 187 | if getattr(__main__, "__package__", None) is None or ( |
| 188 | os.name == "nt" |
| 189 | and __main__.__package__ == "" |
| 190 | and not os.path.exists(py_script) |
| 191 | and os.path.exists(f"{py_script}.exe") |
| 192 | ): |
| 193 | # Executed a file, like "python app.py". |
| 194 | py_script = os.path.abspath(py_script) |
| 195 | |
| 196 | if os.name == "nt": |
| 197 | # Windows entry points have ".exe" extension and should be |
| 198 | # called directly. |
| 199 | if not os.path.exists(py_script) and os.path.exists(f"{py_script}.exe"): |
| 200 | py_script += ".exe" |
| 201 | |
| 202 | if ( |
| 203 | os.path.splitext(sys.executable)[1] == ".exe" |
| 204 | and os.path.splitext(py_script)[1] == ".exe" |
| 205 | ): |
| 206 | rv.pop(0) |
| 207 | |
| 208 | rv.append(py_script) |
| 209 | else: |
| 210 | # Executed a module, like "python -m werkzeug.serving". |
| 211 | if os.path.isfile(py_script): |
| 212 | # Rewritten by Python from "-m script" to "/path/to/script.py". |
| 213 | py_module = t.cast(str, __main__.__package__) |
| 214 | name = os.path.splitext(os.path.basename(py_script))[0] |
| 215 | |
| 216 | if name != "__main__": |
| 217 | py_module += f".{name}" |
| 218 | else: |
| 219 | # Incorrectly rewritten by pydevd debugger from "-m script" to "script". |
| 220 | py_module = py_script |
| 221 | |
| 222 | rv.extend(("-m", py_module.lstrip("."))) |
| 223 | |
| 224 | rv.extend(args) |
| 225 | return rv |
| 226 |