File: source.R

package info (click to toggle)
r-cran-reticulate 1.41.0.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,088 kB
  • sloc: cpp: 5,154; python: 620; sh: 13; makefile: 2
file content (51 lines) | stat: -rw-r--r-- 1,614 bytes parent folder | download
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


#' Read and evaluate a Python script
#'
#' Evaluate a Python script within the Python main module, then make all public
#' (non-module) objects within the main Python module available within the
#' specified R environment.
#'
#' To prevent assignment of objects into R, pass `NULL` for the `envir`
#' parameter.
#'
#' @inheritParams py_run_file
#'
#' @param envir The environment to assign Python objects into (for example,
#'   `parent.frame()` or `globalenv()`). Specify `NULL` to not assign Python
#'   objects.
#'
#' @export
#' @importFrom utils download.file
source_python <- function(file, envir = parent.frame(), convert = TRUE) {

  # Download file content from URL to a local tempory file
  if (!file.exists(file) && isTRUE(grepl("^https?://", file))) {
    tmpfile <- tempfile(fileext = ".py")
    utils::download.file(url = file, destfile = tmpfile, quiet = TRUE)
    file <- tmpfile
    on.exit(unlink(file), add = TRUE)
  }

  # source the python script into the main python module
  main_dict <- py_run_file(file, local = FALSE, convert = convert)
  on.exit(py_flush_output(), add = TRUE)

  # copy objects from the main python module into the specified R environment
  if (!is.null(envir)) {
    names <- py_dict_get_keys_as_str(main_dict)
    names <- names[!startsWith(names, '_')]
    names <- names[-match("r", names)] # don't export "R interface object"
    Encoding(names) <- "UTF-8"

    for (name in names) {
      value <- main_dict[[name]]
      if (!inherits(value, "python.builtin.module"))
        assign(name, value, envir = envir)
    }
  }

  # return nothing
  invisible(NULL)
}