Subprocess Warnings

There are (to me) important warnings about using the subprocess module. They are down under Popen constructor documentation.

The top of the module documentation recommends just using subprocess.run, so a new to subprocess reader may never make it down to the warning section.

Would it make sense to move the existing warning up ? e.g. between subprocess.run and class subprocess.CompletedProcess

2 Likes

ISTM the warning is too strong. Fully qualified paths are “more reliable” if the target is known to be at that exact location whenever subprocess is invoked. However, you lose portability. Outside of the standard /usr/bin/... targets, you can’t really assume anything about where the target is located (i.e. can you know in advance where a user has installed a python update or virtualenv?)

It’s not saying you should hardcode the paths – just that you should expand them yourself via shutil.which() first.

At least on Windows, subprocess.run(["command", ...]") doesn’t respect PATHEXT (the executable suffixes list) so it’ll find command.exe but not command.bat or command.CMD. subprocess.run([shutil.which("command"), ...]") however will do the right thing. It’s also explicit about whether it should allow .\command.exe.

I don’t know if there are other cases where the two might not be equivalent.

2 Likes

If you are running code in a known environment, RHEL etc
then the hard wired paths are a good thing. Pointing that out is
good for improved reliability/security.

But if portability is your goal that I doubt that security is high on your list of problems to address.

If a user/admin has built a venv I assume that they are running code in that venv and finding it is not an issue.