我可以在文本文件中打印任何带有 Network 或 Diagnostic 的行。但是,输出将打印文件中的所有行。对于此脚本,我只需要用上述单词打印行即可。 导入操作系统
os.system("NET START > c:\\temp\\mypythonfiles\\currservices.txt")
path1="c:\\temp\\mypythonfiles\\currservices.txt"
list1=[]
substr1="Network"
substr2="Diagnostic"
tstring=substr1+substr2
stop=open("c:\\temp\\mypythonfiles\\currservices.txt","rt")
with open(path1,"rt") as file :
for line in file:
list1.append(line)
if line.find(tstring):
for line in list1:
print("Service found:",line, sep=" ")
stop.close()
以下是输出:
Service found: The command completed successfully.
Service found: These Windows services are started:
Service found:
Service found: Application Information
Service found: aswbIDSAgent
Service found: Avast Antivirus
Service found: Background Tasks Infrastructure Service
Service found: Base Filtering Engine
Service found: CNG Key Isolation
Service found: COM+ Event System
Service found: Connected Devices Platform Service
Service found: Connected Devices Platform User Service_2f2f13e
Service found: Connected User Experiences and Telemetry
Service found: Contact Data_2f2f13e
Service found: CoreMessaging
Service found: Credential Manager
Service found: Cryptographic Services
Service found: Data Sharing Service
Service found: Data Usage
Service found: DCOM Server Process Launcher
Service found: Delivery Optimization
Service found: Device Association Service
Service found: DHCP Client
Service found: Diagnostic Policy Service
Service found: Diagnostic Service Host
Service found: Distributed Link Tracking Client
Service found: DNS Client
Service found: Geolocation Service
Service found: Human Interface Device Service
Service found: IKE and AuthIP IPsec Keying Modules
....rest of NET START LIST
我已经尝试了很多事情来使其工作,但是输出几乎总是如上所述。任何帮助都会很棒。
答案 0 :(得分:0)
尝试一下:
for line in file:
if 'Network' in line or 'Diagnostic' in line:
print('Service found:', line)
很难理解当前代码中的操作。不需要list1
,并且您不应该遍历整个list1
并在每次找到'Network'
或'Diagnostic'
时打印它。
答案 1 :(得分:0)
您的代码中存在一些逻辑错误。首先,tstring=substr1+substr2
产生一个字符串'NetworkDiagnostic'
(两个子字符串的总和)。其次,如果找不到子字符串,并且line.find(tstring)
为-1
,则-1
返回True
。第三,永远不会使用变量stop
。
这是一个可能的解决方案:
with open(path1) as file:
for line in file:
if substr1 in line or substr2 in line:
print("Service found: ", line)