【问题标题】:Embedding Powershell Script in Python Error在 Python 错误中嵌入 Powershell 脚本
【发布时间】:2020-09-01 17:33:05
【问题描述】:

我有一个功能齐全的 Powershell 脚本,可以毫无问题地生成 HTML 报告。我正在尝试创建一个 Python 脚本来运行 PowerShell 脚本,以便我可以通过电子邮件发送带有 Python 的报告以及我工作的其他原因。这是我第一次尝试在 Python 脚本中运行 Powershell 脚本,但我仍然是 Python 的新手,并且 Python 比 Powershell 更好。研究了这个问题 2-3 个小时,我摸不着头脑。我的最终目标是使用 Python 创建 AD 报告,但我必须从头开始学习,而我拥有的 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')

【问题讨论】:

  • 如果您在 Powershell 提示符下运行 .ps1 文件,它是否有效?如果是这样,那么问题出在 Python 部分。如果没有,那么它在 Powershell 部分。
  • @vonPryz,是的,.ps1 脚本输出一个 .html 文件,然后通过电子邮件发送。
  • python3 report.pypython.exe report.py 的结果不同(Windows 10 上的 WSL)...

标签: python python-3.x powershell subprocess


【解决方案1】:

'C:\Users\wills.b\Documents\scripts\ADHTMLREPORT.ps1' 从原始代码 sn-p 更改为 r'C:\Users\wills.b\Documents\scripts\ADHTMLREPORT.ps1''C:\\Users\\wills.b\\Documents\\scripts\\ADHTMLREPORT.ps1'(参见 @Axe319 的麻木主动编辑)。

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 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)

注意事项:

  1. 3.3 版更改:添加了对名称别名 1 的支持。
  2. 需要正好四个十六进制数字。
  3. 任何 Unicode 字符都可以用这种方式编码。 需要八位十六进制数字

【讨论】:

  • 感谢@JosefZ 的回复,我稍后会检查并通知您。在你回复之前差点忘了这件事。
猜你喜欢
  • 2013-01-29
  • 2015-07-07
  • 1970-01-01
  • 2021-05-29
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
  • 2020-12-10
  • 2019-07-11
相关资源
最近更新 更多