CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Python (http://www.codingforums.com/forumdisplay.php?f=46)
-   -   How do you "include" a file? (http://www.codingforums.com/showthread.php?t=216838)

Apothem 01-30-2011 06:56 AM

How do you "include" a file?
 
How do you basically include (or import) a file?
Such that if I had:

a.py:
Code:

print 'hello'
b.py:
Code:

print 'bye'
c.py:
Code:

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


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

hello
---
bye


oesxyl 01-30-2011 10:04 AM

a.py:
Code:

def dummy1():
    print "Hello"

b.py:
Code:

def dummy2():
    print "world"

c.py:
Code:

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...l/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.

Edit: 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

Quote:

Originally Posted by Apothem (Post 1047486)
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?

Quote:

Can variables also be in it as well?
yes

Quote:

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....html#packages

best regards


All times are GMT +1. The time now is 05:21 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.