[Libguestfs] [PATCH 4/5] v2v: utils: Add utility functions for running external Python code.

Richard W.M. Jones rjones at redhat.com
Thu Feb 22 13:57:24 UTC 2018


---
 v2v/utils.ml  | 16 ++++++++++++++++
 v2v/utils.mli | 11 +++++++++++
 2 files changed, 27 insertions(+)

diff --git a/v2v/utils.ml b/v2v/utils.ml
index 1ceba94cd..f8dbf233e 100644
--- a/v2v/utils.ml
+++ b/v2v/utils.ml
@@ -196,3 +196,19 @@ let find_file_in_tar tar filename =
     )
   in
   loop lines
+
+let run_python ?(python = "python") code =
+  (* In debug mode output the python code without quoting into
+   * the log, and don't echo the actual command because the
+   * multiple levels of quoting is very confusing.
+   *)
+  debug "running python code using ‘%s’:\n%s" python code;
+  let cmd = sprintf "%s -c %s" (quote python) (quote code) in
+  external_command ~echo_cmd:false cmd
+
+let py_quote str =
+  let str = String.replace str "\\" "\\\\" in
+  let str = String.replace str "'" "\\'" in
+  "'''" ^ str ^ "'''"
+
+let py_bool = function true -> "True" | false -> "False"
diff --git a/v2v/utils.mli b/v2v/utils.mli
index 34402e28f..3a8dfd437 100644
--- a/v2v/utils.mli
+++ b/v2v/utils.mli
@@ -61,3 +61,14 @@ val find_file_in_tar : string -> string -> int64 * int64
 
     Function raises [Not_found] if there is no such file inside [tar] and
     [Failure] if there is any error parsing the tar output. *)
+
+val run_python : ?python:string -> string -> string list
+(** Run a snippet of Python code, and collect the output.
+
+    On failure this raises an error. *)
+
+val py_quote : string -> string
+(** Return a fully quoted Python string literal. *)
+
+val py_bool : bool -> string
+(** Return "True" or "False". *)
-- 
2.13.2




More information about the Libguestfs mailing list