A python_include() for cgi programming
I have recently have the opportunity to work on a Python web application. I've found it beneficial to reduce duplicate code with the following code lines import textwrap from pathlib import Path exec(textwrap.dedent(Path('myfile.py').read_text())) Perhaps such code could be the basis for a python_include() statement similar to how includes, requires work in PHP. Thank you for any consideration.
``` import myfile ``` or ``` from myfile import * ``` Will import the names from another file. You should use this instead of executing text read from a path. Thanks, ---- *Cade Brown* Research Assistant @ ICL (Innovative Computing Laboratory) Personal Email: brown.cade@gmail.com ICL/College Email: cade@utk.edu On Tue, Nov 3, 2020 at 7:49 PM warp_drive enterprise <robotai@gmail.com> wrote:
I have recently have the opportunity to work on a Python web application. I've found it beneficial to reduce duplicate code with the following code lines
import textwrap from pathlib import Path exec(textwrap.dedent(Path('myfile.py').read_text()))
Perhaps such code could be the basis for a python_include() statement similar to how includes, requires work in PHP.
Thank you for any consideration. _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-leave@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/EHZMYY... Code of Conduct: http://python.org/psf/codeofconduct/
Hello! If you want to run a file with its path inside a `my_file` variable, you can also use `__import__(my_file)`. This will also avoid polluting your namespace, compared to Cade Brown’s answer. I have to admit, this is pretty hacky, but I think this is better than a plain `exec()`. You can always create your own `python_include()` function.
I know what your getting at, 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. Though I prefer this version as it is simpler and less error prone. with open('myfile.py') as f: exec(f.read()) Basically, it includes the file and keep the scope of all variables that came before this type of include statement. Very useful for this like a shared authentication file across an entire website of multiple files/pages. Happy Thanksgiving!
participants (5)
-
Cade Brown
-
Mathew Elman
-
Matteo Bertucci
-
Voltron
-
warp_drive enterprise