H_H*_*H_H 25 python powershell function
我需要从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."
Run Code Online (Sandbox Code Playgroud)
和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)
Run Code Online (Sandbox Code Playgroud)
所以,不知何故,我想运行PowerShell示例中的'hello()'或'bye()'函数.知道如何将参数传递给函数也是很好的.谢谢!
Ada*_*rey 37
你想要两件事:点源脚本(据我所知)(类似于python的import)和subprocess.call.
import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./SamplePowershell\";", "&hello"])
Run Code Online (Sandbox Code Playgroud)
所以这里发生的是我们启动PowerShell,告诉它导入你的脚本,并使用分号来结束该语句.然后我们可以执行更多命令,即hello.
您还想为函数添加参数,所以让我们使用上面文章中的参数(稍微修改):
Function addOne($intIN)
{
Write-Host ($intIN + 1)
}
Run Code Online (Sandbox Code Playgroud)
然后使用您想要的任何参数调用该函数,只要powershell可以处理该输入.所以我们将上面的python修改为:
import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./SamplePowershell\";", "&addOne(10)"])
Run Code Online (Sandbox Code Playgroud)
这给了我输出:
PowerShell sample says hello.
11
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
75963 次 |
| 最近记录: |