0

I have this module named say a.py in the directory /home/ssridhar/Python. This module contains a function say

def number_haloes(n):
    halo_param = var2['halo_id'][z1]
    print len(halo_param)

I have another module say b.py in the directory /home/ssridhar/Python/mean.

I want to use the def number_haloes from a.py in b.py

I tried import a but it is showing ImportError: No module named a

How do I do this task?

Srivatsan
  • 9,225
  • 13
  • 58
  • 83
  • I believe you can use ```__import__()``` to specify the full path and file name – wnnmaw Mar 06 '14 at 15:33
  • @wnnmaw should i say __import__(/home/ssridhar/Python/a.py) ?? – Srivatsan Mar 06 '14 at 15:34
  • It would be ```a = __import__(r"/home/ssridhar/Python/a.py")``` I think, but you should read [the docs](http://docs.python.org/2/library/functions.html#__import__) to double check – wnnmaw Mar 06 '14 at 15:36
  • But you might be better off throwing ```os.path.abspath()``` around your name to avoid complications – wnnmaw Mar 06 '14 at 15:38
  • doesn't this solves the issue: http://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path?rq=1 – Svend Mar 06 '14 at 15:42
  • @Svend Yep, and this is probably a dupe, good find – wnnmaw Mar 06 '14 at 16:00
  • @wnnmaw but when I follow the answer there, it runs my a.py!! I only want to use the def inside a.py – Srivatsan Mar 06 '14 at 16:26

1 Answers1

0

You need to add "/home/ssridhar/Python" to your python path. Only then Python will know how to load a.py. For instance you can try this

import sys
sys.path.append('/home/ssridhar/Python')

import a
skar
  • 401
  • 5
  • 15
  • when I try this, this runs my a.py!! I only want to use the def inside a.py – Srivatsan Mar 06 '14 at 16:27
  • unless there is a call to the function in a.py it won't get executed. Can you post what all is there in a.py. – skar Mar 06 '14 at 16:32
  • well it is a big program! But what it does it, it takes two files, compares them with some input conditions and writes out several files according to the conditions.. This def inside the function, just tells me how many files are there in each file being written – Srivatsan Mar 06 '14 at 16:42
  • What I mean is in a.py if you are calling `number_haloes(n)` then it will get executed every time a gets imported. You can try to add the function calls under an if condition for instance- `if __name__ == "__main__": number_haloes(n)` [read](http://stackoverflow.com/questions/419163/what-does-if-name-main-do) – skar Mar 07 '14 at 01:46
  • This will stop the function from executing if `a` is getting imported in an another module. – skar Mar 07 '14 at 01:54