How can I import functions from another python file

Y

yinglcs

Hi,
i have 2 python files in *different directory* , how can I import
python functions from 1 python file to another?

i get this error:
import task
ImportError: No module named task/

Thank you.
 
L

Lee Harr

Hi,
i have 2 python files in *different directory* , how can I import
python functions from 1 python file to another?

i get this error:
import task
ImportError: No module named task/


The directory that module is in must by on your python
path in order to import it. You can do it by modifying
sys.path or by setting the PYTHONPATH env variable.


$ mkdir otherdir
$ cat > otherdir/amod.py
def afunc():
return 'found'
$ pythonTraceback (most recent call last):
'found'
 
S

Shane Geiger

The directory that module is in must by on your python
path in order to import it.
That's not exactly correct. You *can* import from files that aren't in
your sys.path. What follows is a full-working (with python 2.5)
example. Perhaps ihooks is going to be obsolete at some point, but it
works now. See PEP 302 for more info. (I'm not sure how to modify this
example to work with a newer import mechanism or else I would provide it
to you.)



import os
def writefile(f, data, perms=750): open(f, 'w').write(data) and
os.chmod(f, perms)

foobar = """
print "this is from the foobar module"

def x():
print "This is the x function."

"""

writefile('/tmp/foobar.py', foobar)


# File:ihooks-example-1.py
import ihooks, imp, os, sys
def import_from(filename):
"Import module from a named file"
if not os.path.exists(filename):
sys.stderr.write( "WARNING: Cannot import file." )
loader = ihooks.BasicModuleLoader()
path, file = os.path.split(filename)
name, ext = os.path.splitext(file)
m = loader.find_module_in_dir(name, path)
if not m:
raise ImportError, name
m = loader.load_module(name, m)
return m

foo = import_from("/tmp/foobar.py")

print foo.x
print foo.x()
print foo.x()



You can do it by modifying
sys.path or by setting the PYTHONPATH env variable.


$ mkdir otherdir
$ cat > otherdir/amod.py
def afunc():
return 'found'
$ python

Traceback (most recent call last):

'found'

--
Shane Geiger
IT Director
National Council on Economic Education
(e-mail address removed) | 402-438-8958 | http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top