python-3.x - 系统在python中找不到文件指定错误
问题描述
我想使用 python 脚本运行以下 power-shell 命令:
timedetail = subprocess.check_output('powershell.exe Get-WinEvent -LogName Microsoft-Windows-TerminalServices-LocalSessionManager/Operational | Where { ($_.ID -eq "25" -or $_.ID -eq "21") -and ($_.TimeCreated -gt [datetime]::Today.AddDays(-2))} |Select TimeCreated , Message | sort-Object -Property TimeCreated -Unique | Format-List', startupinfo=st_inf,shell=False,stderr=subprocess.PIPE, stdin=subprocess.PIPE).decode('ANSI').strip().splitlines()
但这不适用于 python 代码,这显示错误:
[WinError 2] The system cannot find the file specified
任何人都可以帮助如何使用 python 代码运行 powershell 命令?
提前致谢。
解决方案
我会使用run
而不是check_output
. run
Python 3.5 中已添加,建议在call
,check_call
或check_output
. 请参阅另一个问题。
run
返回CompletedProcess
此处记录的 a 。
这是您的脚本的更新版本:
import subprocess
def run_powershell_command(command):
completed = subprocess.run(["powershell", "-Command", command], capture_output=True)
return completed
get_logs_command = 'Get-WinEvent -LogName Microsoft-Windows-TerminalServices-LocalSessionManager/Operational | Where { ($_.ID -eq "25" -or $_.ID -eq "21") -and ($_.TimeCreated -gt [datetime]::Today.AddDays(-2))} |Select TimeCreated , Message | sort-Object -Property TimeCreated -Unique | Format-List'
result = run_powershell_command(get_logs_command)
for line in result.stdout.splitlines():
print(line)
推荐阅读
- ruby-on-rails - Rails 5:如何从 API 的响应中保存 Array of Hash 中的 uniq 元素
- kubernetes - 这里实际节点的 CPU 和内存容量是多少?
- css - 如何制作浮动:相对位置下降?
- python - 如何加快我的python字典循环?
- git - 与推送相关的提交列表(远程)
- javascript - 单击另一个表格行时关闭上一个表格行
- python - 在python中合并CSV文件
- php - Symfony/Doctrine 不断创建相同的迁移
- phpstorm - 如何在不混合 PhpStorm 中的类声明的情况下附加项目?
- sql - 使用另一个表中的单个列的值更新特定列