繁体   English   中英

python 的 os.uname() 模块在 windows 但在 wsl 2 (ubuntu 20.04) 中不起作用

[英]os.uname() module of python not working in windows but in wsl 2 (ubuntu 20.04)

当我在 WSL2(ubuntu 20.04)的 python 中编写代码时:

>>import os
>>os.uname()

output 是:

posix.uname_result(sysname='Linux', nodename='Saqib-PC', release='4.19.104-microsoft-standard', version='#1 SMP Wed Feb 19 06:37:35 UTC 2020', machine='x86_64')

但是当我在 windows 终端上运行相同的代码时,它给了我一个 AttributeError:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'os' has no attribute 'uname'

windows 端子和 WSL2 中的两个片段都在此处给出:

在 windows 终端中:请参见此处的图片

在 WSL2(Ubuntu 20.04)中:在此处查看图片

顺便说一句:其他 os 模块在两者中的工作文件


谁能告诉我为什么会这样?

os.uname仅在Unix发行版/版本的子集上可用:。

文档

可用性:Unix 的最新版本。

Without getting into technicalities, WSL is still Unix, much like a Linux VM on a Windows host is "still" Unix (and therefore, os.uname will be available there).

扩展现有答案。

谁能告诉我为什么会这样?

对于主要问题, DeepSpace 的回答是正确且充分的。 os.uname()适用于所有版本的 WSL,因为:

  • WSL1 通过系统调用翻译“假装”为 Linux。 这并不意味着消极——它确实是一个很好的“假装”暴民。 在这种情况下,它实现了uname系统调用所需的 Linux kernel API,以返回 Python 的信息以填充该元组。

  • WSL2(在提出这个问题时还没有发布,或者可能刚刚发布)在虚拟机内的容器内的真实 Linux kernel 下运行。 正如您会在 Docker 容器(来自主机 Linux 内核)中获得uname结果一样,您也会在 WSL2 下获得有效结果。

但是,Windows 没有uname系统调用,因此os.uname()没有在 Python 中为 Windows 实现。

便携式替代品

正如IshtiukAhammed 的回答所提到的,还有 Python platform.uname()调用。 文档

相当便携的uname界面

此方法在 Linux (WSL) 和 Windows Python 解释下都有效。 例如,从 WSL 内部:

$ python.exe # Launches the Windows Python interpreter, assuming it is on the path
Python 3.10.5 ... on win32

>> import platform
>> platform.uname()

uname_result(system='Windows', node='ComputerName', release='10', version='10.0.22000', machine='AMD64')

>> exit()

$ python3 # Linux/WSL
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux

>> import platform
>> import os

>> platform.uname()

uname_result(system='Linux', node='hostname', release='5.10.102.1-microsoft-standard-WSL2', version='#1 SMP Wed Mar 2 00:30:59 UTC 2022', machine='x86_64', processor='x86_64')

>> os.uname()

posix.uname_result(sysname='Linux', nodename='hostname', release='5.10.102.1-microsoft-standard-WSL2', version='#1 SMP Wed Mar 2 00:30:59 UTC 2022', machine='x86_64')

您会注意到键之间的一些细微命名差异,但信息几乎相同。

虽然@IshtiukAhammed 提到“extra info which is the name of [the] processor” ,但事实是 Linux 和 Windows 都没有实现这一点。 同样,来自文档

请注意,许多平台不提供此信息或仅返回与for machine()相同的值

在 Windows Python 的情况下, processor根本不会返回。 对于 Linux,在 WSL 中,它与machine的信息相同。

当然,即使没有“额外信息”, platform.uname()也是可移植性更好的选择。

旁注:谨慎使用 Windows release字段。 在 Windows 11 上,这仍然报告10 10.0.22000实际上是初始 (21H2) Windows 11 版本的构建。

“os.uname()”仅适用于 Unix 发行版/版本的子集:-

因此,它将适用于基于 Linux 的系统;),但不适用于 Windows........

因此,我们可以改用“platform.uname()”模块。 它将提供与“os.uname()”相同的信息,以及一个额外的信息,即“处理器”的名称,所以我认为这是一个更好的解决方案......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM