In Show output of a full LaTeX document I provided a partial solution to a similar question. The following code is an attempt to simulate the running of a full MWE within another document as for example a tutorial for LaTeX. The code produces an output as per the image below:

The top part of the box is the code and the bottom part the LaTeX output. The code sandboxes the begin{document}...\end{document} macros in order to disable them within the example code and only just typeset them.
I am looking for a method to import packages or classes at this point and only run them locally within the example. How can this be achieved?
An approach would be to just let ProvidesPackage etc... to empty, disable the \@preamblecmds and use globaldefs to ensure that the code only runs within a group.
\documentclass{article}
\usepackage[listings]{tcolorbox}
\usepackage{amsmath,amsfonts,lipsum}
\begin{document}
\makeatletter
\gdef\@preamblecmds{}
\def\documentclass#1{}
\def\usepackage#1{}
\let\Document\document
\let\Enddocument\enddocument
\def\document{}
\def\enddocument{}
\gdef\after@@{\let\enddocument\Enddocument\let\document\Document}
\newenvironment{tex}{
\tcblisting{boxrule=1pt}}
{\endtcblisting\aftergroup\after@@}
% auto example
\begin{tex}
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\section{Introduction}
Whence we conclude that $\gamma$ is a primitive root modulo $p$. But
\begin{align*}
\gamma^{p-1}-1 &=
g^{p-1} - 1 + \frac{p-1}{1!}g^{p-2}xp +
\frac{(p-1)(p-2)}{2!}g^{p-3}x^2p^2 + \ldots \\
&= p\left(kp + \frac{p-1}{1!}g^{p-2}x +
\frac{(p-1)(p-2)}{2!}g^{p-3}x^2p + \ldots\right).
\end{align*}
\end{document}
\end{tex}
\bigskip
\lipsum[1]
\end{document}
--shell-escape? – Marco Daniel Mar 25 '12 at 11:20previewpackage. – Stephan Lehmke Mar 25 '12 at 11:22\sectionafter\begin{document}if I were you:-)– ienissei Mar 25 '12 at 12:04\begin{document}was neutered! – yannisl Mar 25 '12 at 12:22\@preamblecmdsbefore the main\begin{document}: when it has acted it's impossible to recover the original definitions of the "preamble only" commands. However, using\globaldefs=-1would break all packages that use\gdefor\xdeffor their workings. And what about section numbers and the like? LaTeX relies on the fact that\stepcounteracts globally. – egreg Mar 25 '12 at 12:43\@premablecmds. – yannisl Mar 25 '12 at 13:29