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

运行main.py遇ValueError: Attempted relative import in non-package错误求助

Fixing "ValueError: Attempted relative import in non-package" in Your Python Project

Hey there! I totally get the confusion with relative imports—they can be tricky when you're trying to run a script directly inside a package. Let's break down what's happening and how to fix it.

Why This Error Happens

Relative imports (like from . import a,b) are designed to work within a Python package—meaning when the module is being imported as part of the package, not run as a standalone script. When you execute python main.py directly, Python treats main.py as a top-level script, not as part of the test package. That's why it doesn't recognize the . (which refers to the current package) in your import statement.

Solutions to Try

Instead of running main.py directly, use Python's -m flag to execute it as part of the test package. Here's how:

  • Navigate to the parent directory of your test folder (the folder that contains test/).
  • Run this command:
    python -m test.main
    

This tells Python to treat test as a package, and main as a module within it—so your relative imports will work exactly as intended.

2. Switch to Absolute/Direct Imports (For Quick Script Execution)

If you just want to run main.py directly from inside the test folder, you can modify the import statement to skip the relative path:
Change your main.py code to:

import a, b
a.test()
b.testing()

Then run it normally with:

python main.py

This works because when you run the script from the test folder, that directory is added to Python's module search path, so it can find a.py and b.py directly.

If you want to keep relative imports but still run main.py directly, you can manually add the package directory to Python's path. Add this at the top of main.py:

import sys
import os

# Add the current directory to the module search path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from . import a, b
a.test()
b.testing()

While this works, it's not ideal for production code since it bypasses Python's normal package structure rules.

A Note on the Official Docs

The "6.4.2. Intra-package References" section you looked at covers imports between modules within a package (like importing a from b.py). It doesn't cover the edge case of running a package module as the main script—this is where the confusion usually comes from!

内容的提问来源于stack exchange,提问作者iamsanga

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 18:32:37