尝试通过执行PowerShell代码的Python脚本运行print('hello world')时发现错误



我目前正在尝试使用以下代码在powershell中运行一个简单的hello world程序:

import subprocess
import sys
p = subprocess.Popen(["powershell.exe",
'C:/users/m.m/Desktop/hello.ps1'],
stdout = sys.stdout)
p.communicate()

我正在尝试做的是这个; 我已经保存了">Hello.PS1"Python程序,其中包含桌面中的print("hello, world!")的PowerShell扩展,我想创建一个程序来读取我的python文件中的文件,打开它们并在通过python命令调用Python后在PowerShell中运行这些脚本

我已经按照此处的建议尝试了上面的代码 ==> 在 python 脚本中运行 powershell 脚本,如何让 python 在运行时打印 powershell 输出,但它给了我安全错误。

这是我在运行上述代码时遇到的错误:

C:/users/m.m/Desktop/hello.ps1 : File C:usersm.mDesktophello.ps1 cannot 
be loaded because running scripts is 
disabled on this system. For more information, see about_Execution_Policies 
at 
https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ C:/users/m.m/Desktop/hello.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess

主要目标是:使用 python 为 powershell 编写脚本。

您收到该错误可能有两个原因,首先是因为您没有以管理员身份运行PowerShell,您应该保存脚本并以管理员身份重新加载ISE。

其次,您必须设置以下内容:

Set-ExecutionPolicy RemoteSigned

Set-ExecutionPolicy unrestricted

在运行脚本之前运行此命令。

有关Set-ExecutionPolicy的更多信息,请参阅此处

确保可以运行Powershell脚本(默认情况下处于禁用状态(。 以管理员身份在PowerShell窗口中运行此命令

Set-ExecutionPolicy RemoteSigned

因为您得到的错误是

无法加载,因为在此系统上禁用了运行脚本。