473,769 Members | 7,408 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can I import functions from another python file

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.

Apr 9 '07 #1
3 12090
On 2007-04-09, yi*****@gmail.c om <yi*****@gmail. comwrote:
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'
$ python
>>import amod
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ImportError: No module named amod
>>import sys
sys.path.appe nd('otherdir')
import amod
amod.afunc( )
'found'
Apr 9 '07 #2
En Mon, 09 Apr 2007 18:06:11 -0300, yi*****@gmail.c om <yi*****@gmail. com>
escribió:
i have 2 python files in *different directory* , how can I import
python functions from 1 python file to another?
See the tutorial about modules, packages, and the module search path:
http://docs.python.org/tut/node8.html
You can extend the search path using .pth files:
http://docs.python.org/lib/module-site.html
(but consider using packages instead of cluttering your search path with
infinite entries)

--
Gabriel Genellina

Apr 9 '07 #3
>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.
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(fil ename):
"Import module from a named file"
if not os.path.exists( filename):
sys.stderr.writ e( "WARNING: Cannot import file." )
loader = ihooks.BasicMod uleLoader()
path, file = os.path.split(f ilename)
name, ext = os.path.splitex t(file)
m = loader.find_mod ule_in_dir(name , path)
if not m:
raise ImportError, name
m = loader.load_mod ule(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
>>>import amod
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ImportError: No module named amod
>>>import sys
sys.path.app end('otherdir')
import amod
amod.afunc ()
'found'
--
Shane Geiger
IT Director
National Council on Economic Education
sg*****@ncee.ne t | 402-438-8958 | http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy
Apr 10 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3119
by: Steve | last post by:
Hi, I've written a small cgi python script that collects feedback from a webform. I need to pass the values to another python script.. how do I do this? Is this even possible? Thanks Steve
3
3998
by: | last post by:
Hi everybody, I'm sure there's a way to do this, but I can't find it. How can I execute another .py file from my first .py file without using an exec* command? They're both in the same directory, and it would be nice to have some run("another.py") type statement as opposed to a big exec with absolute pathnames and garbage like that. It works the way I have it, but it just seems like a bad way in general to do it. I'm runnning Python...
6
1918
by: Ian Sparks | last post by:
I have a python file with a number of functions named with the form doX so : doTask1 doThing doOther The order these are executed in is important and I want them to be executed top-down. They all have the same parameter signature so I'd like to do : for name, func in vars(mymodule).items(): if not name.startswith("do") and callable(func):
11
2747
by: Java and Swing | last post by:
Is there some other way, besides SWIG, which will allow me to call functions inside an Ansi C DLL? Example (C): defs.h ------- typedef unsigned long MY_DIGIT; myapp.c
2
2814
by: Kevin | last post by:
i have a python file called pyq which outputs stock quotes, currently i also have a html file that takes stock ticker inputs, i would like to bridge the two by building another program that takes the html inputs and uses them to call the pyq stock ticker program and then output them into a text file... any idea how to do this? my tentative code is:
2
1848
by: Phoe6 | last post by:
Hi, I have the following directory structure in my project. Base: file1.py file2.py Directory1: file1-dir1.py I am able to import file1 into file2.py What I need to do is, import file1 in the file file1-dir1.py.
8
2306
by: Eric_Dexter | last post by:
I was looking for a simple way to load a simple python program from another python program. I tried os.system(cabel) The file name is cabel.py a csound instrument editor.. The error I am getting is
2
2973
by: KraftDiner | last post by:
I have a class that is defined in a file called MyClass.py How do I use that class in another python script.. import MyClass ? (Does it need to be in a specific location?)
4
1837
by: Michael Malinowski | last post by:
Is there a way to read the directory that the currently running python file is located in? Cheers Mike.
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10214
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9865
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5304
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3563
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.