添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
我在计算机建立了d:\bag文件夹,并创建了__init__.py文件,并保存在D:\bag下。在已经创建bag包中创建了一个名称time的模块。
运行以下代码出错,请给指导一下。

import bag.time
if name ==’ main ‘:
print(bag.time.minutes)
报错为Traceback (most recent call last):
File “C:\Program Files\149-3.py”, line 1, in
import bag.time
ModuleNotFoundError: No module named ‘bag’

如果没有, 你会得到 ModuleNotFoundError: No module named 'bag'

The first entry in the module search path is the directory that contains the input script, if there is one.

The PYTHONPATH environment variable is often used to add directories to the search path. If this environment variable is found then the contents are added to the module search path.

For WIN10,

WIN+R > sysdm.cpl > OK > Advanced > Environment Variables > System Variables > PYTHONPATH > Edit

File "D:\bag\149-6.py", line 3, in from bag import time ModuleNotFoundError: No module named 'bag' 谢谢您了。

If you run the script by python directly, not under PyCharm / VS Code / Virtual Environment or else.

C:\>python
Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', 'C:\\Software\\Python\\python39.zip', 'C:\\Software\\Python\\DLLs', 'C:\\Software\\Python\\lib', 'C:\\Software\\Python', 'C:\\Software\\Python\\lib\\site-packages', 'C:\\Software\\Python\\lib\\site-packages\\win32', 'C:\\Software\\Python\\lib\\site-packages\\win32\\lib', 'C:\\Software\\Python\\lib\\site-packages\\Pythonwin', 'D:\\Python\\Project\\OK', 'C:\\', 'C:\\Software\\Python\\python310.zip']
>>> from bag import time
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'bag'
>>> sys.path.append("D:\\")
>>> sys.path
['', 'C:\\Software\\Python\\python39.zip', 'C:\\Software\\Python\\DLLs', 'C:\\Software\\Python\\lib', 'C:\\Software\\Python', 'C:\\Software\\Python\\lib\\site-packages', 'C:\\Software\\Python\\lib\\site-packages\\win32', 'C:\\Software\\Python\\lib\\site-packages\\win32\\lib', 'C:\\Software\\Python\\lib\\site-packages\\Pythonwin', 'D:\\Python\\Project\\OK', 'C:\\', 'C:\\Software\\Python\\python310.zip', 'D:\\']
>>> from bag import time
<module 'bag.time' from 'D:\\bag\\time.py'>
>>> quit()
C:\>d:
d:\>cd bag
d:\bag>dir
 Volume in drive D is DATA
 Volume Serial Number is 627D-9CEA
 Directory of d:\bag
01/13/2023  09:45 PM    <DIR>          .
01/13/2023  09:45 PM    <DIR>          ..
01/13/2023  09:44 PM                38 time.py
01/13/2023  09:42 PM                 0 __init__.py
01/13/2023  09:45 PM    <DIR>          __pycache__
               2 File(s)             38 bytes
               3 Dir(s)  548,079,394,816 bytes free
d:\bag>type __init__.py
d:\bag>type time.py
def foo():
    print('Hello World !')