使用 Python 3.5 执行 PowerShell 命令

Executing PowerShell commands with Python 3.5

我一直在处理一个问题,需要通过 PowerShell 命令行将 Python 脚本转换为 运行。该脚本应将命令传递给命令行并保存输出。但是,我 运行 遇到无法识别某些命令行参数的问题。

import subprocess
try:
    output = subprocess.check_output\
    (["Write-Output 'Hello world'"], shell=True)
    # (["dir"], shell=True)
except subprocess.CalledProcessError as e:
    print(e.output)
    print('^Error Output^')

如果我将当前命令与 check_output 命令一起使用,我会收到一条错误消息:

'"Write-Output 'Hello world'"' is not recognized as an internal or external command,
operable program or batch file.

如果我只使用 "dir" 行,脚本 运行 就可以了。我不同意为什么会发生这种情况。这不是我 运行ning 的确切脚本,但它在我的机器上产生了同样的问题。如果我只是在命令行中输入问题命令,它会按预期将 "Hello world" 输出到新行。

任何关于为什么会发生这种情况的见解将不胜感激。如果相关,我不想使用任何类型的管理员权限解决方法。

我相信这是因为在 Windows 中你的默认 Shell 不是 PowerShell,你可以执行一个 Powershell 命令,通过使用你需要的参数执行 Powershell 来调用可执行文件.

例如


POWERSHELL_COMMAND = r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe'

subprocess.Popen([POWERSHELL_COMMAND,
                  '-ExecutionPolicy', 'Unrestricted',
                  'Write-Output', 'Hello World'],
                  stdout = subprocess.PIPE,
                  stderr = subprocess.PIPE)

如果 powershell 不在路径中,您可以使用可执行文件的完整路径 或者如果它在路径中,您可以只使用 POWERSHELL_COMMAND = "powershell" 作为命令,请注意,使用反斜杠 windows 路径,以避免错误,您可以使用原始字符串。

要验证您的路径中是否有 powershell,您可以转到配置并检查,或者您可以只打开 cmd 并键入 powershell 如果它有效,那么您可以假设powershell 在路径中。

来自docs

On Windows with shell=True, the COMSPEC environment variable specifies the default shell.

所以 set COMSPEC=powershell 允许 shell=True 使用 powershell 作为默认值而不是 cmd