使用 Python 3.5 执行 PowerShell 命令

tar*_*a23 3 python powershell windows-scripting

我一直在研究一个需要通过 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^')
Run Code Online (Sandbox Code Playgroud)

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

'"Write-Output 'Hello world'"' is not recognized as an internal or external command,
operable program or batch file.
Run Code Online (Sandbox Code Playgroud)

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

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

eki*_*iim 5

我相信这是因为在 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)
Run Code Online (Sandbox Code Playgroud)

如果powershell不在路径中,您可以使用可执行文件的完整路径,或者如果它在路径中,您可以将其POWERSHELL_COMMAND = "powershell"用作命令,小心,使用反斜杠的Windows路径,以避免错误,您可以使用原始字符串。

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

文档

在 shell=True 的 Windows 上,COMSPEC 环境变量指定默认 shell。

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