我目前正在尝试使用以下代码在 powershell 中运行一个简单的 hello world 程序:
import subprocess
import sys
p = subprocess.Popen(["powershell.exe",
'C:/users/m.m/Desktop/hello.ps1'],
stdout = sys.stdout)
p.communicate()
我想做的是这个;我已在桌面上保存了带有 powershell 扩展的“hello.ps1”python 程序,其中包含 print("hello, world!")
,并且我想创建一个程序它读取我的 python 文件中的文件,打开它们并通过 python
命令调用 python 后在 powershell 中运行这些脚本。
我已经按照此处的建议尝试了上面的代码==> Running powershell script within python script, how to make python print the powershell output while it is running ,但它给了我安全错误。
这是我运行上面的代码时遇到的错误:
C:/users/m.m/Desktop/hello.ps1 : File C:\users\m.m\Desktop\hello.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
的更多信息可以在 here 找到。
关于python - 在尝试通过在 powershell 中执行代码的 python 脚本运行 print ('hello world' 时发现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58339574/