系统在 python 中找不到指定的文件错误
The system cannot find the file specified error in 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
has been added in Python 3.5 and it is recommended to use it prior to call
, check_call
or check_output
. See this other question.
run
returns 一个 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)
我想 运行 使用 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
has been added in Python 3.5 and it is recommended to use it prior to call
, check_call
or check_output
. See this other question.
run
returns 一个 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)