温馨提示×

python怎么调用powershell命令

小亿
111
2024-12-07 07:38:30
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要在Python中调用PowerShell命令,您可以使用subprocess模块

import subprocess

# PowerShell命令
powershell_command = "Get-Process"

# 在PowerShell中运行命令
result = subprocess.run(["powershell", "-Command", powershell_command], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

# 输出结果
print("输出:")
print(result.stdout)

# 输出错误(如果有)
if result.stderr:
    print("错误:")
    print(result.stderr)

在这个例子中,我们使用subprocess.run()函数执行了一个简单的PowerShell命令Get-Process,该命令列出当前正在运行的所有进程。stdoutstderr参数用于捕获命令的输出和错误(如果有)。text=True参数表示我们希望以文本形式接收输出,而不是字节形式。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:python如何执行powershell命令

0