python - 在尝试通过在 powershell 中执行代码的 python 脚本运行 print ('hello world' 时发现错误

标签 python powershell

我目前正在尝试使用以下代码在 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/

相关文章:

python - 如何阻止 Python 的 csv.DictWriter.writerows 在 Windows 中的行之间添加空行?

python - 任何带有字符串(字母和标点符号)的数字的正则表达式是什么?

powershell - PowerShell脚本参数未正确解析

list - powershell列表列表:条目初始化由地址而不是值完成

powershell - Try/Catch 或 Error 变量并使用

windows - CMD/Powershell : Commands not working with cURL. Cygwin 工作

python - Pandas 正则表达式,用 char 替换 group

python - R lm 与 Python sklearn linear_model

python - 检查二进制表示中是否存在位序列

node.js - 从 GitHub 操作中的 Node 程序运行 Powershell 脚本