在Python中嵌入Powershell脚本错误

2024-06-25 22:50:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个功能齐全的Powershell脚本,可以生成没有任何问题的HTML报告。我正在尝试创建一个Python脚本来运行PowerShell脚本,这样我就可以通过电子邮件将报告发送出去,其中包含Python以及我工作的其他原因。这是我第一次尝试在Python脚本中运行Powershell脚本,我仍然是Python的新手,使用Python比使用Powershell更好。我花了2-3个小时研究这个问题,结果弄得我头晕目眩。我的最终目标是使用Python创建广告报告,但我必须从头开始学习,我拥有的Powershell脚本现在已经完成了我需要它完成的所有工作

提前谢谢

代码:

import subprocess
result = subprocess.run(['C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', 'C:\\Users\\wills.b\\Documents\\scripts\\ADHTMLREPORT.ps1'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
print(result)

错误:

bryanwi09@KY-IT-002:/mnt/c/Users/wills.b/Documents/scripts$ python3 report.py
  File "report.py", line 2
    result = subprocess.run(['C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', 'C:\Users\wills.b\Documents\scripts\ADHTMLREPORT.ps1'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
                                                                                               ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
bryanwi09@KY-IT-002:/mnt/c/Users/wills.b/Documents/scripts$ python3 report.py
CompletedProcess(args=['C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', 'C:\\Users\\wills.b\\Documents\\scripts\\ADHTMLREPORT.ps1'], returncode=127, stdout=b'C:\\Users\\wills.b\\Documents\\scripts\\ADHTMLREPORT.ps1: 1: C:WindowsSystem32WindowsPowerShellv1.0powershell.exe: not found\n')

Tags: 脚本windows报告scriptsresultexeusersdocuments
1条回答
网友
1楼 · 发布于 2024-06-25 22:50:15

'C:\Users\wills.b\Documents\scripts\ADHTMLREPORT.ps1'从原始代码片段更改为r'C:\Users\wills.b\Documents\scripts\ADHTMLREPORT.ps1''C:\\Users\\wills.b\\Documents\\scripts\\ADHTMLREPORT.ps1'(请参阅@Axe319的numb主动编辑)

import subprocess 
result = subprocess.run(['C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',
    r'C:\Users\wills.b\Documents\scripts\ADHTMLREPORT.ps1'],      ### improved ###
    stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
print(result)

阅读String and Bytes literals了解解释:

Escape sequences only recognized in string literals are:

Escape Sequence  Meaning                                      Notes

\N{name}         Character named name in the Unicode database (4)
\uxxxx           Character with 16-bit hex value xxxx         (5)
\Uxxxxxxxx       Character with 32-bit hex value xxxxxxxx     (6)

Notes:

  1. Changed in version 3.3: Support for name aliases 1 has been added.
  2. Exactly four hex digits are required.
  3. Any Unicode character can be encoded this way. Exactly eight hex digits are required.

相关问题 更多 >