man
man

Reputation: 173

Print specified output in subrocess

I want to print specified output in subrocess Here is my code:

from subprocess import check_output

output = check_output(['python3', 'code.py']).decode('ascii')
print(output)

The output is:

Tom
John

How can I print just Tom or just John instead of both of them? I have tried print(output[0]) to print Tom but I get only T.

Upvotes: 0

Views: 41

Answers (2)

Olvin Roght
Olvin Roght

Reputation: 7812

Let's take a look on steps you've already done:

  1. You call check_output() and it returns output in the form of bytes;
  2. Then You call bytes.decode(), which returns str.

As a result you get multi-line string. You've tried to access to first line using index 0, but you got first char instead of first line. It happened, cause accessing to string by index will return you char from this index.

To get first line you should split lines of your multi-line string (convert str to list of str). There's built-in function str.splitlines() which does what you need.


So, to upgrade your code we need to add one more line before your print() statement:

output_lines = output.splitlines()

After that you can access to line by index:

print(output_lines[0])

Upvotes: 1

furas
furas

Reputation: 143125

You have single string and you can use any string's function.

You can split it and create list with lines

lines = output.split('\n')

And then display only first line

print(lines[0])

Upvotes: 2

Related Questions