Windows x64 与 x86:硬件与 OS 与进程

Windows x64 vs x86: Hardware vs. OS vs. process

我在 Windows 上的 Python 3 中遇到基于 x86 与 x64 的问题。

我需要知道我的 Python 程序是否 运行ning:

它们不是一回事(根本不是!)。

AMD64 架构处理器可以 运行 64 位或 32 位 操作系统

并且 64 位操作系统可以 运行 64 位或 32 位 进程

我知道:

为了避免不可避免的 "why do you care?" 问题,这是因为我的 Python 程序正在自动配置 Windows - 在 x86 和 x64 Windows 上,事情在不同的地方,但我事先不知道我的程序是 运行ning 在 32 位还是 64 位 Python.

所以我需要弄清楚。

所以您的实际问题是,您 运行 使用的 Windows 是否是 x64? :)

抄袭this and this,怎么样

import os
arch = (
    os.environ.get("PROCESSOR_ARCHITEW6432") or 
    os.environ.get("PROCESSOR_ARCHITECTURE")
)
# `arch` should now reliably be `x64` if the system is 64-bit.

我相信这会起作用,但我还没有在 Windows 的 32 位版本上测试过它:

import sys, os
x64_process = (sys.maxsize > 2**32)
x64_os = os.environ.get('ProgramW6432') is not None

这可能是我最重要的用例 - 在注册表更改后重新启动 explorer.exe:

def restartExplorer():
    '''Restart explorer'''
    do(r'taskkill /f /im explorer.exe')
    if x64_os and not x64_process:
        do(os.environ['systemroot']+ r'\sysnative\cmd.exe /c start /B explorer.exe') # because this Python is in a 32 bit process
    else:
        do("start explorer.exe")

我不会给你 do() 的实现,因为它很明显。 (但如果有人问,会的。)