简体   繁体   English

为什么我无法导入自己的 os 模块?

[英]Why am I unable to import my own os module?

I am using Python 3.10.我正在使用 Python 3.10。

  1. I created a module os.py in a directory, my_dir .我在目录my_dir os.py
  2. I am trying to access my os.py using import os , from my_dir directory.我正在尝试使用import osmy_dir目录访问我的os.py
  3. But it is loading Python's os module, not mine.但它正在加载 Python 的os模块,而不是我的。
  4. I inserted my_dir in sys.path as a first element, but still it's loading Python's os module.我在sys.path中插入my_dir作为第一个元素,但它仍在加载 Python 的os模块。
  5. I repeated the same with another standard library of Python 3, datetime .我对另一个标准库 Python 3, datetime重复了同样的操作。 But it's working as expected.但它按预期工作。 ie, it's loading my datetime.py , not Python's.即,它正在加载我的datetime.py ,而不是 Python 的。

Why does only the os module have this problem?为什么只有os模块有这个问题? Is it a bug in Python 3?它是 Python 3 中的错误吗?

if you want to import some module A that happens to have the name of some other module B, that its placement in the import hierarchy mean that module B is found first, then you need to use a relative import to clearly differentiate between the two from withing modules in the same package如果您想导入某个模块 A 恰好具有某个其他模块 B 的名称,那么它在导入层次结构中的位置意味着首先找到模块 B,那么您需要使用相对导入来清楚地区分两者同一个package中的模块

for example, said you have例如,说你有

my_dir
    __init__.py
    os.py
    app.py

for app.py to use your os.py you do让 app.py 使用你的 os.py 你做

from .os import X

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM