我正在尝试使用 shutil.which
检查 Windows 10 上是否安装了 Linux 子系统。
在命令提示符中使用 Windows where
命令,我可以看到 wsl.exe
可执行文件的位置。
C:\Users\spike>where wsl
C:\Windows\System32\wsl.exe
上面显示WSL确实存在,并且在我的系统PATH
中。
当我在 Python 中使用 which
函数时,它说找不到可执行文件。
print(which("wsl")) # Returns None
为了确保 which
有效,我在 cmd.exe
上对其进行了测试。
print(which("cmd")) # Returns "C:\Windows\System32\cmd.exe"
行得通。好吧,如果我使用确实有效的命令进行系统 shell 调用会怎么样?
print(system("where wsl")) # Returns 1
退出代码 1,未找到命令 wsl
。
所以我再次在 cmd.exe
上测试它。
print(system("where cmd")) # Returns 0
好的,这样确实起作用了。有什么问题?
对于每个 Python 3 示例,假设这些导入。
from shutil import which
from os import system
为什么证明存在wsl.exe
Python却找不到?
谢谢。
最佳答案
感谢@eryksun,他在评论中帮助解决了这个问题。
问题是我使用的是 32 位 Python,wsl.exe
仅在 C:/Windows/System32
中。问题是 Python 正在寻找 C:/Windows/SysWOW64
来寻找可执行文件。
wsl.exe
is only 64-bit, and you're looking inSysWOW64
instead of the realSystem32
because you're using 32-bit Python. – eryksun
因为 WSL 只支持 64 位系统,所以我最终只是用 64 位 Python 运行我的代码。但是,如果您仅使用 Py32,则替代解决方案是使用系统根环境变量和 os.path.join
直接访问 SysWOW64
。
In Windows 7+, the real
System32
directory is accessible in a 32-bit process as "SysNative". Unfortunately this virtual directory isn't available in a native 64-bit process, so you need to first check whether it exists. For example:sysnative = os.path.join(os.environ['SystemRoot'], 'SysNative'); if os.path.exists(sysnative): ...
. – eryksun
关于Python shutil.which 不适用于 wsl.exe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49039323/