【发布时间】:2014-11-19 20:16:29
【问题描述】:
我必须通过 python 脚本调用两个 powershell 命令。我目前正在为此使用 subprocess.Popen。
第一个命令返回一个 powershell 对象。示例:
PS>$temp = <powershell_command_1>
$temp 对象中有多个属性。必须将整个对象传递给同一脚本中的第二个 powershell 对象。例如。
PS><powershell_command_2> -object $temp
如果 $temp 是一个字符串,我在传递 python 字符串变量时没有问题。但是,在这种情况下 $temp 是一个对象。如何将此值传递给第二个 PS cmdlet?
这是回溯
Traceback (most recent call last):
File "file.py", line 430, in <module>
status = c1.configure_cluster()
File "file.py", line 319, in configure_cluster
configure_cluster = subprocess.Popen([self.powershell_binary,'-ExecutionPolicy','ByPass',r'Cmdlet2', temp], stdout=subprocess.PIPE)
File "C:\Python34\lib\subprocess.py", line 858, in __init__
restore_signals, start_new_session)
File "C:\Python34\lib\subprocess.py", line 1085, in _execute_child
args = list2cmdline(args)
File "C:\Python34\lib\subprocess.py", line 663, in list2cmdline
needquote = (" " in arg) or ("\t" in arg) or not arg
TypeError: Type str doesn't support the buffer API
【问题讨论】:
-
你看过
Invoke-Commandcmdlet吗? -
这两个powershell命令是分开运行还是同时运行?例如
Powershell -command { command_1 | command_2 }如果第二个命令接受管道,或者Powershell -command { command_2 -object (command_1) }如果不接受。 -
它们必须单独运行。 python 脚本调用 cmdlet 1,然后根据输出变量的值进行其他处理,随后必须调用 cmdlet 2,其值为 $temp。
-
想到两件事:使用
Export-CliXml/Import-CliXml来持久化对象;或 Powershell 远程会话应该是持久的,因此您可以创建会话,使其保持运行,并使用 Invoke-Command 向其发送更多命令。
标签: python powershell