【问题标题】:Run PowerShell function from Python script从 Python 脚本运行 PowerShell 函数
【发布时间】:2013-01-08 15:35:34
【问题描述】:

我需要从 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()”函数。知道如何将参数传递给函数也很好。 谢谢!

【问题讨论】:

    标签: python function powershell


    【解决方案1】:

    你想要两件事: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
    

    【讨论】:

    • 谢谢。这很有帮助!现在,在包含您指出的转义序列之后,我似乎成功地使用了 subprocess.Popen() 调用以及 subprocess.call()。请问使用 subprocess.call() 是否比 subprocess.Popen() 有优势?我使用 Popen() 的第一个原因是收集标准输出、标准错误和返回码。我也可以用 subprocess.call() 做到这一点吗?还要感谢您提供带参数调用函数的语法。
    • subprocess.call() 等到程序完成。如果您希望能够在程序运行时与程序通信,则 Popen 会更有用。如果您想要 stdout 和 stderr 流,我知道使用 subprocess 模块获取它们的唯一方法是将它们输出到文本文件,如下所示: returnValue= subprocess.call("", executable="fposo.exe", stdout =open("out.txt", "w+"), stderr=open("err.txt", "w+")) print "childProcess 返回" + str(returnValue)
    • 更相关: print "childProcess returned " + str(subprocess.call([".\"./SamplePowershell\";", "&hello"], executable="C:\\WINDOWS\ \system32\\WindowsPowerShell\\v1.0\\powershell.exe", stdout=open("out.txt", "w+"), stderr=open("err.txt", "w+")))跨度>
    • 顺便说一句:在 PowerShell 中,函数的调用类似于 shell 命令 - foo arg1 arg2 - 像 C# 方法 - foo(arg1, arg2);见Get-Help about_Parsing。如果您使用, 分隔参数,您将构造一个array,函数将其视为single 参数。为防止意外使用方法语法,请使用Set-StrictMode -Version 2 或更高版本,但请注意其其他影响。
    • 顺便说一句:我建议不要在示例代码中使用Write-Host,因为它可能会误导初学者认为(a)使用 cmdlet 是在 PowerShell 中生成输出所必需的(它不是)并且 (b) 用于生成输出的 cmdlet 是 Write-Host(通常不是,除非您的意图是直接写入屏幕(主机)而不是输出数据)。
    【解决方案2】:

    这是一个简单的方法

    import os
    os.system("powershell.exe echo hello world")
    

    【讨论】:

      猜你喜欢
      • 2019-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 2018-02-15
      • 1970-01-01
      相关资源
      最近更新 更多