gpt4 book ai didi

python - 使用 Python 3.5 执行 PowerShell 命令

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:51 26 4
gpt4 key购买 nike

我一直在处理一个需要通过 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" 行,脚本运行得很好。我不同意为什么会发生这种情况。这不是我正在运行的确切脚本,但它在我的机器上产生了同样的问题。如果我只是在命令行中输入问题命令,它会按预期将 "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" 作为命令,注意,使用反斜杠窗口路径,以避免错误,您可以使用原始字符串。

要验证您的路径中是否有 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

关于python - 使用 Python 3.5 执行 PowerShell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54257795/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com