목록으로 Python 주석 숨기기

목록으로 Python 주석 숨기기

목록 형식으로 Python 코드를 포함하고 싶지만 코드가 깔끔하고 간결하기를 원합니다. 주석은 전혀 인쇄되지 않으며 빈 줄도 인쇄되지 않습니다.

그만큼쉬운방법은 주석 코드를 제거하는 것이지만 문제를 우회하고 해결책을 찾지 못하는 것입니다. 나는 해결책을 원한다. 해결책은 가져오는 소스 파일을 편집할 필요가 없다는 것을 의미합니다.

나는 다음을 시도했습니다 :

접근법 1

\lstdefinestyle{py_without_comments}{%
    language     = python,
    morecomment  = [l][\nullfont]{\#},
    emptylines   = *1,
}

주석은 인쇄되지 않지만 텍스트가 출력에 도달한 이후 줄은 그대로 유지됩니다. LaTeX에서는 nullfont.

접근법 2

\lstdefinestyle{py_without_comments}{%
    language     = python,
    morecomment  = [is]{\#}{\^^M},
    emptylines   = *1,
}

#접근법 2는 줄부터 끝까지 모든 주석 줄을 무시합니다 . 문제는 줄의 끝도 사라진다는 것입니다! 다음 코드가 있다고 가정해 보겠습니다.

def foo():
    if cond1: bar() #Some explanation
    if cond2: baz() #Some other explanation
    if cond3: bye() #Even more explanations

다음과 같이 인쇄됩니다.

def foo():
    if cond1: bar()        if cond2: baz()        if cond3: bye()

이는 바람직하지 않고, 파이썬적이지 않으며, 추악합니다.

접근법 3

\lstdefinestyle{py_without_comments}{%
    language     = python,
    morecomment  = [il]{\#},
    emptylines   = *1,
}

이것은 매력적으로 작동해야 하지만 어떤 이유에서인지 첫 번째 주석의 모든 코드가 지워집니다( foo()예제 참조).

그래서 나는 시도해 볼 다른 것을 찾고 있습니다. 목록에서는 이것이 불가능할 수 있습니까?

미리 감사드립니다.


편집 1:

MWE를 찾을 수 있습니다여기

답변1

여기 작동하는 것이 있습니다. 그것은 '내부'의 일부와 함께 작동합니다 listings. 더 나은 해결책이 있는지 잘 모르겠습니다. 줄 끝 구분 기호(위의 접근 방식 2)를 사용하고 줄이 비어 있지 않으면 다시 추가하는 것이 작동하지 않는 것 같습니다.

\documentclass[11pt]{article}
\usepackage{xcolor}
\usepackage{listings}

% Default settings.
\lstset{
  basicstyle=\ttfamily,
  numbers=left,
  numbersep=5pt,
  numberstyle=\tiny\color{gray},
  rulecolor=\color{black},
}

% The \incomment macro and auxiliary stuff.
\newif\ifnocomment
\newif\ifemptyline
\makeatletter
% When a line starts, it's empty and we're not in a comment.
\lst@AddToHook{InitVarsBOL}{\global\emptylinetrue\global\nocommenttrue}
% When something is printed, the line is not empty.
\lst@AddToHook{PostOutput}{\global\emptylinefalse}
% When we're in a comment...
\def\incomment#1{%
  % if we just entered...
  \ifnocomment%
    \global\nocommentfalse%
    % and the line is empty, then remove this line.
    \ifemptyline\global\advance\lst@newlines\m@ne\fi%
  \fi}
\makeatother

\lstdefinestyle{python_without_comments}{%
  language=python,
  morecomment=[l][\incomment]{\#},
}

\begin{document}
\begin{lstlisting}[style=python_without_comments]
def f(x): return x + 1 #

# This is function foo...
def foo():
  if cond1: bar()  # Some explanation
  if cond2: baz()  # Some other explanation
  if cond3: bye()  # Even more explanations

# And this is function bar
def bar():  # let's see
  # some more comment
  return 42 # here?
\end{lstlisting}
\end{document}

결과는 다음과 같습니다. 결과

주석이 있는 경우 텍스트 끝에 빈 줄을 인쇄할 수 있습니다. 이것을 제거하는 방법을 잘 모르겠습니다.


편집: 내 원래 답변 OutputBoxPostOutput. 이것은 탭에서는 잘 작동하지 않았습니다.

관련 정보