# PythonTeX + \InputIfFileExists for inputting rows in longtable creates spurious space before the end

TeX Live 2014 on Xubuntu 14.04 LTS.

Minimal working example:

\documentclass[11pt, twoside]{book}
\usepackage{pythontex}
\usepackage{booktabs}
\usepackage{multirow}
\usepackage{longtable}

\begin{document}
\chapter{longtable with \\InputIfFileExists vs. longtable without}
\begin{longtable}{ll}
\toprule
{Col 1} & {Col 2} \\
\toprule
{Col 1} & {Col 2} \\
\hline
\endfoot
\bottomrule
\endlastfoot
\InputIfFileExists{tablerows.tex}{}{}
\end{longtable}

\begin{longtable}{ll}
\toprule
{Col 1} & {Col 2} \\
\toprule
{Col 1} & {Col 2} \\
\hline
\endfoot
\bottomrule
\endlastfoot
{John Doe} & {110} \\

\end{longtable}
\end{document}


Contents of file tablerows.tex (contains final newline):

{John Doe} & {110} \\


Removing \usepackage{pythontex} gives the same output in both cases. This appears to be a bug, but I would like to find workarounds. I have not found anything on this issue asking a search engine. Any ideas? Am I missing anything?

PS: Might also affect other tables/tabulars, I have not checked.

The package pythontex requires, among other packages, filehook which is the bad guy in this case. The definition of \InputIfFileExists becomes

\renewcommand{\InputIfFileExists}[2]{%
\IfFileExists{#1}
{\expandafter\filehook@swap\expandafter{\@filef@und}{%
\filehook@every@atbegin{#1}%
\filehook@atbegin{#1}\@@input
}%
\filehook@atend{#1}\filehook@every@atend{#1}%
}%
}


whereas the original definition is

% latex.ltx, line 1757:
\newcommand\InputIfFileExists[2]{%
\IfFileExists{#1}%


This means that after the trailing \\ in the input file, some actions are performed which stop TeX from searching for \omit or \noalign and so, since the table has not yet ended, to start a new row.

Workaround: define a table safe command using the original \InputIfFileExists.

\documentclass[11pt, twoside]{book}
\usepackage{pythontex}
\usepackage{booktabs}
\usepackage{multirow}
\usepackage{longtable}

\makeatletter
\@ifundefined{filehook@csuse}
{\let\TablesafeInputIfFileExists\InputIfFileExists}% filehook is not loaded
{\let\TablesafeInputIfFileExists\latex@InputIfFileExists}
\makeatletter

\begin{document}

\chapter{longtable with \\InputIfFileExists vs. longtable without}
\begin{longtable}{ll}
\toprule
{Col 1} & {Col 2} \\
\toprule
{Col 1} & {Col 2} \\
\hline
\endfoot
\bottomrule
\endlastfoot
\TablesafeInputIfFileExists{kreuvrows.tex}{}{}
\end{longtable}

\begin{longtable}{ll}
\toprule
{Col 1} & {Col 2} \\