简体   繁体   中英

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'

However, when I run it from the console using the python command python boo.py , it executes well.

As an example, this is my project structure

myproject/
  foo.py
  __init__.py
  koo/
    boo.py
    __init__.py

foo.py content is

def do1():
  print('Inside foo module')

boo.py content is

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. 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:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. 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 is initialized from these locations:

  • 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).

  • the installation-dependent default.

After initialization, Python programs can modify 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. Or modify sys.path adding the parent dir to it.

Try this it worked for me:

import sys
 sys.path.append("Folder PATH"). "Folder PATH" given as...C:\\Working_directory\\VSProject
import <MODULE_NAME> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM