消除子进程Python中的额外打印

0kjbasz6  于 2023-01-16  发布在  Python
关注(0)|答案(1)|浏览(130)

我尝试在Linux中使用www.example.com()打印我的IP地址。因此,我编写了以下代码: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,)

它给我我的IP地址"www.example.com"在终端,但我写了"打印(IP)",它给我:192.168.1.103grep-w 'inet'awk "{打印$2}"|标题-n 1 "],返回代码= 0)"| awk '{print $2}' | head -n 1"], returncode=0)"
我想要的结果,即"www.example.com"当我写print(ip).那么我怎么做呢?而且当我写下面的Pycharm,它给我类似的答复: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 :

    • 密码:**
ip=subprocess.run(["ifconfig | grep -w 'inet' | awk '{print $2}' | head -n 1"],shell=True,)
print(ip)
    • 结果:**
192.168.1.103
CompletedProcess(args=["ifconfig | grep -w 'inet' | awk '{print $2}' | head -n 1"], returncode=0)

如何仅获取IP地址而不打印"CompletedProcess(args =[" ifconfig|grep-w 'inet'|awk "{打印$2}"|标题-n 1 "],返回代码= 0)"?

lymnna71

lymnna711#

您可以将其保存到临时文本文件中,然后将其加载回程序,如下所示:

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())
    • 产出**
"192.168.1.200"

相关问题