python 调用 powershell
时间: 2024-06-20 17:02:02
浏览: 145
在Python中,你可以使用`subprocess`模块来调用外部程序,例如PowerShell。PowerShell是一个命令行工具,通常需要先确保它在[系统](https://geek.csdn.net/educolumn/073441cd796e7450c3f98600b0cbeb95?spm=1055.2569.3001.10083)路径中可用。以下是如何在Python中调用PowerShell的基本步骤:
```python
import subprocess
def call_powershell(command):
# 将PowerShell命令封装为[列表](https://geek.csdn.net/educolumn/ba94496e6cfa8630df5d047358ad9719?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083)
powershell_command = ['powershell.exe', '-Command', command]
# 使用subprocess.[run](https://geek.csdn.net/educolumn/15da07d43c7a20f5ec210826be35c36c?spm=1055.2569.3001.10083)执行PowerShell命令
response = subprocess.check_output(powershell_command, shell=False, stderr=subprocess.PIPE)
# 如果需要,可以将输出解码为[字符串](https://geek.csdn.net/educolumn/ba94496e6cfa8630df5d047358ad9719?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083)(默认是bytes)
output = response.decode('utf-8')
return output
except subprocess.CalledProcessError as e:
print(f"An error occurred: {e.stderr.decode('utf-8')}")
return None
# 使用示例
command_to_[run](https://geek.csdn.net/educolumn/15da07d43c7a20f5ec210826be35c36c?spm=1055.2569.3001.10083) = "Get-Process" # 你想要执行的Po
```