Home > Blockchain >  Getting rid of extra printing in subprocess Python
Getting rid of extra printing in subprocess Python

Time:01-15

I am trying to print my ip address using subprocess.run() in Linux. So , i wrote the following code:

ip=subprocess.run(["ifconfig | grep -w 'inet' | awk '{print $2}' | head -n 1"],shell=True,)

It gives me my Ip address "192.168.1.103" in terminal , but i wrote it "print(ip)" , it gives me : "CompletedProcess(args=["ifconfig | grep -w 'inet' | awk '{print $2}' | head -n 1"], returncode=0)"

I want the result ,i.e "192.168.1.103" when i wrote print(ip). So how can i do it ? Moreover when i wrote the followings in Pycharm , it gives me similar reply :

The code:

ip=subprocess.run(["ifconfig | grep -w 'inet' | awk '{print $2}' | head -n 1"],shell=True,)
print(ip)

The result:

192.168.1.103
CompletedProcess(args=["ifconfig | grep -w 'inet' | awk '{print $2}' | head -n 1"], returncode=0)

How can I obtain only Ip address without printing "CompletedProcess(args=["ifconfig | grep -w 'inet' | awk '{print $2}' | head -n 1"], returncode=0)" ?

CodePudding user response:

You can save it to a temporary text file and load it back to the program like this:

import subprocess

ip=subprocess.run(["ifconfig | grep -w 'inet' | awk '{print $2}' | head -n 1"],shell=True, capture_output=True)
print((ip.stdout).decode('ascii').strip())

Output

"192.168.1.200"
  • Related