Executing linux command using python subprocess

Question:

I have a requirement where I need to extract port number from a file example.ini, this file is in linux directory.

Now when I am executing below command from CLI its giving exact result which I want

$ cat path/example.ini | grep -i variable | cut -d '=' -f 2

however I want run this command using python script using subprocess.run

I am executing in script

subprocess.run(['cat', 'path', '|', 'grep -i variable', '|', 'cut -d "=" -f2'])

I am getting error: No such file or directory

Asked By: Raz

||

Answers:

why use cat with grep ?
grep -i variable path/example.ini | cut -d ‘=’ -f 2

import subprocess

ps = subprocess.Popen(('grep', '-i', 'variable', 'path/example.ini'), stdout=subprocess.PIPE)
output = subprocess.check_output(('cut', '-d', '=', '-f', '2'), stdin=ps.stdout)
ps.wait()
print(output.decode("utf-8")) # bytes object to UTF8

I simplified my solution

import subprocess

ps = subprocess.Popen(('grep', '-i', 'variable', 'path/example.ini'), stdout=subprocess.PIPE)
output = subprocess.run(('cut', '-d', '=', '-f', '2'), stdin=ps.stdout).stdout
Answered By: user103162