Toby Tobkin added the comment:

Hopefully this isn't too much of an amateur question, but I ran into a 
semantics issue: should which be imitating the semantics of the Windows shell 
or of CreateProcess[3]? The current implementation of shutil.which implies 
Windows shell, but Python uses CreateProcess in subprocess for executing 
commands, not cmd.exe.

In order to correctly emulate the behavior of the Windows command search 
sequence[1] (e.g. for cmd.exe or Powershell), one needs to check whether or not 
a given command matches one of the internal Windows shell commands. For 
instance, if we have an executable at C:\xyz\chdir.exe, the following outputs 
should be observed from which if our current directory is C:\xyz:

>>> which('chdir')

>>> which('.\\chdir')

On the other hand, CreateProcess[3] would work this way:

CreateProcess(NULL, "chdir", ...) --> executes C:\xyz\chdir.exe
CreateProcess(NULL, "chdir.exe", ...) --> executes C:\xyz\chdir.exe

There are other semantic differences as well. For example, CreateProcess will 
not do path extension of e.g. "abc" to "abc.bat", but Powershell and cmd will.

Which semantics do I follow? Powershell/cmd or CreateProcess?

[1] Subsection "Command Search Sequence" of
[2] Subsection "Internal and External Commands" of


Python tracker <>
Python-bugs-list mailing list

Reply via email to