I need a Python equivalent of PHP's include function. I know of execfile(), but that doesn't work the same. Any ideas?
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.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With