2016-11-30 86 views
0

我的腳本的目標是將netstart -a的結果打印到名爲currservices.txt的文件中,然後找到在其中包含單詞Network或Diagnostic的服務。我創建了循環來列出所有已啓動的服務,但不太瞭解如何使用循環內部的find()函數打印出具有網絡或診斷信息的服務。在循環中使用find()

import os 
my_command = "net start >I:\\temp\\mypythonfiles\\currservices.txt" 
os.system(my_command) 
value = "Network Diagnostic" 
my_path = "I:\\temp\\mypythonfiles\\currservices.txt" 
my_handle = open(my_path, "r") 
for line_of_text in my_handle: 
    print (line_of_text) 
    find_val = value.find("Network ") 
    print(find_val) 
    my_handle.close() 
  1. 使用OS模塊執行 「net啓動」,同時重定向到一個文件名爲C:\ TEMP \ mypythonfiles \ currservices.txt
  2. 打開新創建的文件進行讀取
  3. 創建循環讀取文件中的每一行;內環路: *檢查每一行使用find()方法列出所有涉及到以下啓動的服務:網絡,診斷 *當發現打印服務名稱

回答

1

首先,我不認爲你需要在一個文件中寫入,使用subprocess.check_output代替:

import subprocess 
# create and execute a subprocess and write its output into output (string) 
output = subprocess.check_output(["net", "start"]) 

然後,我敢肯定,正則表達式會做的伎倆:

import re 
regex = re.compile("Network|Diagnostic") 
# split output (a raw multiline text) so you can iterate over lines 
for p in output.splitlines(): 
    # test regex over current line 
    if regex.match(p): 
     print(p) 
+0

同意。如果這是一個家庭作業問題,那麼你不應該被要求使用find(),這是不切實際的。改用正則表達式 –