Python shutil.which 不适用于 wsl.exe

标签 python windows python-3.x shell shutil

我正在尝试使用 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 in SysWOW64 instead of the real System32 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/

相关文章:

windows - 在 Windows 上跨共享驱动器统一

python - 如何使用 pandas 在标题行中应用过滤器

python - 为什么我在发送 post 请求时收到 "Method not Allowed (HTTP CODE 405)"?

python - 使用jupyter笔记本读取xlsx文件

python - dask DataFrame 查询然后示例错误

python - 我想解析 xml 数据并将其作为 mysql 查询进行处理

python - 使用条件和函数向量化嵌套循环

python - 如何使用 Pandas 删除列值中 URL 字符串的第一部分?

java - Linux 键盘布局

windows - 在 Windows 上使用 LLVM 作为编译器后端 - 需要外部工具吗?