Skip to content

to_process.run_sync fails to set up __main__ in worker process when run from an entry point #1027

Closed

Description

@ilia-kats

Things to check first

  • I have searched the existing issues and didn't find my bug already reported there

  • I have checked that my bug is still present in the latest release

AnyIO version

4.11

Python version

3.11

What happened?

I have a package with an entry point defined in pyproject.toml and I want to run a function in a worker process. The function imports dill, which raises

[snip]

  File "/data/ilia/envs/famo/lib/python3.11/site-packages/dill/_dill.py", line 80, in <module>
    import __main__ as _main_module
          ^^^^^^^^^^^^^^^^^
ModuleNotFoundError: No module named '__main__'

I've tried to debug this a bit, and it turns out that importlib.util.spec_from_file_location (used in the worker process to set up __main__) always returns None if the path does not end in .py or .pyc.

sys.modules["__main__"].__spec__ is also None in that case.

How can we reproduce the bug?

Write a small dummy package with an entry point defined in pyproject.toml that runs a function in a worker process.

Activity

  1. added
    bug
    on Nov 11, 2025
  2. added a commit that references this issue on Feb 17, 2026
    f12be32
  3. tapetersen commented on May 5, 2026

    @tapetersen
    Collaborator

    As noted above this is due to the entry-point scripts not ending in .py and therefore will not be found by the normal loaders.
    This is only one case this can happen with executable scripts run as direct arguments to the python interpreter.

    @agronholm Relevant code:

    # Load the parent's main module but as __mp_main__ instead of
    # __main__ (like multiprocessing does) to avoid infinite recursion
    try:
    spec = spec_from_file_location("__mp_main__", main_module_path)
    if spec and spec.loader:
    main = module_from_spec(spec)
    spec.loader.exec_module(main)
    sys.modules["__main__"] = main
    except BaseException as exc:
    exception = exc
    where you note that it's "inspired" by multiprocessing but they use runpy.run_path instead which doesn't have this problem.
    https://github.com/python/cpython/blob/4fa5c0428213f9b80a2b3e25e49b52e8596d8528/Lib/multiprocessing/spawn.py#L295-L300

    Any reason that couldn't be used here? (I've tested and preliminary it seems to pass everything)

    Edit: PR up at #1134

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions