为什么我不能在不收到关于另一个 python 文件的错误的情况下导入? ("partially initialized module has no attribute")
Why can't I import without getting an error about another python file? ("partially initialized module has no attribute")
我正在尝试导入请求模块以熟悉 bs4,但我当前使用的文件中的请求模块显示为灰色,因此未被识别为模块。当我 运行 几乎是空的程序时,我在项目中遇到不相关 python 文件的错误。
我是否应该将制作的每个 python 文件单独存储在单独的文件夹中?
这两个文件都在同一个项目文件夹中。
import requests
response = get('https://www.newegg.ca/p/N82E16868105274')
print(response.raise_for_status())
错误:
Traceback (most recent call last):
File "C:\Users\Denze\MyPythonScripts\Webscraping learning\beautifulsoup tests.py", line 1, in <module>
import requests
File "C:\Users\Denze\MyPythonScripts\requests.py", line 3, in <module>
res = requests.get('')
AttributeError: partially initialized module 'requests' has no attribute 'get' (most likely due to a circular import)
Process finished with exit code 1
我认为导致我出错的其他有问题的代码:
import requests
res = requests.get('')
playFile = ('TestDownload.txt', 'wb')
for chunk in res.iter_content(100000):
playFile.write(chunk)
playFile.close()
你有一个名字冲突。您不是在导入 requests
库,而是在导入您的脚本。
您想对导入执行以下操作:
MyPythonScripts\beautifulsoup tests.py
→ requests.get() (the library)
你正在做的是:
MyPythonScripts\beautifulsoup tests.py
→ MyPythonScripts\requests.py
→ MyPythonScripts\requests.py .get() (the same file again)
这就是回溯中提到的“循环导入”。该模块导入自身并尝试使用在完成“执行”之前不存在的属性,因此解释器认为这是由于未完成的初始化
Raname MyPythonScripts\requests.py
到别的东西,它应该工作。
我正在尝试导入请求模块以熟悉 bs4,但我当前使用的文件中的请求模块显示为灰色,因此未被识别为模块。当我 运行 几乎是空的程序时,我在项目中遇到不相关 python 文件的错误。
我是否应该将制作的每个 python 文件单独存储在单独的文件夹中? 这两个文件都在同一个项目文件夹中。
import requests
response = get('https://www.newegg.ca/p/N82E16868105274')
print(response.raise_for_status())
错误:
Traceback (most recent call last):
File "C:\Users\Denze\MyPythonScripts\Webscraping learning\beautifulsoup tests.py", line 1, in <module>
import requests
File "C:\Users\Denze\MyPythonScripts\requests.py", line 3, in <module>
res = requests.get('')
AttributeError: partially initialized module 'requests' has no attribute 'get' (most likely due to a circular import)
Process finished with exit code 1
我认为导致我出错的其他有问题的代码:
import requests
res = requests.get('')
playFile = ('TestDownload.txt', 'wb')
for chunk in res.iter_content(100000):
playFile.write(chunk)
playFile.close()
你有一个名字冲突。您不是在导入 requests
库,而是在导入您的脚本。
您想对导入执行以下操作:
MyPythonScripts\beautifulsoup tests.py
→ requests.get() (the library)
你正在做的是:
MyPythonScripts\beautifulsoup tests.py
→ MyPythonScripts\requests.py
→ MyPythonScripts\requests.py .get() (the same file again)
这就是回溯中提到的“循环导入”。该模块导入自身并尝试使用在完成“执行”之前不存在的属性,因此解释器认为这是由于未完成的初始化
Raname MyPythonScripts\requests.py
到别的东西,它应该工作。