0

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

2
  • It seems like you wrote path instead of path/example.ini Commented Sep 5, 2022 at 12:18
  • that I have written here for example in actual command it is cat /var/tmp/backup/agent.ini Commented Sep 5, 2022 at 12:22

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You. I am able to run now and we can also run this command with res = os.popen('linux command').read()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.