...

How do you "include" a file?

Apothem
01-30-2011, 06:56 AM
How do you basically include (or import) a file?
Such that if I had:

a.py:
print 'hello'

b.py:
print 'bye'

c.py:
<import a.py>
print "---"
<import b.py>


How do I make it so that if I run c.py, it will print out:
hello
---
bye

oesxyl
01-30-2011, 10:04 AM
a.py:

def dummy1():
print "Hello"


b.py:

def dummy2():
print "world"


c.py:

if __name__ == '__main__':
from a import dummy1
from b import dummy2
dummy1()
print '----'
dummy2()


running python c.py will do what you want.

http://docs.python.org/release/2.6.6/tutorial/modules.html

usualy you need to be sure that import didn't fail and use exception but probably this will be later when you will feel confortable enought with python.

two things:
- change url to point to your python version instead of 2.6.6
- i assume you don't ask about something like call, eval, exec( see the docs for details)

best regards

Apothem
01-31-2011, 05:22 AM
So there's no way to import files and have the imported file automatically evaluate its contents? In other words, if I want to import files I must ONLY have functions/classes in the file(s) to be imported? Can variables also be in it as well?

Edit: Also, how would you go about importing files from other directories? Suppose you have the following files:
include/libs.py
conf/main.py
test.py

Lets say you run test.py - how would you import the libs.py and main.py?

oesxyl
01-31-2011, 07:45 AM
So there's no way to import files and have the imported file automatically evaluate its contents? In other words, if I want to import files I must ONLY have functions/classes in the file(s) to be imported?
no, python doesn't encourage spagetti code like php, because doesn't make sense, :)
why do you want to do something like this?

Can variables also be in it as well?
yes

Edit: Also, how would you go about importing files from other directories? Suppose you have the following files:
include/libs.py
conf/main.py
test.py

Lets say you run test.py - how would you import the libs.py and main.py?
http://docs.python.org/release/2.6.6/tutorial/modules.html#packages

best regards



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum