[英]Python No module Error with Visual Studio 2013
I am trying to run some python 3.4 example on visual studio 2013. when I try to import
some module from a parent folder and run it from inside visual studio 2013, I always has the error of ImportError: No module named 'foo'
我正在尝试在 Visual Studio 2013 上运行一些 python 3.4 示例。当我尝试从父文件夹import
某个模块并从 Visual Studio 2013 内部运行它时,我总是遇到ImportError: No module named 'foo'
However, when I run it from the console using the python command python boo.py
, it executes well.但是,当我使用 python 命令python boo.py
从控制台运行它时,它执行得很好。
As an example, this is my project structure例如,这是我的项目结构
myproject/
foo.py
__init__.py
koo/
boo.py
__init__.py
foo.py
content is foo.py
内容是
def do1():
print('Inside foo module')
boo.py
content is boo.py
内容是
import sys
sys.path.append("..")
import foo
foo.do1()
I guess, this issue is not about Visual Studio and not about why it doesn't work in VS.我想,这个问题与 Visual Studio 无关,也与为什么它在 VS 中不起作用有关。 The real question is why it works in the terminal.真正的问题是它为什么在终端中工作。 Probably it is because the terminal runs under different environmental settings, where the python interpreter can find the parent directory and thus the foo.py:可能是因为终端运行在不同的环境设置下,python解释器可以找到父目录,从而找到foo.py:
When a module named spam is imported, the interpreter first searches for a built-in module with that name.当导入名为 spam 的模块时,解释器首先搜索具有该名称的内置模块。 If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path.如果未找到,它将在变量 sys.path 给出的目录列表中搜索名为 spam.py 的文件。 sys.path is initialized from these locations: sys.path 从这些位置初始化:
the directory containing the input script (or the current directory).包含输入脚本的目录(或当前目录)。
PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH). PYTHONPATH(目录名称列表,与 shell 变量 PATH 具有相同的语法)。
After initialization, Python programs can modify sys.path.初始化后,Python 程序可以修改 sys.path。 The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path.包含正在运行的脚本的目录位于搜索路径的开头,在标准库路径之前。 This means that scripts in that directory will be loaded instead of modules of the same name in the library directory.这意味着将加载该目录中的脚本而不是库目录中的同名模块。 This is an error unless the replacement is intended.这是一个错误,除非更换是有意的。 See section Standard Modules for more information.有关更多信息,请参阅标准模块部分。
So, add the parent dir to pythonpath, and it will work.因此,将父目录添加到 pythonpath,它将起作用。 Or modify sys.path adding the parent dir to it.或者修改 sys.path 添加父目录。
Try this it worked for me:试试这个它对我有用:
import sys
sys.path.append("Folder PATH"). "Folder PATH" given as...C:\\Working_directory\\VSProject
import <MODULE_NAME>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.