Python Forum

Full Version: Printing the output in columns
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Gurus,

I am trying to print all services running on my windows laptop as a "three column output"
and i have written the following code.

However, i am only getting only one line output.
Could someone help/point me to the right direction?

import re
from subprocess import check_output

with open('c:/users/dell/file.txt', 'w') as f:
    output=check_output("c:/windows/system32/sc query state= all").decode()
    print(output, file=f)

print('Service Name \t DISPLAY NAME \t\t\t STATE')
file=open('c:/users/dell/file.txt').readlines()

for i in file:
    one=re.match(r'(SERVICE_NAME:)\s(.*)',i)
    if one is not None:
        x=one.group(2)

for i in file:
    two=re.match(r'(DISPLAY_NAME:)\s(.*)',i)
    if two is not None:
        y=two.group(2)

for i in file:
    three=re.search(r'(STATE.*:)\s(.*)',i)
    if three is not None:
            z=three.group(2)

print(('%s \t %s \t %s')%(x,y,z))
Output:
>>> Service Name DISPLAY NAME STATE WwanSvc WWAN AutoConfig 4 RUNNING >>>
You have to use lists:
x = [ ]
for i in file:
    x.append(...)
your tabs do not match.
header has 4 tabs before State field,
detail has only two.
you need to use two for both, and then adjust tab width to match.
A better way would be to format each field for maximum width, or anticipated maximum width
and then print fields with fixed spacing between.

for a good tutorial, see: https://www.python-course.eu/python3_for...output.php
#!python3
import re
from subprocess import check_output

with open('file.txt', 'w') as f:
    output=check_output("c:/windows/system32/sc query state= all").decode("utf-8", "ignore")
    print(output, file=f)
lines = open('file.txt').readlines()

x = [ ]
for line in lines:
    one=re.match(r'(SERVICE_NAME:)\s(.*)', line)
    if one:
        x.append(one.group(2))

y = [ ]
for line in lines:
    two=re.match(r'(DISPLAY_NAME:)\s(.*)', line)
    if two:
        y.append(two.group(2))

z = [ ]
for line in lines:
    three=re.search(r'(STATE.*:)\s(.*)', line)
    if three:
        z.append(three.group(2))

print('%-20s %-60s %-10s' % ("Service Name", "DISPLAY NAME", "STATE"))
for a,b,c in zip(x, y, z):
    print('%-20s %-60s %-10s' % (a, b, c))
#done