Skip to content

Commit 625d08a

Browse files
committed
unix: Initialize sys.path from MICROPYPATH environment variable.
If it's not available, "~/.micropython/lib:/usr/lib/micropython" is used as a fallback.
1 parent e11b17c commit 625d08a

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

unix/main.c

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,41 @@ int main(int argc, char **argv) {
233233
qstr_init();
234234
rt_init();
235235

236+
char *home = getenv("HOME");
237+
char *path = getenv("MICROPYPATH");
238+
if (path == NULL) {
239+
path = "~/.micropython/lib:/usr/lib/micropython";
240+
}
241+
uint path_num = 0;
242+
for (char *p = path; p != NULL; p = strchr(p, ':')) {
243+
path_num++;
244+
if (p != NULL) {
245+
p++;
246+
}
247+
}
248+
sys_path = mp_obj_new_list(path_num, NULL);
249+
mp_obj_t *items;
250+
mp_obj_list_get(sys_path, &path_num, &items);
251+
char *p = path;
252+
for (int i = 0; i < path_num; i++) {
253+
char *p1 = strchr(p, ':');
254+
if (p1 == NULL) {
255+
p1 = p + strlen(p);
256+
}
257+
if (p[0] == '~' && p[1] == '/' && home != NULL) {
258+
// Expand standalone ~ to $HOME
259+
CHECKBUF(buf, PATH_MAX);
260+
CHECKBUF_APPEND(buf, home, strlen(home));
261+
CHECKBUF_APPEND(buf, p + 1, p1 - p - 1);
262+
items[i] = MP_OBJ_NEW_QSTR(qstr_from_strn(buf, CHECKBUF_LEN(buf)));
263+
} else {
264+
items[i] = MP_OBJ_NEW_QSTR(qstr_from_strn(p, p1 - p));
265+
}
266+
p = p1 + 1;
267+
}
268+
236269
mp_obj_t m_sys = mp_obj_new_module(MP_QSTR_sys);
270+
rt_store_attr(m_sys, MP_QSTR_path, sys_path);
237271
mp_obj_t py_argv = mp_obj_new_list(0, NULL);
238272
rt_store_attr(m_sys, MP_QSTR_argv, py_argv);
239273

0 commit comments

Comments
 (0)