模块导入与否时exec行为差异及异常原因问询
mymodule? Great question—this comes down to a key Python behavior that trips up a lot of folks: how Python decides which directories to search for modules (the sys.path list) based on how you run your code.
Let's get straight to the core rule here:
- When you run a script directly (e.g., typing
python my_script.pyin your terminal), Python automatically adds the directory containing that script to the very start ofsys.path. That means even if the directory wasn't in your system's PATH variable, Python will check it first for any modules you try to import—so it findsmymodule.pyright there in the same directory. - When you import a script as a module (say, running another script that does
import my_script), Python doesn't add the imported script's directory tosys.pathby default. So ifmymodule.pyis in the same folder asmy_script, but that folder isn't insys.path, Python can't locate it, hence the ImportError you saw in the first case.
Let's map this to your scenario with concrete examples:
First script (throws error):
Imagine your first script isscript1.py, sitting in/home/you/code/withmymodule.py. If you run this script by importing it from another file in a different directory—like/home/you/other/run.pythat usesimport code.script1—Python'ssys.pathwill include/home/you/other/(the directory of the script you're actually running), but not/home/you/code/. So whenscript1.pytries toimport mymodule, Python can't find it, and you get the ImportError.Second script (no error):
If you runscript1.pydirectly withpython /home/you/code/script1.py, Python immediately drops/home/you/code/into the front ofsys.path. Now when it hitsimport mymodule, it checks that directory first, findsmymodule.py, and imports it without any issues.
A less likely edge case: if your second script uses relative imports (like from . import mymodule), but that only works if the directory is set up as a proper Python package (with an __init__.py file). But given your description of an empty runtime environment, the direct vs imported script execution difference is almost certainly what's happening here.
内容的提问来源于stack exchange,提问作者Dmitry Torba

