gpt4 book ai didi

python - 从 Python 脚本运行 PowerShell 函数

转载 作者:IT老高 更新时间:2023-10-28 22:22:04 26 4
gpt4 key购买 nike

我需要从 Python 脚本运行 PowerShell 函数。 .ps1 和 .py 文件当前都位于同一目录中。我要调用的函数在 PowerShell 脚本中。我见过的大多数答案都是从 Python 运行整个 PowerShell 脚本。在这种情况下,我尝试从 Python 脚本运行 PowerShell 脚本中的单个函数。

这是示例 PowerShell 脚本:

# sample PowerShell
Function hello
{
Write-Host "Hi from the hello function : )"
}

Function bye
{
Write-Host "Goodbye"
}

Write-Host "PowerShell sample says hello."

和 Python 脚本:

import argparse
import subprocess as sp

parser = argparse.ArgumentParser(description='Sample call to PowerShell function from Python')
parser.add_argument('--functionToCall', metavar='-f', default='hello', help='Specify function to run')

args = parser.parse_args()

psResult = sp.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
'-ExecutionPolicy',
'Unrestricted',
'. ./samplePowerShell',
args.functionToCall],
stdout = sp.PIPE,
stderr = sp.PIPE)

output, error = psResult.communicate()
rc = psResult.returncode

print "Return code given to Python script is: " + str(rc)
print "\n\nstdout:\n\n" + str(output)
print "\n\nstderr: " + str(error)

所以,不知何故,我想运行 PowerShell 示例中的“hello()”或“bye()”函数。知道如何将参数传递给函数也很好。谢谢!

最佳答案

你想要两件事:dot source the script (据我所知)类似于 python 的导入)和 subprocess.call .

import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./SamplePowershell\";", "&hello"])

所以这里发生的是我们启动 powershell,告诉它导入你的脚本,并使用分号结束该语句。然后我们可以执行更多的命令,即hello。

您还想为函数添加参数,所以让我们使用上面文章中的那个(稍作修改):

Function addOne($intIN)
{
Write-Host ($intIN + 1)
}

然后使用您想要的任何参数调用该函数,只要 powershell 可以处理该输入。所以我们将上面的python修改为:

import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./SamplePowershell\";", "&addOne(10)"])

这给了我输出:

PowerShell sample says hello.
11

关于python - 从 Python 脚本运行 PowerShell 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14508809/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com