python - Write Python output neatly in a txt file?
问题描述
I am trying to create a program that lists and saves all running services on my Windows machine to a txt file. I got it to work but it is not listing line by line like in my output in the Python shell. Also, there are added parenthesis I do not want. See output vs txt file screenshot below. Also, my code is below.
My Code so far:
import win32con
import win32service
#Define ListServices class
def ListServices():
resume = 0
accessSCM = win32con.GENERIC_READ
accessSrv = win32service.SC_MANAGER_ALL_ACCESS
#Open Service Control Manager
hscm = win32service.OpenSCManager(None, None, accessSCM)
#Enumerate Service Control Manager DB
typeFilter = win32service.SERVICE_WIN32
stateFilter = win32service.SERVICE_ACTIVE
statuses = win32service.EnumServicesStatus(hscm, typeFilter, stateFilter)
for (short_name, desc, status) in statuses:
#Save output to txt file
f=open('MyServices.txt', 'w')
f.write(str(statuses))
f.close()
#Print output and append 'Running' at the end of each line
print(desc, status, '----------> Running')
ListServices();
解决方案
write
不会像 do 那样附加换行符print
,所以你应该自己处理它。另外,请注意,没有理由在每次迭代时打开和关闭文件。只要您需要,就让它保持打开状态:
with open('MyServices.txt', 'w') as f:
for (short_name, desc, status) in statuses:
f.write(str(statuses))
f.write(os.linesep)
#Print output and append 'Running' at the end of each line
print(desc, status, '----------> Running')
推荐阅读
- javascript - 当其中一个移动时,如何在铯沙堡中的两点之间画一条线?
- azure - 如何使用邮递员调用 azure graph api
- arduino - 5volt Arduino Pro Mini 无法驱动 5 Volt 执行器,但同样的工作由 Arduino Uno 完美完成
- html - CGI:如何将 Gnuplot 命令放入我的 bash 脚本中?
- jquery - 如何使数据表中的下拉列表不覆盖?
- java - Java - 如何从包含通用数组的 ArrayList 中访问值
- javascript - 如何可视化键盘(平板电脑)上的 inputtext?
- jmeter - 如果假设我有 500 个线程,如何计算请求中每个线程所花费的时间
- identityserver4 - IdentityServer4 是否与 .NETFramework 一起使用
- wso2 - 分散收集(克隆+聚合)不起作用