2016-11-30 93 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(),这是不切实际的。改用正则表达式 –