TLDR; I assumed that python -c "..." && other-command would either work or fail with an error, but it failed silently. I would like a better experience than that to avoid other users wasting as much time as I did. (feel free to skip to potential solutions)
I run an internal company website and went with Let’s Encrypt certbot to manage SSL certificate renewal. I had used it before but decided to use a slightly different set of tools to install and run it as a background resource, namely I use systemd instead of cron.
My mistake was using what the cerbot documentation provided but in a systemd service file:
What I did not realize is that systemd services don’t allow running multiple commands like this as if it were a bash session and my config was actually parsed equivalently as python -c '...' "&&" "sudo" "certbot" "renew" "-q".
I knew that there was a chance that systemd did not allow most bash syntax, but I assumed that if it didn’t support it that Python would error saying something like "unexpected argument ‘&&’ ". However, I got no error or warning and therefore went done the rabbit hole of trying to see if there was some weird STDOUT vs STDERR thing with how I was checking journalctl logs. It didn’t help that this was backlogged twice since I can just manually renew certs for 3 more months.
In short I wasted a bunch of time and want to avoid that for future users without breaking current behavior.
Potential solutions
Disallow arguments to Python following the -c '<command>' section. (Not backwards compatible, and unlikely to be acceptable, for good reason)
Print a warning to STDERR when trailing arguments are provided, unless an environment variable is set (e.g. PYTHON_ALLOW_CLI_SCRIPT_ARGS=1 or whatever) or another option is used (e.g. -C is used instead of -c).
I am leaning towards a solution like option 2. I am not a full-time developer and so I wouldn’t know the specifics of what “flavor” of option 2 would be best, or if there is a better option to go with. Guidance would be appreciated before I submit a FR/bug report to the already 5k+ issues in the CPython repo.
Option 1 is unequivocally bad since programs like the following are valid: python -c 'import sys; print(sys.argv)' arg2 arg3 etc. I only provided it since it’s the obvious thought, even if it’s bad.
Python passes the trailing arguments to the program a args. If you don’t want to allow arguments to your script it should detect them and emit the appropriate error. I don’t think it is possible for python to both pass arguments to programs and raise an error when they are passed and undesired because there is no way for python to know if the program it is running doesn’t want to accept arguments. A third option might be to add a ‘–no-args’ argument to python, but I would be strongly against that as this seems to be a niche case with an obvious solution (raise an exception in your script if it gets passed arguments).
I understand that raising an error and crashing is not a good solution. That’s why I lean towards Option 2 over Option 1.
Also, I think that the warning (not errors) would have to be the default for calls to python -c otherwise, as you said, you should just handle it properly instead of using the --no-args or equivalent.
I forgot about another option (let’s call it option 4 to not conflict with --no-args)
Parse arguments for python unless they are proceeded by --, e.g. python -c '...' <arg-to-python> -- <arg-to-script>. I would have highly preferred this option, if it were not backwards-incompatible. Perhaps it could be implemented as a breaking change? But then you would cause lots of people problems just to prevent some potential problems…
Another point I want to address is that I am NOT talking about changing behavior for python script.py or python -m ... at all. This is exclusively about when you use -c to run a quick python command.
Another another point is that you can also unintentionally miss arguments you meant to pass to Python, not just bash syntax like in my example. For example, you might tag on -P at the end of call to python -c '...' -P thinking it gets passed to python, when it in fact gets passed to your script. I think there are many cases where it’s confusing.
It might be interesting to always emit a warning if sys.argv has length > 1 but is never accessed. I’m not sure whether that’s actually feasible to implement, though.
That would be exceedingly surprising, I don’t know of any other programming language or environment that warns you for passing command line arguments and not using them.
Frankly, I don’t think this is a good idea to do as part of -c. If this IS to be done, switch the logic around, and have the stricter behaviour on a new flag. And if you’re going to do that, the easiest way is to build a module with whatever rules you want, and use python -m run rather than python -c.
You could also use ExecStartPre= but I would fix this with a systemd timer feature.
However if all you want is to randomise when the systemd unit runs then there are systemd timer methods to do that. See RandomizedDelaySec= in systemd.timer
As a general hint, btw - any time you have to give the full path to an executable instead of simply giving its name, there’s a good chance you’re not running through a shell. It’s far from a guarantee, but it’s an easy reminder.
While the environment itself doesn’t warn on unused cli arguments, literally every well written cli program warns on unexpected arguments, try out python --vreison.
The issue is that python --option -c '...' looks the same as python -c '...' --option for those familiar with bash but not the python cli in-and-out.
For other examples that might change your perspective, try out perl -e 'print "hello\n"' --help and node -e 'console.log("hello")' --help for examples where the --help is processed by perl and node respectively and not as arguments to the script you are running.
I will note that bash -c 'echo hello' --help does NOT follow perl and node, and instead follows python’s current behavior. However, pointing to other people’s poor behavior as a way to justify your poor behavior is not correct.
And this is why I want to re-emphasize that I exclusively want to add a warning to python -c, NOT to python -m or python script.py. I don’t think adding safety to an alternative option (e.g. -C instead of -c) would do any good. Otherwise, you would end up with “I need to remember to use -C because it reminds me how python parses cli arguments”. It’s a redundant step in a reminder chain.
Another part of my rational for this change is that who would expect to do any argument parsing as part of a -c script? Would you not be surprised if you saw a 500+ character script that started with python -c 'import sys; if sys.argv[1].strip() == "--my-option1": ...'?
I appreciate your time, but I don’t need help understanding why I was wrong in my systemd example. I was exclusively using it as a real-life example for why I think the current behavior of python -c should change to help people.
If you are curious, I ended up using 2 ExecStart='s because my service was a Type=oneshot.
That’s a very good rule of thumb, that I’ll keep in mind from now on.
On the other hand, there’s a chance that systemd implemented its own subset of shell syntax. For example, JS’s yarn has its own parsing system for && and || to make it wok on Windows.
I understand that it is valid, which is why I think it should only WARN and not error/crash if arguments are passed to the inline script, and there should either be env_var flag to ignore those warnings or use @zware 's suggestion to warn only if sys.argv is unused (if that’s possible).
That’s not the same thing though. Try creating a file called app.py and then running python app.py junkity junk --vreison. There won’t be an error unless app.py chooses to throw an error. If you ignore args - as in the original example - no args will be checked.
Things that let you invoke a program allow you to pass arguments to it. Those arguments are usually not processed by the previous parser (in the same way that bash won’t process Python’s arguments).
Just because you can’t think of any good time to pass args to an inline script, that doesn’t mean nobody does But also, why should they be denied args? Every other Python program can receive args.
This is not something that’s ever going to justify a backward-incompatible change to the meaning of python -c. At best, you might get an alternative like -C, but more likely, you’d write your own functionality.
There’s nothing different about inline scripts. So would your proposed warning cause problems for scripts in files too?
Mildly, because options are going to be rare. But I would not at all be surprised by, for example, python -c 'import sys, unicodedata; print(unicodedata.name(sys.argv[1][0]))' which can be used to quickly give a Unicode name to any single character argument. That can be used, for example, in an xargs command. So, I would not at all be surprised to see sys.argv used in an inline script.
Even without that problem, tracking whether the CLI args are ever accessed would be hard (sys.argv isn’t the only way to access them, and even detecting that would be fiddly), so it would need a stronger justification than the combination of:
users may not realise Python ignores sys.argv by default
users may try to use shell syntax with Python in a context that treats all supplied text as plain string arguments