python调用powershell做ping 172.20.131.101
时间: 2023-05-21 11:05:44
浏览: 120
可以使用以下[代码](https://geek.csdn.net/educolumn/1572ef9b473b4e00f6b2bf6d428b7c27?spm=1055.2569.3001.10083)来在 Python 中调用 PowerShell 并执行 ping [命令](https://geek.csdn.net/educolumn/4641683097031caa4ae7258fda89dcae?spm=1055.2569.3001.10083):
import sub[proc](https://geek.csdn.net/educolumn/535f08ce32f749725902114bc56ad7b8?spm=1055.2569.3001.10083)ess
command = 'powershell.exe Ping 172.20.131.101'
result = sub[proc](https://geek.csdn.net/educolumn/535f08ce32f749725902114bc56ad7b8?spm=1055.2569.3001.10083)ess.check_[output](https://geek.csdn.net/educolumn/3fa40697d361ab41848a3d891b656e90?spm=1055.2569.3001.10083)(command)
print(result)
相关问题
python 调用 powershell
在Python中,你可以使用`subprocess`模块来调用外部程序,例如PowerShell。PowerShell是一个命令行工具,通常需要先确保它在系统路径中可用。以下是如何在Python中调用PowerShell的基本步骤:
```python
import subprocess
def call_powershell(command):
# 将PowerShell命令封装为列表
powershell_command = ['powershell.exe', '-Command', command]
# 使用subprocess.run执行PowerShell命令
response = subprocess.check_output(powershell_command, shell=False, stderr=subprocess.PIPE)
# 如果需要,可以将输出解码为字符串(默认是bytes)
output = response.decode('utf-8')
return output
except
```
python调用powershell
### 回答1:
你可以使用 Python 的 subprocess 模块来调用 PowerShell。例如:
import subprocess
powerShellCommand = "Write-Host 'Hello from PowerShell'"
# Run the PowerShell command using subprocess.run
result = subprocess.run(["powershell", "-Command", powerShellCommand], capture_output=True, text=True)
# print the output
print(result.stdout)
```