From 8e912a501a926f59f330f8a71c2ac1bd4af88a9e Mon Sep 17 00:00:00 2001 From: Jim Mussared Date: Fri, 7 Oct 2022 02:13:58 +1100 Subject: [PATCH] unix: Enable sys.executable. Gives the absolute path to the unix micropython binary. This work was funded through GitHub Sponsors. Signed-off-by: Jim Mussared Signed-off-by: Damien George --- ports/unix/main.c | 16 ++++++++++++++++ ports/unix/mpconfigport.h | 3 +++ tests/unix/extra_coverage.py.exp | 9 +++++---- 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/ports/unix/main.c b/ports/unix/main.c index 44823ee17..7920db02f 100644 --- a/ports/unix/main.c +++ b/ports/unix/main.c @@ -43,6 +43,7 @@ #include "py/builtin.h" #include "py/repl.h" #include "py/gc.h" +#include "py/objstr.h" #include "py/stackctrl.h" #include "py/mphal.h" #include "py/mpthread.h" @@ -435,6 +436,17 @@ STATIC void set_sys_argv(char *argv[], int argc, int start_arg) { } } +#if MICROPY_PY_SYS_EXECUTABLE +extern mp_obj_str_t mp_sys_executable_obj; +STATIC char executable_path[MICROPY_ALLOC_PATH_MAX]; + +STATIC void sys_set_excecutable(char *argv0) { + if (realpath(argv0, executable_path)) { + mp_obj_str_set_data(&mp_sys_executable_obj, (byte *)executable_path, strlen(executable_path)); + } +} +#endif + #ifdef _WIN32 #define PATHLIST_SEP_CHAR ';' #else @@ -598,6 +610,10 @@ MP_NOINLINE int main_(int argc, char **argv) { printf(" peak %d\n", m_get_peak_bytes_allocated()); */ + #if MICROPY_PY_SYS_EXECUTABLE + sys_set_excecutable(argv[0]); + #endif + const int NOTHING_EXECUTED = -2; int ret = NOTHING_EXECUTED; bool inspect = false; diff --git a/ports/unix/mpconfigport.h b/ports/unix/mpconfigport.h index 08ddd21f6..a67d11b9e 100644 --- a/ports/unix/mpconfigport.h +++ b/ports/unix/mpconfigport.h @@ -154,6 +154,9 @@ typedef long mp_off_t; // Don't default sys.argv because we do that in main. #define MICROPY_PY_SYS_PATH_ARGV_DEFAULTS (0) +// Enable sys.executable. +#define MICROPY_PY_SYS_EXECUTABLE (1) + #define MICROPY_PY_USOCKET_LISTEN_BACKLOG_DEFAULT (SOMAXCONN < 128 ? SOMAXCONN : 128) // Bare-metal ports don't have stderr. Printing debug to stderr may give tests diff --git a/tests/unix/extra_coverage.py.exp b/tests/unix/extra_coverage.py.exp index 294115455..2f5409b85 100644 --- a/tests/unix/extra_coverage.py.exp +++ b/tests/unix/extra_coverage.py.exp @@ -62,10 +62,11 @@ ime utime utimeq argv atexit byteorder exc_info -exit getsizeof implementation maxsize -modules path platform print_exception -ps1 ps2 stderr stdin -stdout tracebacklimit version version_info +executable exit getsizeof implementation +maxsize modules path platform +print_exception ps1 ps2 +stderr stdin stdout tracebacklimit +version version_info ementation # attrtuple (start=1, stop=2, step=3)