【发布时间】:2020-05-18 12:20:03
【问题描述】:
我想用C:\Windows\System32\ 下的python 启动WindowsSandbox.exe。但由于某种原因,它不起作用,尽管另一个可执行文件 (cmd.exe) 位于完全相同的位置。
不知道为什么会这样(环境:Windows 10 1909 Python 3.8.0):
CMD:
C:\>where calc.exe
C:\Windows\System32\calc.exe
C:\>where WindowsSandbox.exe
C:\Windows\System32\WindowsSandbox.exe
Python:
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system("calc.exe") # Opens calculator without any problem
0
>>> os.system("C:/Windows/System32/calc.exe") # Opens calculator without any problem
0
>>> os.system("WindowsSandbox.exe")
'WindowsSandbox.exe' is not recognized as an internal or external command,
operable program or batch file.
1
>>> os.system("C:/Windows/System32/WindowsSandbox.exe")
'C:/Windows/System32/WindowsSandbox.exe' is not recognized as an internal or external command,
operable program or batch file.
1
>>>
Nodejs(只是为了证明它应该在 python 上工作):
Welcome to Node.js v12.13.1.
Type ".help" for more information.
> const { execSync } = require("child_process")
undefined
> execSync('calc.exe') //Able to launch calculator
<Buffer >
> execSync('C:/Windows/System32/calc.exe') //Able to launch calculator
<Buffer >
> execSync('WindowsSandbox.exe') //Able to launch Windows Sandbox
<Buffer >
> execSync('C:/Windows/System32/WindowsSandbox.exe') //Able to launch Windows Sandbox
<Buffer >
>
我还尝试了双重转义 ('C:\\Windows\\System32\\WindowsSandbox.exe')、原始字符串 (r'C:\Windows\System32\WindowsSandbox.exe') 和反斜杠 ('C:/Windows/System32/WindowsSandbox.exe')。它们都不起作用
%PATH%应该没有问题(cmd.exe和WindowsSandbox.exe都可以直接从cmd运行)。
任何帮助将不胜感激,谢谢。
【问题讨论】:
-
原因很简单:64位Windows上有两个
C:\Windows\System32。第一个是%SystemRoot%\System32包含 64 位可执行文件。第二个是%SystemRoot%\SysWOW64包含 32 位可执行文件。每当 32 位应用程序想要访问目录%SystemRoot%\System32时,Windows File System Redirector 会将此文件系统访问重定向到 Microsoft 记录的%SystemRoot%\SysWOW64。 -
所以在使用 32 位
python.exe时,使用os.system会导致使用由%SystemRoot%\System32\cmd.exe定义的环境变量ComSpec,这会导致执行 32 位C:\Windows\SysWOW64\cmd.exe在您现在搜索C:\Windows\System32\WindowsSandbox.exe的计算机上重定向到C:\Windows\SysWOW64\WindowsSandbox.exe并且该可执行文件在该目录中不存在。就是这样。 -
感谢您的解释,有没有办法使用 32 位 Python 从“实际”
C:/Windows/System32调用WindowsSandbox.exe或任何其他 64 位程序?覆盖 %ComSpec% 变量? -
最好检查 Python 脚本文件在哪个环境中执行,即是否在 64 位 Windows 上由 32 位或 64 位 Python 执行。这可以通过获取环境变量
SystemRoot的值、将其字符串值与\Sysnative\cmd.exe连接并检查该文件是否存在来轻松完成。这仅在 64 位 Windows 上是正确的,Python 脚本在 32 位环境中执行。在这种情况下,WindowsSandbox.exe的完整限定文件名是环境变量SystemRoot与\Sysnative\WindowsSandbox.exe连接的字符串值。 -
在 32 位 Windows 上以及在 64 位 Windows 上由 64 位 Python 执行 Python 脚本时,文件
%SystemRoot%\Sysnative\cmd.exe不存在,因此正确的完整文件名WindowsSandbox.exe是环境变量SystemRoot与\System32\WindowsSandbox.exe连接的字符串值。但是,os.system的用法已被弃用,不应再使用。 subprocess module 现在应该用于使用 Python 3.x.x 编写新的 Python 代码。
标签: python python-3.x cmd path