有时候需要Python不能完成一些功能时,需要用到PowerShell的脚本,但是想要完成一个完整性功能,就需要在Python执行完会直接调用PowerShell脚本,以下举个例子来实现这个功能。
先写一个PowerShell的脚本:
PowerShell 测试Ping功能 #通过Python函数传进来的iplist进行Ping测试,并返回结果 function test_ping($iplist){ #$a = $iplist.split(",") foreach ($myip in $iplist) #foreach ($myip in $a){ $strQuery = "select * from win32_pingstatus where address = '$myip'" # 利用 Get-WmiObject 送出 ping 的查詢 $wmi = Get-WmiObject -query $strQuery if ($wmi.statuscode -eq 0) { echo "Pinging`t$myip...`tsuccessful" } else { echo "Pinging`t$myip...`tErrorCode:" + $wmi.statuscode } } } test_ping $args # -*- coding: utf-8 -*- import subprocess def python_call_powershell(ip): try: args = [r"powershell", r"D:/test_ping.ps1",ip] p = subprocess.Popen(args, stdout=subprocess.PIPE) dt = p.stdout.read()#这里是标准输出,也就是PowerShell输出什么都会被传递这里输出 return dt except Exception, e: print e return False if __name__ == "__main__": #ip = ["blog.bigyoung.cn", "blog.bigyoung.cn0", "3.3.3.3"] ip = '"blog.bigyoung.cn", "blog.bigyoung.cn0", "3.3.3.3"'#这里定义的IPlist 需要是一个str类型 # print python_call_powershell(",".join(ip)) print python_call_powershell(ip)这个脚本的原理简单点就是通过Python的子进程调用Poweshell脚本,然后传回Ping结果。
具体的传参说明,需要进一步了解Python的subprocess第三方库。
参考文档:http://www.jb51.net/article/59292.htm
所有评论(0)