如何通過呼叫 powershell 函式傳遞要從 python 腳本列印的可變顏色。
function check($color){
Write-Host "I have a $color shirt"
}
import subprocess
color = "blue"
subprocess.call(["powershell.exe", '-Command', '&{. "./colortest.ps1"; & check(color)}'])
上面的代碼導致以下錯誤
color : The term 'color' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:27
&{. "./colortest.ps1"; & check(color)}
~~~
CategoryInfo : ObjectNotFound: (color:String) [], CommandNotFoundException
FullyQualifiedErrorId : CommandNotFoundException
如果我直接將實際顏色作為常量引數插入,那么我會得到想要的結果,但用變數替換它會失敗。
subprocess.call(["powershell.exe", '-Command', '&{. "./colortest.ps1"; & check("blue")}'])
結果
I have a blue shirt
uj5u.com熱心網友回復:
使用str.format代碼可以如下。注意,使用引數呼叫PowerShell CLI-Command時,無需使用& {...},PowerShell 會將字串解釋為您要執行的命令。呼叫函式 () 時也不需要&(call operator)check,最后,PowerShell 中的函式引數要么命名為 ( -Color) 要么定位,不要(...)用于包裝引數。
import subprocess
color = "blue"
subprocess.call([ 'powershell.exe', '-c', '. ./colortest.ps1; check -color {0}'.format(color) ])
uj5u.com熱心網友回復:
您在這部分的問題:
'&{. "./colortest.ps1"; & check(color)}'
是您將字串傳遞color給函式check。您需要改為傳遞區域變數的值color。所以你可以使用F-string。
subprocess.call(["powershell.exe", '-Command', f"&{. "./colortest.ps1"; & check({color})}"])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/420890.html
標籤:
