赞
踩
我的问题是:
I have a folder structure: A B is in the folder C,
The struture:A/a.py B/b.py
I write the following code in b.py
import A.a
now under C I use cmd, type python B/b.py
Then what error would happen? why? and how?
AI 回答道:
When you have a folder structure like the one you’ve described and you try to run python B/b.py
from within the C
directory, you might encounter a few different errors depending on the contents of B/b.py
and how the Python interpreter locates and executes the script. Let’s break down the possible issues:
Import Error: If the import statement import A.a
in b.py
is the first non-decorator statement in the file, Python will attempt to execute this import before running any other code. If the Python interpreter cannot locate the module A.a
, you will get an ImportError
. This can happen if the current working directory is not in the Python path or if the module is not properly installed.
Relative Import Issue: If B/b.py
is a script that you intend to run directly (as a main program), using a relative import like import A.a
might not work as expected because relative imports are based on the name of the current module, not the file’s location on the filesystem. Since B/b.py
is being run directly, it doesn’t have a “name” in the context of a package, which can lead to an import error.
Working Directory: If you’re running python B/b.py
from the C
directory, Python will look for modules in the current working directory first. If A
is not a recognized package (i.e., it doesn’t have an __init__.py
file or isn’t installed in a location that’s in the Python path), then Python won’t be able to find A.a
.
Package Structure: For the import to work properly, the directory A
should be a package, which means it should contain an __init__.py
file. Additionally, the directory C
should be in the Python path, or you should modify the sys.path
in B/b.py
to include the path to A
.
Shebang Line: If B/b.py
starts with a shebang line (#!/usr/bin/env python
or similar), it might be executed as an executable script, which could alter how imports are resolved.
To resolve these issues, you could:
A
is a package by adding an __init__.py
file inside it.sys.path
in b.py
to include the directory containing A
.A
is installed as a package or is in a location known to Python.A
package.Here’s an example of how you might modify sys.path
in b.py
:
import sys
sys.path.append('/path/to/C') # Replace with the actual path to the C directory
import A.a
# Rest of your code...
However, modifying sys.path
at runtime is generally not recommended for production code due to potential security risks and maintenance issues. A better approach would be to structure your code and directories in a way that is naturally discoverable by the Python import system.
但是即使我在加了__init__.py到A文件夹下面后,在C文件夹下运行python B/b.py还是会报错:
ModuleNotFoundError: No module named ‘A’
只有把b.py 移到C文件夹根目录运行python b.py才能解决问题。有没有别的办法?
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。