summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorstijn <stijn@ignitron.net>2021-04-06 20:40:31 +0200
committerDamien George <damien@micropython.org>2021-04-07 12:41:25 +1000
commita66286f3a0f24985cae2648102e51de64b8a1871 (patch)
tree79e0bf738d9a669d917dcd5bee5aadbe2d214ee3
parent4f53f462ca9dbec45771e06d2d1a84b61e01e61a (diff)
unix: Improve command line argument processing.
Per CPython everything which comes after the command, module or file argument is not an option for the interpreter itself. Hence the processing of options should stop when encountering those, and the remainder be passed as sys.argv. Note the latter was already the case for a module or file but not for a command. This fixes issues like 'micropython myfile.py -h' showing the help and exiting instead of passing '-h' as sys.argv[1], likewise for '-X <something>' being treated as a special option no matter where it occurs on the command line.
-rw-r--r--ports/unix/main.c12
-rw-r--r--tests/cmdline/repl_inspect.py2
-rw-r--r--tests/cmdline/repl_inspect.py.exp2
3 files changed, 10 insertions, 6 deletions
diff --git a/ports/unix/main.c b/ports/unix/main.c
index 07db8d22c..129c6d3bb 100644
--- a/ports/unix/main.c
+++ b/ports/unix/main.c
@@ -341,6 +341,9 @@ STATIC int invalid_args(void) {
STATIC void pre_process_options(int argc, char **argv) {
for (int a = 1; a < argc; a++) {
if (argv[a][0] == '-') {
+ if (strcmp(argv[a], "-c") == 0 || strcmp(argv[a], "-m") == 0) {
+ break; // Everything after this is a command/module and arguments for it
+ }
if (strcmp(argv[a], "-h") == 0) {
print_help(argv);
exit(0);
@@ -400,6 +403,8 @@ STATIC void pre_process_options(int argc, char **argv) {
}
a++;
}
+ } else {
+ break; // Not an option but a file
}
}
}
@@ -568,11 +573,10 @@ MP_NOINLINE int main_(int argc, char **argv) {
if (a + 1 >= argc) {
return invalid_args();
}
+ set_sys_argv(argv, a + 1, a); // The -c becomes first item of sys.argv, as in CPython
+ set_sys_argv(argv, argc, a + 2); // Then what comes after the command
ret = do_str(argv[a + 1]);
- if (ret & FORCED_EXIT) {
- break;
- }
- a += 1;
+ break;
} else if (strcmp(argv[a], "-m") == 0) {
if (a + 1 >= argc) {
return invalid_args();
diff --git a/tests/cmdline/repl_inspect.py b/tests/cmdline/repl_inspect.py
index 5a7564a3c..8c86f287d 100644
--- a/tests/cmdline/repl_inspect.py
+++ b/tests/cmdline/repl_inspect.py
@@ -1,2 +1,2 @@
-# cmdline: -c print("test") -i
+# cmdline: -i -c print("test")
# -c option combined with -i option results in REPL
diff --git a/tests/cmdline/repl_inspect.py.exp b/tests/cmdline/repl_inspect.py.exp
index 59f734b2f..051acfd15 100644
--- a/tests/cmdline/repl_inspect.py.exp
+++ b/tests/cmdline/repl_inspect.py.exp
@@ -1,6 +1,6 @@
test
MicroPython \.\+ version
Use \.\+
->>> # cmdline: -c print("test") -i
+>>> # cmdline: -i -c print("test")
>>> # -c option combined with -i option results in REPL
>>>