Carreau: Test are due to a regression in mpl, [fixed there](https://github.com/matplotlib/matplotlib/pull/16709)
diff --git a/IPython/core/magics/execution.py b/IPython/core/magics/execution.py
index 2b26ebe96..fb2df90b5 100644
--- a/IPython/core/magics/execution.py
+++ b/IPython/core/magics/execution.py
@@ -692,6 +692,11 @@ def run(self, parameter_s='', runner=None,
                 warn('For Windows, use double quotes to wrap a filename: %run "mypath\\myfile.py"')
             error(msg)
             return
+        except TypeError:
+            if fpath in sys.meta_path:
+                filename = ""
+            else:
+                raise
 
         if filename.lower().endswith(('.ipy', '.ipynb')):
             with preserve_keys(self.shell.user_ns, '__file__'):
diff --git a/IPython/utils/module_paths.py b/IPython/utils/module_paths.py
index 0570c322e..32ecab850 100644
--- a/IPython/utils/module_paths.py
+++ b/IPython/utils/module_paths.py
@@ -20,6 +20,7 @@
 # Stdlib imports
 import importlib
 import os
+import sys
 
 # Third-party imports
 
@@ -61,6 +62,8 @@ def find_mod(module_name):
     loader = importlib.util.find_spec(module_name)
     module_path = loader.origin
     if module_path is None:
+        if loader.loader in sys.meta_path:
+            return loader.loader
         return None
     else:
         split_path = module_path.split(".")

%run does not work with import hooks
Hi,

I ran into an issue where the use of `imp` vs `__import__` matters. `imp` is bypassing some things that import statements do, such as calling custom [import hooks](https://docs.python.org/3/reference/import.html#import-hooks). Is there are reason `imp` is being used? If not, can this be updated to use `__import__`?

As a note, this comes up when using `%run -m foo`.

Thanks!
diff --git a/IPython/core/tests/test_magic.py b/IPython/core/tests/test_magic.py
index 5f58b110e..e5ad820c1 100644
--- a/IPython/core/tests/test_magic.py
+++ b/IPython/core/tests/test_magic.py
@@ -1198,3 +1198,49 @@ def test_timeit_arguments():
         # 3.7 optimize no-op statement like above out, and complain there is
         # nothing in the for loop.
         _ip.magic("timeit -n1 -r1 a=('#')")
+
+
+TEST_MODULE = """
+print('Loaded my_tmp')
+if __name__ == "__main__":
+    print('I just ran a script')
+"""
+
+
+def test_run_module_from_import_hook():
+    "Test that a module can be loaded via an import hook"
+    with TemporaryDirectory() as tmpdir:
+        fullpath = os.path.join(tmpdir, 'my_tmp.py')
+        with open(fullpath, 'w') as f:
+            f.write(TEST_MODULE)
+
+        class MyTempImporter(object):
+            def __init__(self):
+                pass
+
+            def find_module(self, fullname, path=None):
+                if 'my_tmp' in fullname:
+                    return self
+                return None
+
+            def load_module(self, name):
+                import imp
+                return imp.load_source('my_tmp', fullpath)
+
+            def get_code(self, fullname):
+                with open(fullpath, 'r') as f:
+                    return compile(f.read(), 'foo', 'exec')
+
+            def is_package(self, __):
+                return False
+
+        sys.meta_path.insert(0, MyTempImporter())
+
+        with capture_output() as captured:
+            _ip.magic("run -m my_tmp")
+            _ip.run_cell("import my_tmp")
+
+        output = "Loaded my_tmp\nI just ran a script\nLoaded my_tmp\n"
+        nt.assert_equal(output, captured.stdout)
+
+        sys.meta_path.pop(0)

pip install -e .[all]
parse_log_pytest
requirements.txt
pytest
apt-get update apt-get install -y gcc graphviz
3.9
requirements/base.txt
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
alabaster==0.7.16
anyio==4.9.0
argon2-cffi==23.1.0
argon2-cffi-bindings==21.2.0
arrow==1.3.0
asttokens==3.0.0
async-lru==2.0.5
attrs==25.3.0
babel==2.17.0
backcall==0.2.0
beautifulsoup4==4.13.3
bleach==6.2.0
certifi==2025.1.31
cffi==1.17.1
charset-normalizer==3.4.1
comm==0.2.2
debugpy==1.8.13
decorator==5.2.1
defusedxml==0.7.1
docutils==0.21.2
exceptiongroup==1.2.2
executing==2.2.0
fastjsonschema==2.21.1
fqdn==1.5.1
h11==0.14.0
httpcore==1.0.7
httpx==0.28.1
idna==3.10
imagesize==1.4.1
importlib_metadata==8.6.1
iniconfig==2.1.0
ipykernel==6.29.5
ipyparallel==9.0.1
-e git+https://github.com/ipython/ipython.git@34327182a1578d76e17a9fd1843052994f4dca45#egg=ipython
ipywidgets==8.1.5
isoduration==20.11.0
jedi==0.19.2
Jinja2==3.1.6
json5==0.10.0
jsonpointer==3.0.0
jsonschema==4.23.0
jsonschema-specifications==2024.10.1
jupyter-events==0.12.0
jupyter-lsp==2.2.5
jupyter_client==8.6.3
jupyter_core==5.7.2
jupyter_server==2.15.0
jupyter_server_terminals==0.5.3
jupyterlab==4.3.6
jupyterlab_pygments==0.3.0
jupyterlab_server==2.27.3
jupyterlab_widgets==3.0.13
MarkupSafe==3.0.2
matplotlib-inline==0.1.7
mistune==3.1.3
nbclient==0.10.2
nbconvert==7.16.6
nbformat==5.10.4
nest-asyncio==1.6.0
nose==1.3.7
notebook==7.3.3
notebook_shim==0.2.4
numpy==2.0.2
overrides==7.7.0
packaging==24.2
pandocfilters==1.5.1
parso==0.8.4
pexpect==4.9.0
pickleshare==0.7.5
platformdirs==4.3.7
pluggy==1.5.0
prometheus_client==0.21.1
prompt_toolkit==3.0.50
psutil==7.0.0
ptyprocess==0.7.0
pure_eval==0.2.3
pycparser==2.22
Pygments==2.19.1
pytest==8.3.5
python-dateutil==2.9.0.post0
python-json-logger==3.3.0
PyYAML==6.0.2
pyzmq==26.3.0
qtconsole==5.6.1
QtPy==2.4.3
referencing==0.36.2
requests==2.32.3
rfc3339-validator==0.1.4
rfc3986-validator==0.1.1
rpds-py==0.24.0
Send2Trash==1.8.3
six==1.17.0
sniffio==1.3.1
snowballstemmer==2.2.0
soupsieve==2.6
Sphinx==7.4.7
sphinxcontrib-applehelp==2.0.0
sphinxcontrib-devhelp==2.0.0
sphinxcontrib-htmlhelp==2.1.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==2.0.0
sphinxcontrib-serializinghtml==2.0.0
stack-data==0.6.3
terminado==0.18.1
testpath==0.6.0
tinycss2==1.4.0
tomli==2.2.1
tornado==6.4.2
tqdm==4.67.1
traitlets==5.14.3
types-python-dateutil==2.9.0.20241206
typing_extensions==4.13.0
uri-template==1.3.0
urllib3==2.3.0
wcwidth==0.2.13
webcolors==24.11.1
webencodings==0.5.1
websocket-client==1.8.0
widgetsnbextension==4.0.13
zipp==3.21.0

name: ipython
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - ca-certificates=2025.2.25=h06a4308_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.4.4=h6a678d5_1
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - ncurses=6.4=h6a678d5_0
  - openssl=3.0.16=h5eee18b_0
  - pip=25.0=py39h06a4308_0
  - python=3.9.21=he870216_1
  - readline=8.2=h5eee18b_0
  - setuptools=75.8.0=py39h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - tzdata=2025a=h04d1e81_0
  - wheel=0.45.1=py39h06a4308_0
  - xz=5.6.4=h5eee18b_1
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - alabaster==0.7.16
      - anyio==4.9.0
      - argon2-cffi==23.1.0
      - argon2-cffi-bindings==21.2.0
      - arrow==1.3.0
      - asttokens==3.0.0
      - async-lru==2.0.5
      - attrs==25.3.0
      - babel==2.17.0
      - backcall==0.2.0
      - beautifulsoup4==4.13.3
      - bleach==6.2.0
      - certifi==2025.1.31
      - cffi==1.17.1
      - charset-normalizer==3.4.1
      - comm==0.2.2
      - debugpy==1.8.13
      - decorator==5.2.1
      - defusedxml==0.7.1
      - docutils==0.21.2
      - exceptiongroup==1.2.2
      - executing==2.2.0
      - fastjsonschema==2.21.1
      - fqdn==1.5.1
      - h11==0.14.0
      - httpcore==1.0.7
      - httpx==0.28.1
      - idna==3.10
      - imagesize==1.4.1
      - importlib-metadata==8.6.1
      - iniconfig==2.1.0
      - ipykernel==6.29.5
      - ipyparallel==9.0.1
      - ipywidgets==8.1.5
      - isoduration==20.11.0
      - jedi==0.19.2
      - jinja2==3.1.6
      - json5==0.10.0
      - jsonpointer==3.0.0
      - jsonschema==4.23.0
      - jsonschema-specifications==2024.10.1
      - jupyter-client==8.6.3
      - jupyter-core==5.7.2
      - jupyter-events==0.12.0
      - jupyter-lsp==2.2.5
      - jupyter-server==2.15.0
      - jupyter-server-terminals==0.5.3
      - jupyterlab==4.3.6
      - jupyterlab-pygments==0.3.0
      - jupyterlab-server==2.27.3
      - jupyterlab-widgets==3.0.13
      - markupsafe==3.0.2
      - matplotlib-inline==0.1.7
      - mistune==3.1.3
      - nbclient==0.10.2
      - nbconvert==7.16.6
      - nbformat==5.10.4
      - nest-asyncio==1.6.0
      - nose==1.3.7
      - notebook==7.3.3
      - notebook-shim==0.2.4
      - numpy==2.0.2
      - overrides==7.7.0
      - packaging==24.2
      - pandocfilters==1.5.1
      - parso==0.8.4
      - pexpect==4.9.0
      - pickleshare==0.7.5
      - platformdirs==4.3.7
      - pluggy==1.5.0
      - prometheus-client==0.21.1
      - prompt-toolkit==3.0.50
      - psutil==7.0.0
      - ptyprocess==0.7.0
      - pure-eval==0.2.3
      - pycparser==2.22
      - pygments==2.19.1
      - pytest==8.3.5
      - python-dateutil==2.9.0.post0
      - python-json-logger==3.3.0
      - pyyaml==6.0.2
      - pyzmq==26.3.0
      - qtconsole==5.6.1
      - qtpy==2.4.3
      - referencing==0.36.2
      - requests==2.32.3
      - rfc3339-validator==0.1.4
      - rfc3986-validator==0.1.1
      - rpds-py==0.24.0
      - send2trash==1.8.3
      - six==1.17.0
      - sniffio==1.3.1
      - snowballstemmer==2.2.0
      - soupsieve==2.6
      - sphinx==7.4.7
      - sphinxcontrib-applehelp==2.0.0
      - sphinxcontrib-devhelp==2.0.0
      - sphinxcontrib-htmlhelp==2.1.0
      - sphinxcontrib-jsmath==1.0.1
      - sphinxcontrib-qthelp==2.0.0
      - sphinxcontrib-serializinghtml==2.0.0
      - stack-data==0.6.3
      - terminado==0.18.1
      - testpath==0.6.0
      - tinycss2==1.4.0
      - tomli==2.2.1
      - tornado==6.4.2
      - tqdm==4.67.1
      - traitlets==5.14.3
      - types-python-dateutil==2.9.0.20241206
      - typing-extensions==4.13.0
      - uri-template==1.3.0
      - urllib3==2.3.0
      - wcwidth==0.2.13
      - webcolors==24.11.1
      - webencodings==0.5.1
      - websocket-client==1.8.0
      - widgetsnbextension==4.0.13
      - zipp==3.21.0
prefix: /opt/conda/envs/ipython

IPython/core/tests/test_magic.py::test_run_module_from_import_hook
IPython/core/tests/test_magic.py::test_extract_code_ranges IPython/core/tests/test_magic.py::test_extract_symbols IPython/core/tests/test_magic.py::test_extract_symbols_raises_exception_with_non_python_code IPython/core/tests/test_magic.py::test_magic_not_found IPython/core/tests/test_magic.py::test_cell_magic_not_found IPython/core/tests/test_magic.py::test_magic_error_status IPython/core/tests/test_magic.py::test_config IPython/core/tests/test_magic.py::test_config_available_configs IPython/core/tests/test_magic.py::test_config_print_class IPython/core/tests/test_magic.py::test_rehashx IPython/core/tests/test_magic.py::test_magic_parse_options IPython/core/tests/test_magic.py::test_magic_parse_long_options IPython/core/tests/test_magic.py::test_hist_pof IPython/core/tests/test_magic.py::test_macro IPython/core/tests/test_magic.py::test_macro_run IPython/core/tests/test_magic.py::test_magic_magic IPython/core/tests/test_magic.py::test_numpy_reset_array_undec IPython/core/tests/test_magic.py::test_reset_out IPython/core/tests/test_magic.py::test_reset_in IPython/core/tests/test_magic.py::test_reset_dhist IPython/core/tests/test_magic.py::test_reset_in_length IPython/core/tests/test_magic.py::TestResetErrors::test_reset_redefine IPython/core/tests/test_magic.py::test_tb_syntaxerror IPython/core/tests/test_magic.py::test_time IPython/core/tests/test_magic.py::test_time_last_not_expression IPython/core/tests/test_magic.py::test_time2 IPython/core/tests/test_magic.py::test_time3 IPython/core/tests/test_magic.py::test_multiline_time IPython/core/tests/test_magic.py::test_time_local_ns IPython/core/tests/test_magic.py::test_doctest_mode IPython/core/tests/test_magic.py::test_parse_options IPython/core/tests/test_magic.py::test_dirops IPython/core/tests/test_magic.py::test_cd_force_quiet IPython/core/tests/test_magic.py::test_xmode IPython/core/tests/test_magic.py::test_reset_hard IPython/core/tests/test_magic.py::TestXdel::test_xdel IPython/core/tests/test_magic.py::test_whos IPython/core/tests/test_magic.py::test_psearch IPython/core/tests/test_magic.py::test_timeit_shlex IPython/core/tests/test_magic.py::test_timeit_special_syntax IPython/core/tests/test_magic.py::test_timeit_return IPython/core/tests/test_magic.py::test_timeit_quiet IPython/core/tests/test_magic.py::test_timeit_return_quiet IPython/core/tests/test_magic.py::test_timeit_invalid_return IPython/core/tests/test_magic.py::test_prun_special_syntax IPython/core/tests/test_magic.py::test_prun_quotes IPython/core/tests/test_magic.py::test_extension IPython/core/tests/test_magic.py::test_notebook_export_json IPython/core/tests/test_magic.py::TestEnv::test_env IPython/core/tests/test_magic.py::TestEnv::test_env_get_set_complex IPython/core/tests/test_magic.py::TestEnv::test_env_get_set_simple IPython/core/tests/test_magic.py::TestEnv::test_env_secret IPython/core/tests/test_magic.py::TestEnv::test_env_set_bad_input IPython/core/tests/test_magic.py::TestEnv::test_env_set_whitespace IPython/core/tests/test_magic.py::CellMagicTestCase::test_cell_magic_class IPython/core/tests/test_magic.py::CellMagicTestCase::test_cell_magic_class2 IPython/core/tests/test_magic.py::CellMagicTestCase::test_cell_magic_func_deco IPython/core/tests/test_magic.py::CellMagicTestCase::test_cell_magic_reg IPython/core/tests/test_magic.py::test_file IPython/core/tests/test_magic.py::test_file_single_quote IPython/core/tests/test_magic.py::test_file_double_quote IPython/core/tests/test_magic.py::test_file_var_expand IPython/core/tests/test_magic.py::test_file_unicode IPython/core/tests/test_magic.py::test_file_amend IPython/core/tests/test_magic.py::test_file_spaces IPython/core/tests/test_magic.py::test_script_config IPython/core/tests/test_magic.py::test_script_out IPython/core/tests/test_magic.py::test_script_err IPython/core/tests/test_magic.py::test_script_out_err IPython/core/tests/test_magic.py::test_script_bg_out IPython/core/tests/test_magic.py::test_script_bg_err IPython/core/tests/test_magic.py::test_script_bg_out_err IPython/core/tests/test_magic.py::test_script_defaults IPython/core/tests/test_magic.py::test_line_cell_info IPython/core/tests/test_magic.py::test_multiple_magics IPython/core/tests/test_magic.py::test_alias_magic IPython/core/tests/test_magic.py::test_save IPython/core/tests/test_magic.py::test_store IPython/core/tests/test_magic.py::test_edit_interactive IPython/core/tests/test_magic.py::test_edit_cell IPython/core/tests/test_magic.py::test_bookmark IPython/core/tests/test_magic.py::test_ls_magic IPython/core/tests/test_magic.py::test_strip_initial_indent IPython/core/tests/test_magic.py::test_logging_magic_quiet_from_arg IPython/core/tests/test_magic.py::test_logging_magic_quiet_from_config IPython/core/tests/test_magic.py::test_logging_magic_not_quiet IPython/core/tests/test_magic.py::test_time_no_var_expand IPython/core/tests/test_magic.py::test_timeit_arguments
IPython/utils/module_paths.py IPython/core/magics/execution.py
IPython/utils/module_paths.py IPython/core/magics/execution.py