Skip to content

Commit 630d851

Browse files
committed
unix: Be sure to add current/base dir of a script to sys.path.
This mirrors CPython behavior and makes possible to run scripts which import other modules not from script's directory.
1 parent 625d08a commit 630d851

1 file changed

Lines changed: 14 additions & 6 deletions

File tree

unix/main.c

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -238,18 +238,19 @@ int main(int argc, char **argv) {
238238
if (path == NULL) {
239239
path = "~/.micropython/lib:/usr/lib/micropython";
240240
}
241-
uint path_num = 0;
241+
uint path_num = 1; // [0] is for current dir (or base dir of the script)
242242
for (char *p = path; p != NULL; p = strchr(p, ':')) {
243243
path_num++;
244244
if (p != NULL) {
245245
p++;
246246
}
247247
}
248248
sys_path = mp_obj_new_list(path_num, NULL);
249-
mp_obj_t *items;
250-
mp_obj_list_get(sys_path, &path_num, &items);
249+
mp_obj_t *path_items;
250+
mp_obj_list_get(sys_path, &path_num, &path_items);
251+
path_items[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
251252
char *p = path;
252-
for (int i = 0; i < path_num; i++) {
253+
for (int i = 1; i < path_num; i++) {
253254
char *p1 = strchr(p, ':');
254255
if (p1 == NULL) {
255256
p1 = p + strlen(p);
@@ -259,9 +260,9 @@ int main(int argc, char **argv) {
259260
CHECKBUF(buf, PATH_MAX);
260261
CHECKBUF_APPEND(buf, home, strlen(home));
261262
CHECKBUF_APPEND(buf, p + 1, p1 - p - 1);
262-
items[i] = MP_OBJ_NEW_QSTR(qstr_from_strn(buf, CHECKBUF_LEN(buf)));
263+
path_items[i] = MP_OBJ_NEW_QSTR(qstr_from_strn(buf, CHECKBUF_LEN(buf)));
263264
} else {
264-
items[i] = MP_OBJ_NEW_QSTR(qstr_from_strn(p, p1 - p));
265+
path_items[i] = MP_OBJ_NEW_QSTR(qstr_from_strn(p, p1 - p));
265266
}
266267
p = p1 + 1;
267268
}
@@ -318,6 +319,13 @@ int main(int argc, char **argv) {
318319
return usage();
319320
}
320321
} else {
322+
// Set base dir of the script as first entry in sys.path
323+
char *basedir = realpath(argv[a], NULL);
324+
if (basedir != NULL) {
325+
char *p = strrchr(basedir, '/');
326+
path_items[0] = MP_OBJ_NEW_QSTR(qstr_from_strn(basedir, p - basedir));
327+
free(basedir);
328+
}
321329
for (int i = a; i < argc; i++) {
322330
rt_list_append(py_argv, MP_OBJ_NEW_QSTR(qstr_from_str(argv[i])));
323331
}

0 commit comments

Comments
 (0)