Calling a Python function from another file

老子叫甜甜 提交于 2019-12-06 12:46:48

The problem is with this line:

helpers.hello()

Replace it with this:

hello()

Now it works because you've only imported the name hello from the helpers module. You haven't imported the name helpers itself.

So you can have this:

from helpers import hello
hello()

Or you can have this:

import helpers
helpers.hello()
Jack Zhao

I reset the CLASSPATH and it works fine somehow. Weird problem. Thanks everyone!

from helpers import hello
....
helpers.hello()   ## You didn't import the helpers namespace.

Your problem is a matter of understanding namespaces. You didn't import the helpers namespace...which is why the interpreter doesn't recognize the helpers. I would strongly recommend you read up on namespaces, as they are very useful in python.

Namespace Document 1

Offical Python Namespace Document

Take a look at these links above.

The python interpreter does not find your module "helpers".

With what operating system do you work?

When you are under Unix/Linux or similar, and your files are in the same directory, it should work. But I heard, that there are troubles working for example on Windows. Maybe, there must be a search path set.

See here: https://docs.python.org/2/tutorial/modules.html#the-module-search-path

Edit: Michael is right, when you do "from helpers import ..." than not the module is importet as such, but only hello is known to the system!

Just do

from helpers import hello
hello()

Or:

import helpers
helpers.hello()

Still the import error must be solved. For that, it would be useful to know your system and directory structure! On a system like Windows, it might be necessary, to set PYTHONPATH accordingly (see link above).

can't comment, but are the two files in the same folder? I would try:

from helpers.py import hello

File system :

__init__.py
helpers.py      <- 'hello' function 
utils
   __init__.py  <- functions/classes
   barfoo.py
main.py

in main...

from helpers import hello
hello()
import utils        # which ever functions/classes defined in the __init__.py file. 
from utils import * # adds barfoo the namespace or you could/should name directly. 

follow the importing modules in the docs

I had the same problem: ModuleNotFoundError: No module named "Module_Name". In my case, both the module and the script I was calling it to were in the same directory, however, my work directory was not correct. After I changed my working directory using the following, my import worked:

import os
os.chdir("C:\\Path\to\desired\directory")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!