Skip to content

Commit

Permalink
Fix knitr output remapping from a clean new session (#1418)
Browse files Browse the repository at this point in the history
  • Loading branch information
dfalbel authored Jul 20, 2023
1 parent 70a23d6 commit 6e74c1e
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 2 deletions.
1 change: 1 addition & 0 deletions R/output.R
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ set_knitr_python_stdout_hook <- function() {
# if knitr is already in progress here, this means that python was initialized
# during a chunk execution. We have to force an instant remap as the hook won't
# have a chance to run for that chunk.
# In such cases `context.__enter__` is never called.
if (isTRUE(getOption('knitr.in.progress'))) set_output_streams(tty = FALSE)
} else {
setHook(
Expand Down
6 changes: 5 additions & 1 deletion inst/python/rpytools/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,14 +153,18 @@ def __init__(self, r_stdout, r_stderr, tty):
self.r_stdout = r_stdout
self.r_stderr = r_stderr
self.tty = tty
self._stdout = sys.stdout
self._stderr = sys.stderr

def __enter__(self):
# It's possible that __enter__ does not execute before __exit__ in some
# special cases. We also store _stdout and _stderr when creating the context.
self._stdout = sys.stdout
self._stderr = sys.stderr

_remap_output_streams(self.r_stdout, self.r_stderr, self.tty)

def __exit__(self):
def __exit__(self, *args):
sys.stdout = self._stdout
sys.stderr = self._stderr

4 changes: 4 additions & 0 deletions tests/testthat/_snaps/python-knitr-engine/knitr-print2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
bt <- reticulate::import_builtins()
bt$print("Hello world")

## Hello world
13 changes: 12 additions & 1 deletion tests/testthat/test-python-knitr-engine.R
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ test_that("Output streams are remaped when kniting", {
local_edition(3)

owd <- setwd(test_path("resources"))
rmarkdown::render("knitr-print.Rmd")
rmarkdown::render("knitr-print.Rmd", quiet = TRUE)
setwd(owd)

rendered <- test_path("resources", "knitr-print.md")
Expand All @@ -87,4 +87,15 @@ test_that("Output streams are remaped when kniting", {
}))
expect_length(out, 0)

# make sure it works from a background session
callr::r(function(path) {
setwd(path)
rmarkdown::render(
"knitr-print.Rmd",
output_file = "knitr-print2.md",
quiet = TRUE
)
}, args = list(path = test_path("resources")))

expect_snapshot_file(test_path("resources", "knitr-print2.md"))
})

0 comments on commit 6e74c1e

Please sign in to comment.