我的脚本的目标是将netstart -a的结果打印到名为currservices.txt的文件中,然后查找其中包含单词Network或Diagnostic的服务。我创建了循环以列出所有已启动的服务,但不太了解如何在循环内使用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()
答案 0 :(得分: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)