Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Python function from another file

This problem has confused me for days.

I have two files, helpers.py and launcher.py.

In helpers.py I have defined the function hello(), which prints "hello".

I want to call hello() in launcher.py.

This is what I wrote in launcher.py:

from helpers import hello
....
helpers.hello()

But when I run it, I get this:

    from helpers import hello
ImportError: No module named helpers

How do I fix this?

Edit in response to answers / comments

  1. I'm using OS X and Python 3.4
  2. The two files are in the same directory
  3. I tried the two ways:

    from helpers import hello
    hello()
    

    and

    import helpers
    helpers.hello()
    

    But still this bug:

    import helpers
    ImportError: No module named 'helpers'
    

I think there should be something wrong in the CLASSPATH of Terminal.

Second edit

The problem highlighted in these answers was an issue, but in the end resetting the classpath resolved.

like image 781
Jack Zhao Avatar asked Dec 08 '22 02:12

Jack Zhao


2 Answers

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()
like image 185
Michael Laszlo Avatar answered Dec 28 '22 18:12

Michael Laszlo


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

like image 29
Jack Zhao Avatar answered Dec 28 '22 19:12

Jack Zhao