0

I have two variables holding the ouputs from using subprocess output and want the output of the both variable to be printed into one line.. below is the details..

cmd1=subprocess.Popen("some_command", shell=True, stdout=subprocess.PIPE)
cmd_input1=cmd1.stdout.read().decode('utf8')

cmd_input1 has:

one
two
three
four


cmd2=subprocess.Popen("othere_command", shell=True, stdout=subprocess.PIPE)
cmd_input2=cmd2.stdout.read().decode('utf8')

while cmd_input2 has :
1
2
3
4

I need the print output of both the variables into one line, line below..

one   1
two   2
three 3
four  4

I tried below but not working.. i just started learning python..

print("%  %." % (cmd_input1, cmd_input2)

Its python3 , please guide..

2
  • try.. print(cmd_input1, str(cmd_input2)) Commented Jan 27, 2018 at 11:22
  • not working, still printing the output into one after another not into one line as expected Commented Jan 27, 2018 at 11:23

2 Answers 2

3

You may want to use zip() built-in function to mix two lists and split() to split the output to lists of strings.

Zip will make a list of tuples:

[('one', 1), ('two', 2), ('three', 3), ('four', 4)]

Then you'll need to print it out. Here's the full code:

zipped = zip(cmd_input1.split('\n'), cmd_input2.split('\n'))
for line in zipped:
    print(line[0], line[1])
Sign up to request clarification or add additional context in comments.

2 Comments

ababak, thx for the great input, that works nice, but it looks like if there are missing value in the cmd_input2 then its taking the next number joining into the cmd_input, would be great to suggest on this
Well, zip will aggregate elements from each of the lists one by one and it will stop when any of the lists are over. I am not sure what do you mean when you say missing values.
0

You can iterate over both outputs simultaneously by splitting them into lines and zipping them:

for out1, out2 in zip(cmd_input1.splitlines(), cmd_input2.splitlines()):
    print(out1.ljust(5), out2)

I also used str.ljust to align the output.

1 Comment

great ans indeed anx for the solution but it looks like if there are missing value in the cmd_input2 then its taking the next number joining into the cmd_input, would be great to suggest on this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.