You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

模块导入与否时exec行为差异及异常原因问询

Why isn't the second script throwing an ImportError for 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.py in your terminal), Python automatically adds the directory containing that script to the very start of sys.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 finds mymodule.py right 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 to sys.path by default. So if mymodule.py is in the same folder as my_script, but that folder isn't in sys.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:

  1. First script (throws error):
    Imagine your first script is script1.py, sitting in /home/you/code/ with mymodule.py. If you run this script by importing it from another file in a different directory—like /home/you/other/run.py that uses import code.script1—Python's sys.path will include /home/you/other/ (the directory of the script you're actually running), but not /home/you/code/. So when script1.py tries to import mymodule, Python can't find it, and you get the ImportError.

  2. Second script (no error):
    If you run script1.py directly with python /home/you/code/script1.py, Python immediately drops /home/you/code/ into the front of sys.path. Now when it hits import mymodule, it checks that directory first, finds mymodule.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:28:29