{
  "$type": "site.standard.document",
  "canonicalUrl": "https://rednafi.com/python/how-not-to-run-a-script/",
  "description": "Fix Python ModuleNotFoundError by using python -m instead of direct script execution to ensure correct sys.path handling for imports.",
  "path": "/python/how-not-to-run-a-script/",
  "publishedAt": "2022-03-16T00:00:00.000Z",
  "site": "at://did:plc:fgtm2c26vfcj74rfmeggbyqj/site.standard.publication/3mnl6f7ob462z",
  "tags": [
    "Python"
  ],
  "textContent": "When I first started working with Python, nothing stumped me more than how bizarre Python's\nimport system seemed to be. Often time, I wanted to run a module inside of a package with\nthe python src/sub/module.py command, and it'd throw an ImportError that didn't make any\nsense. Consider this package structure:\n\nLet's say you're importing module a in module b:\n\nNow, if you try to run module b.py with the following command, it'd throw an import error:\n\nWhat! But you can see the src/a.py module right there. Why can't Python access the module\nhere? Turns out Python puts the path of the module that you're trying to access to the top\nof the sys.path stack. Let's print the sys.path before importing module a in the\nsrc/sub/b.py file:\n\nNow running this module with python src/sub/b.py will print the following:\n\nFrom the first section of the above output, it's evident that Python looks for the imported\nmodule in the src/sub/ directory, not in the root directory from where the command is\nbeing executed. That's why it can't find the a.py module because it exists in a directory\nabove the sys.path's first entry. To solve this, you should run the module with the -m\nswitch as follows:\n\nThis will not raise the import error and return the following output:\n\nHere, the first entry denotes the root directory from where the script is being run from.\nVoila, problem solved!\n\nFurther reading\n\n- [Don't run python my/script.py]\n\n\n\n\n[don't run python my/script.py]:\n    https://www.youtube.com/watch?v=hgCVIa5qQhM",
  "title": "How not to run a script in Python"
}