From 65fb8450047e4b43ecc0ebb1d6ccae807da939f3 Mon Sep 17 00:00:00 2001 From: Michael Svingel Date: Tue, 5 Nov 2024 17:26:09 +0100 Subject: [PATCH 1/2] store list of imported python modules in json file --- inst/documents/dummy.qmd | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/inst/documents/dummy.qmd b/inst/documents/dummy.qmd index 855385e..220a699 100644 --- a/inst/documents/dummy.qmd +++ b/inst/documents/dummy.qmd @@ -32,6 +32,32 @@ knitr::spin_child(params$script) ```{python, file=params$script, eval=(grepl("\\.py$", params$script))} ``` +```{python, eval=(grepl("\\.py$", params$script)), echo=FALSE} +import json +import sys +import subprocess + +temp_dir = r.params['tmpdir'] + +# Get a list of installed packages using pip list +installed_packages = subprocess.check_output([sys.executable, '-m', 'pip', 'list', '-v']).decode('utf-8').strip().split('\n')[2:] +installed_packages = {package.split()[0]: [package.split()[1], package.split()[2]] for package in installed_packages} + +imported_modules = {} +for module_name, module in sys.modules.items(): + if not (module_name.startswith('_') or module_name.startswith('.') or '.' in module_name): + if module_name in installed_packages: + imported_modules[module_name] = { + "version": installed_packages[module_name][0], + "installation_path": installed_packages[module_name][1] + } + +with open(f'{temp_dir}/python_imports.json', 'w') as json_file: + json.dump(imported_modules, json_file) + +``` + + ```{r sessioninfo, include=FALSE} saveRDS( object = whirl:::session_info(params$check_approved_folder_pkgs, params$check_approved_url_pkgs), From 205137652429ccfa32b2dcb37c192b734250bd4a Mon Sep 17 00:00:00 2001 From: Michael Svingel Date: Tue, 5 Nov 2024 17:26:51 +0100 Subject: [PATCH 2/2] add imported python modules to log --- inst/documents/log.qmd | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/inst/documents/log.qmd b/inst/documents/log.qmd index a6f5242..47bc988 100644 --- a/inst/documents/log.qmd +++ b/inst/documents/log.qmd @@ -122,8 +122,19 @@ cat("\n") ```{r, results="asis", eval=(grepl("\\.py$", params$title)), fig.height = 0.5} library(knitr) +library(jsonlite) cat("\n## Python Packages\n") +cat("\n### Imported Python Packages\n") +json_data <- fromJSON(file.path(params$tmpdir, "python_imports.json")) +df <- do.call(rbind, lapply(names(json_data), function(x) cbind(package = x, as.data.frame(t(json_data[[x]]))))) +colnames(df) <- c("Package", "Version", "Path") +row.names(df) <- NULL +df |> + knitr::kable() |> + knitr::knit_print() + +cat("\n### Installed Python Packages in environment\n") pip_list_output <- system("pip list", intern=TRUE) pip_list_df <- as.data.frame(do.call(rbind, strsplit(pip_list_output, "\\s{2,}"))) pip_list_df <- pip_list_df[-c(1, 2), ]