39

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()」関数を実行したいと考えています。また、関数にパラメーターを渡す方法を知っておくとよいでしょう。ありがとう!

4

2 に答える 2

52

スクリプトのドット ソース((私が知る限り) Python のインポートに似ています) とsubprocess.callの2 つが必要です。

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
于 2013-01-28T02:32:01.183 に答える
0

これを行うための短くて簡単な方法を次に示します

import os
os.system("powershell.exe echo hello world")
于 2021-06-20T14:04:09.887 に答える