如何在Python 3中运行包含子文件夹导入的脚本?
First, let's lock in your project structure to make sure we're aligned (this is what I'm assuming you're working with):
proj/ ├── run.py └── subfolder/ └── foofile.py
Where foofile.py contains your function:
def foofun(): print("Hello from foofun!")
Below are three reliable solutions, ordered from most Pythonic (and recommended) to quick-and-dirty for testing:
1. Turn the Subfolder into a Proper Package (Best Practice)
This is the standard, maintainable way to handle imports in Python projects, and it works seamlessly across all Python 3 versions.
- Step 1: Create an empty
__init__.pyfile insidesubfolder. This tells Python thatsubfolderis an importable package (note: Python 3.3+ supports namespace packages without this file, but adding it ensures compatibility with older versions and tools like pytest).
Your updated structure will look like:proj/ ├── run.py └── subfolder/ ├── __init__.py └── foofile.py - Step 2: Update
run.pyto import the function using the package path:# Option A: Import the function directly from subfolder.foofile import foofun # Option B: Import the module and call the function through it # import subfolder.foofile as foo_module if __name__ == "__main__": foofun() # foo_module.foofun() - Step 3: Run the script from the proj root directory with:
python run.py
2. Temporarily Add the Subfolder to Python's Path (Quick Debugging)
If you need a fast fix without restructuring your project, you can manually add the subfolder to Python's module search path. This is great for testing but not recommended for production code, as it's fragile to changes in your project structure.
Update run.py like this:
import sys import os # Get the absolute path to the proj root directory proj_root = os.path.dirname(os.path.abspath(__file__)) # Add the subfolder path to Python's search list sys.path.append(os.path.join(proj_root, "subfolder")) # Now you can import foofile directly from foofile import foofun if __name__ == "__main__": foofun()
Run it the same way as before: python run.py from the proj root.
3. Use Relative Imports (For Package-Based Projects)
This works if you plan to treat proj as a full Python package (e.g., if you're going to distribute it via pip). Note that you can't run run.py directly as a script with this method—you have to execute it as a module.
Update run.py with a relative import:
from .subfolder.foofile import foofun if __name__ == "__main__": foofun()
Then run it from the parent directory of proj (not inside proj itself):
python -m proj.run
Quick Tips to Avoid Import Headaches
- Double-check that you're using the correct Python environment (virtualenv, conda, etc.)—environment mismatches often cause weird import failures.
- Don't move script files without updating your import paths or sys.path adjustments.
- For larger projects, consider setting up a
pyproject.tomlorsetup.pyto formalize your package structure—this makes imports even smoother and enables easy installation.
内容的提问来源于stack exchange,提问作者Watchduck

