gpt4 book ai didi

python - 如何将字符串变量从 python 传递给 PowerShell 函数

转载 作者:行者123 更新时间:2023-12-05 02:33:58 25 4
gpt4 key购买 nike

如何通过调用 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

最佳答案

使用 str.format代码如下。请注意,在调用 PowerShell CLI 时使用 -Command 参数,无需使用 & {...},PowerShell 会将字符串解释为您要执行的命令。也不需要 & (call operator)当调用您的函数 (check) 时,最后,PowerShell 中的函数参数是 named (-Color) or positional , 不要使用 (...) 来包装你的参数。

import subprocess
color = "blue"
subprocess.call([ 'powershell.exe', '-c', '. ./colortest.ps1; check -color {0}'.format(color) ])

关于python - 如何将字符串变量从 python 传递给 PowerShell 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70843534/

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