Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent to PHP include

I need a Python equivalent of PHP's include function. I know of execfile(), but that doesn't work the same. Any ideas?

like image 755
Andrey Avatar asked Jun 28 '12 01:06

Andrey


People also ask

What is the equivalent of include in Python?

Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import.

Is there include in Python?

When you just need that code, include does the ugly bits for you. It allows you to run code from files, strings or other sources as if they were regular modules. Code is executed as compliant as possible with the Python ecosystem.

Should I use require or include PHP?

Use require when the file is required by the application. Use include when the file is not required and application should continue when file is not found.


2 Answers

Try import, with a try/except on ImportError:

try:
    import modulename
except ImportError:
    print 'importing modulename failed'

Without catching ImportError it is the equivalent of require, sorta-kinda.

Do note that python will only execute the module code once (making this more a include_once or require_once statement. Functions in the module can be called more than once, of course.

like image 177
Martijn Pieters Avatar answered Sep 28 '22 05:09

Martijn Pieters


If what you want is to set a string variable in your script to the contents of an external file a la php (Example #6 Using output buffering to include a PHP file into a string ...) then this might work:

s = open('file.abc').read()
like image 32
dusty Avatar answered Sep 28 '22 05:09

dusty