You will need to import the other file as a module like this:
import Math
If you don't want to prefix your Calculate
function with the module name then do this:
from Math import Calculate
If you want to import all members of a module then do this:
from Math import *
Edit: Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.
Just write the "include" command :
import os
def include(filename):
if os.path.exists(filename):
execfile(filename)
include('myfile.py')
@Deleet :
@bfieck remark is correct, for python 2 and 3 compatibility, you need either :
Python 2 and 3: alternative 1
from past.builtins import execfile
execfile('myfile.py')
Python 2 and 3: alternative 2
exec(compile(open('myfile.py').read()))
If you use:
import Math
then that will allow you to use Math's functions, but you must do Math.Calculate, so that is obviously what you don't want.
If you want to import a module's functions without having to prefix them, you must explicitly name them, like:
from Math import Calculate, Add, Subtract
Now, you can reference Calculate, Add, and Subtract just by their names. If you wanted to import ALL functions from Math, do:
from Math import *
However, you should be very careful when doing this with modules whose contents you are unsure of. If you import two modules who contain definitions for the same function name, one function will overwrite the other, with you none the wiser.
I've found the python inspect module to be very useful
For example with teststuff.py
import inspect
def dostuff():
return __name__
DOSTUFF_SOURCE = inspect.getsource(dostuff)
if __name__ == "__main__":
dostuff()
And from the another script or the python console
import teststuff
exec(DOSTUFF_SOURCE)
dostuff()
And now dostuff should be in the local scope and dostuff() will return the console or scripts _name_ whereas executing test.dostuff() will return the python modules name.
I would like to emphasize an answer that was in the comments that is working well for me. As mikey has said, this will work if you want to have variables in the included file in scope in the caller of 'include', just insert it as normal python. It works like an include statement in PHP. Works in Python 3.8.5.
Alternative #1
import textwrap
from pathlib import Path
exec(textwrap.dedent(Path('myfile.py').read_text()))
Alternative #2
with open('myfile.py') as f: exec(f.read())
I prefer Alternative #2 and have been using it in my website development.
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