2015-04-28 70 views
0

我正在編寫一個腳本來針對機器列表運行PSinfo(來自Sysinternals套件),然後我想在執行其他操作之前搜索輸出中的特定字符串。基本的代碼如下:嘗試在命令輸出中搜索字符串

with open ("specific-pcs.txt") as machines: 
    line = [] 
    for machineName in machines: 
     machineName = machineName.strip() 

     ps_Info = subprocess.Popen("location of PsInfo \\" + machineName + " -s").communicate()[0] 

     if ("Silverlight" in ps_Info): 
      subprocess.Popen("wmic product where caption='Microsoft Silverlight' call uninstall") 
      print "Uninstalling Silverlight" 
     else: 
      pass 

中psinfo的輸出看起來是這樣的:

Microsoft Office Word MUI (English) 2010 14.0.7015.1000 
Microsoft ReportViewer 2010 Redistributable 10.0.30319 
Microsoft Silverlight 5.1.10411.0 
Microsoft Visual C++ 2008 Redistributable - x86 9.0.30729.4148 9.0.30729.4148 
Realtek High Definition Audio Driver 6.0.1.7004 

但由於正在運行的代碼,它抱怨說,「‘Nonetype’不是可迭代」。 我需要的是說如果Silverlight(在這種情況下)存在於輸出中。 我需要改變什麼?

謝謝,克里斯。

回答

0

communicate一個流回報None如果不是重定向到一個管道,這意味着你的情況:

subprocess.Popen("location of PsInfo \\" + machineName + " -s").communicate() 

將返回(None, None)的,並且使用Nonein操作時,你得到的argument of type 'NoneType' is not iterable錯誤。

此外,你應該叫Popen,而不是一個單一的字符串時使用的參數列表,所以這應該工作:

ps_Info = subprocess.Popen([r"C:\Path\To\PsInfo", r"\\" + machineName, "-s"], 
          stdout=subprocess.PIPE).communicate()[0] 
+0

感謝您的答覆,@mata。每當我添加[]括號和stdout = subprocess.PIPE位時,python就會在腳本運行時「找不到指定的文件」,就像你的例子中的+或逗號一樣......任何想法爲什麼是這樣? – user3514446

+0

您是否使用PsInfo的完整路徑,並且如果您在字符串中使用反斜槓,則應該使用原始字符串'r'...''。更新了我的答案,我也忘了在機器名稱前添加反斜槓。 – mata

+0

我做了,是的,與'r'。唯一的區別是它是否包含[]括號和stdout = subprocess.PIPE位。 – user3514446