Reputation: 11
I am running this python function in suse linux to grep ip of node from /etc/hosts--
def mm_node():
import os
node_name = os.system("`cat /etc/hosts | egrep -i mm | grep om | awk '{print $1}'`")
return node_name
mm_node()
As a result, it is showing this weird output
sh: 192.168.10.10: command not found
instead of
192.168.10.10
If I run the shell command
(cat /etc/hosts | egrep -i mm | grep om | awk '{print $1}'
)
directly on linux command prompt, it gives the o/p as
192.168.10.10
Upvotes: 0
Views: 217
Reputation: 155505
Backquotes tell the shell to capture the output and use it on the command line, typically as argument to a command, as in grep `whoami` /etc/passwd
. In your case the command line consists only of a backquoted pipeline, so the shell interprets the output of the pipeline as the command to execute. That is why it complains that the IP address is "not found".
If your intention is to capture the output of the pipeline to use in your Python code, you should use the subprocess
module, which is the modern alternative to os.system
that allows easy capturing of the output. For example:
import subprocess
def mm_node():
output = subprocess.run(
"cat /etc/hosts | egrep -i mm | grep om | awk '{print $1}'",
shell=True,
capture_output=True
).stdout
return output.strip()
print(mm_node())
Upvotes: 2
Reputation: 638
def mm_node():
import os
node_name = os.system("cat /etc/hosts | egrep -i mm | grep om | awk '{print $1}'")
return node_name
mm_node()
Upvotes: 0