Niv
Niv

Reputation: 27

Can't print bash output using subprocess.Popen

When trying to use subprocess.Popen I can't get the bash output and receive the following error:

SyntaxError: invalid syntax

The code is:

import subprocess

# Graphic-card

out = subprocess.Popen(['lspci', '|', 'grep', ''NVIDIA'''],

         stdout=subprocess.PIPE,

         stderr=subprocess.STDOUT)

stdout,stderr = out.communicate()

print(stdout)

Upvotes: 1

Views: 83

Answers (1)

chepner
chepner

Reputation: 531165

| is not a command argument; it's shell syntax that joins two commands. For this command, you need to either let the shell handle the pipe:

out = subprocess.Popen("lspci | grep NVIDIA", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

or create two Popen instances and connect them yourself:

pre_out = subprocess.Popen(["lspci"], stdout=subprocess.PIPE)
out = subprocess.Popen(["grep", "NVIDIA"], stdin=pre_out.stdout, stderr=subprocess.STDOUT)

Upvotes: 2

Related Questions