473,836 Members | 1,949 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 12094
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
3121
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
3999
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
1920
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
2753
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
2818
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
1853
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
2311
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
2977
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
1845
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
9656
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,...
1
10567
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9349
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...
1
7771
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6972
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5641
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
5811
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4000
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3100
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.