File: python-info.R

package info (click to toggle)
r-cran-sessioninfo 1.2.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 536 kB
  • sloc: sh: 14; makefile: 2
file content (60 lines) | stat: -rw-r--r-- 1,396 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

should_show_python <- function(pkgs) {
  "reticulate" %in% pkgs ||
    (isNamespaceLoaded("reticulate") &&
     reticulate::py_available(initialize = FALSE))
}

#' Python configuration
#'
#' @return
#' Returns a [reticulate::py_config] object, which also has the
#' `python_info` class. It is a named list of values.
#'
#' If reticulate is not installed or Python is not configured,
#' then it return a `python_info` object that is a character vector, and
#' it does not have a `py_config` class.
#'
#' @export
#' @examplesIf FALSE
#' python_info()
#' session_info(info = "all")

python_info <- function() {
  conf <- if (isNamespaceLoaded("reticulate") &&
              reticulate::py_available(initialize = FALSE)) {
    tryCatch(
      reticulate::py_config(),
      error = function(err) {
        c("`reticulate::py_config()` failed with error:",
          conditionMessage(err))
      }
    )
  } else {
    "Python is not available"
  }

  class(conf) <- unique(c("python_info", class(conf), "list"))
  conf
}

#' @export

format.python_info <- function(x, ...) {
  x <- NextMethod(x, ...)
  paste0(" ", unlist(strsplit(x, "\n", fixed = TRUE)))
}

#' @export

as.character.python_info <- function(x, ...) {
  old <- options(cli.num_colors = 1)
  on.exit(options(old), add = TRUE)
  format(x, ...)
}

#' @export

print.python_info <- function(x, ...) {
  cat(format(x, ...), sep = "\n")
}