相关疑难解决方法(0)

从脚本导入已安装的包会引发"AttributeError:module has no attribute"或"ImportError:无法导入名称"

我有一个名为的脚本requests.py导入请求包.该脚本无法访问包中的属性,也无法导入它们.为什么这不起作用,我该如何解决?

以下代码提出了一个问题AttributeError.

import requests

res = requests.get('http://www.google.ca')
print(res)
Run Code Online (Sandbox Code Playgroud)
Traceback (most recent call last):
  File "/Users/me/dev/rough/requests.py", line 1, in <module>
    import requests
  File "/Users/me/dev/rough/requests.py", line 3, in <module>
    requests.get('http://www.google.ca')
AttributeError: module 'requests' has no attribute 'get'
Run Code Online (Sandbox Code Playgroud)

以下代码提出了一个问题ImportError.

from requests import get

res = get('http://www.google.ca')
print(res)
Run Code Online (Sandbox Code Playgroud)
Traceback (most recent call last):
  File "requests.py", line 1, in <module>
    from requests import get
  File "/Users/me/dev/rough/requests.py", line 1, in <module>
    from requests import get
ImportError: cannot import name 'get' …
Run Code Online (Sandbox Code Playgroud)

python exception python-module shadowing

43
推荐指数
2
解决办法
1万
查看次数

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

当您将其作为.py运行时,它不会加载random的特定模块。但是,如果我将其加载到python shell中,则不会有任何问题。

# -*- coding: utf-8 -*-
#!/usr/bin/env python

import random
print(random.randint(0,9))
Run Code Online (Sandbox Code Playgroud)

我运行它...并且:

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'
Run Code Online (Sandbox Code Playgroud)

并且在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
Run Code Online (Sandbox Code Playgroud)

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

python random powershell

1
推荐指数
1
解决办法
427
查看次数