Set_up:我有一个.py文件,用于我需要在程序中使用的每个函数.
在这个程序中,我需要从外部文件调用该函数.
我试过了:
from file.py import function(a,b)
Run Code Online (Sandbox Code Playgroud)
但我得到错误:
ImportError:没有名为'file.py'的模块; 文件不是包
我该如何解决这个问题?
我有一个名为的脚本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 3.7 和 pycharm,但我正在从命令行运行我的代码,对于我使用 pytest 的单元测试。
我的项目结构是:
my_message_validator/
__init__.py
module_1/
__init.py__
foo.py
module_2/
__init.py__
bar.py
baz.py
module_3
context.py
test_all.py
Run Code Online (Sandbox Code Playgroud)
模块_1。初始化.py
from module_1 import foo
Run Code Online (Sandbox Code Playgroud)
模块_2。初始化.py
# For some reason pycharm doesnt complain when I use '.' but if I use module_2 it does
from . import bar, baz
Run Code Online (Sandbox Code Playgroud)
如果我尝试从命令行运行我的代码或我的测试,无论我如何移动,我似乎都得到了ModuleNotFoundError: No module named,当我设法让测试工作时,我仍然无法从命令行单独运行我的代码。
如何导入module_1到module_2并且这些居然包?我来自 java,发现导入更容易理解,我发现 python 导入非常混乱......
另外,我如何才能将我需要的任何内容导入到我的测试 module\package\folders 中context.py?
目前测试上下文如下所示:
import os
import sys
# Is …Run Code Online (Sandbox Code Playgroud) python ×3
exception ×1
file ×1
function ×1
import ×1
module ×1
package ×1
python-3.7 ×1
python-3.x ×1
shadowing ×1