Skip to main content
 首页 » 编程设计

python之以 .py 运行时出现随机模块错误

2025年05月04日20grandyang

当您以 .py 运行它时,它不会加载 random 的特定模块。但是如果我在 python shell 中加载它,我没有问题。

# -*- coding: utf-8 -*- 
#!/usr/bin/env python 
 
import random 
print(random.randint(0,9)) 

我运行它...并且:

Traceback (most recent call last): 
  File "random.py", line 4, in <module> 
    import random 
  File "C:\Users\root\Pythin\random.py", line 5, in <module> 
    print(random.randint(0,9)) 
AttributeError: module 'random' has no attribute 'randint' 

在 python shell 中我没有问题:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import random 
>>> print(random.randint(0,9)) 
1 

我在 Windows PowerShell (Windows10|64bits) 中运行它。使用命令 python random.py。有人帮我吗?非常感谢。

请您参考如下方法:

将代码的文件名更改为“myrandom.py”。然后运行程序。

更新:请不要将您的 Python 源代码文件命名为标准模块。因为它会导致错误。因为现在不是导入 python 的标准库 RANDOM,而是 python 导入这个 random.py 并导致错误。

例如不要给你的 python 源代码命名等:

  1. 随机.py
  2. 时间.py
  3. csv.py
  4. 等等………………