【问题标题】:The system cannot find the file specified error in python系统在python中找不到文件指定错误
【发布时间】:2021-04-20 08:32:12
【问题描述】:

我想使用 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 命令?

提前致谢。

【问题讨论】:

标签: python-3.x powershell subprocess get-winevent


【解决方案1】:

我会使用run 而不是check_outputrunhas been added in Python 3.5,建议在callcheck_callcheck_output之前使用。见this other question

run 返回一个CompletedProcess,即documented here

这是您的脚本的更新版本:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2016-09-19
    • 2012-03-02
    • 2011-09-17
    • 1970-01-01
    相关资源
    最近更新 更多