CreateProcess 如何定位可执行文件? [英] How does CreateProcess locate the executable?
问题描述
根据文档,CreateProcess 可以传递一个可执行文件名作为第一个参数,或命令行作为第二个参数(从可执行文件名将被提取).
According to the docs, CreateProcess can be passed an executable name as first argument, or a command line as a second argument (from which the executable name will be extracted).
如果您传递一个可执行文件名称,文档会说不会搜索 PATH
.
If you pass an executable name, the docs say PATH
won't be searched.
如果您改为传递命令行,则会提取第一个令牌以供使用作为可执行文件名称和 PATH
应该被搜索.
if you pass a command line instead, the first token is extracted to be used
as the executable name and PATH
is supposed to be searched.
不过,就我而言,我对 CreateProcess
的调用 --- 仅使用命令行并且使用修改后的环境 --- 找不到所寻求的可执行文件.它只是如果我在命令行之前使用 cmd.exe/c
成功(我明白为什么它是这样工作的).
In my case, though, my call to CreateProcess
---with a command line only and
with a modified environment--- doesn't find the sought executable. It only
succeeds if I precede the command line with cmd.exe /c
(I understand why
it works this way).
为了完整起见,我实际上并没有直接使用 Windows API,但是subprocess.Popen
在 Python 中,虽然我认为我已经缩小了问题的范围针对上述情况.使用 shell = True
,正确的环境是已接;使用 shell = False
(我想要的创建子进程的方式),该调用无法找到我的可执行文件.可执行文件是一个独立的 exe,而不是 cmd.exe 的内在命令.
For completeness, I'm not actually using the Windows API directly, but
subprocess.Popen
in Python, although I think I've narrowed down the problem
to the above circumstances. With shell = True
, the right environment is
picked up; with shell = False
(my desired way of creating the subprocess),
the call fails to locate my executable. The executable is a standalone exe, not an intrinsic command of cmd.exe.
有人可以告诉我我在这里做错了什么或者我的误解在哪里吗?
Can someone please tell my what I'm doing wrong here or where's my misunderstanding?
示例代码:
from subprocess import Popen
import os, sys
exe = "wc.exe" # No other wc.exe on the PATH
env = os.environ.copy()
new_path = os.path.expandvars(r"%HOMEDRIVE%%HOMEPATH%\SmallApps\GnuWin32\bin;%PATH%")
env["PATH"] = os.path.expandvars(new_path).encode(sys.getfilesystemencoding())
Popen(
args=[exe, "*.*"],
env=env,
# shell=True # Works if you uncomment this line.
)
推荐答案
如果你想让 CreateProcess
看到它,你需要修改 current 进程的环境.目前,子shell(无论是包含在命令行中还是通过shell=True
请求)正在看到您修改后的环境,但CreateProcess
的直接调用不是.
You need to modify the environment of the current process if you want CreateProcess
to see it. Currently, the subshell (whether included in the command line or requested via shell=True
) is seeing your modified environment, but the direct invocation of CreateProcess
is not.
这篇关于CreateProcess 如何定位可执行文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!