When executing a script, the directory of the script is added to sys.path. This generally has nothing to do with the current working directory. Automatically adding the script directory by default is as safe as one’s search PATH and execution habits permit (e.g. not executing files located in “~/Downloads”). Adding the current working directory by default is generally unsafe, but thankfully that doesn’t happen when running scripts.
That is nice to know; I’ve perhaps been letter my interactive testing
mislead me about this. I’ll test that. […] Ok, testing shows that it
does indeed add the script’s directory and not the current directory.
Adding it ahead of everything else is pretty iffy, convenience over
caution IMO. But ok, I can keep this in mind.
By default, the current working directory is added for “-c” and “-m” commands and the REPL, since there is no main script in those cases. It gets added as the empty string '', so it varies with whatever the current directory happens to be when an import is executed.
And here we part company. I remain against this (with the possible
exception of the REPL, still with misgivings). If I write some shell
script and invoke:
python -m foo ...
it will very much NOT be my desire that the current working directory
magicly get inserted into sys.path - my previously sound shell script
suddenly has a component which can misbehave in a malicious setting.
Such as that of the sysadmin doing some work inside an arbitrary user’s
directory, or inside a malicious software package (generic, not “python
package”). It needn’t be a sysadmin; any user standing somewhere
unfortunate gets this misfeature.
It is a security mine waiting to go off.
Python badly needs some switch to say “do not change sys.path at all”.
The -s and -S options do not provide this. Maybe it is too late to
change the default Python behaviour here, but I remain convinced that
this is a misfeature, and refer again to the maxim Heuer’s Razor:
If it can't be turned off, it's not a feature. - Karl Heuer
Grumblingly,
Cameron Simpson cs@cskk.id.au