2

大家好,我想知道如何将os.system结果存储在变量中

我们知道它返回 0

所以我想知道我应该怎么做才能存储结果

第二个问题:如何在 Linux 中获取 ip [有人会建议ifconfig] 但是ifconfig显示了这么多结果,我只是想IP

4

3 回答 3

1

由于您的第一个问题是 python 问题,这里是如何使用 python 在 linux 中获取 IP 地址:

import socket
import fcntl
import struct

ifname='eth0'
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
address = socket.inet_ntoa(fcntl.ioctl(
                    s.fileno(),
                    0x8915,  # SIOCGIFADDR
                    struct.pack('256s', ifname[:15])
                    )[20:24])
于 2011-06-08T10:53:14.033 回答
1
import os
from subprocess import *

def run_cmd(cmd):
        p = Popen(cmd, shell=True, stdout=PIPE)
        output = p.communicate()[0]
        return output

至于第二个问题,见http://www.cyberciti.biz/tips/read-unixlinux-system-ip-address-in-a-shell-script.html

于 2011-06-08T09:22:18.630 回答
0

嗨,您可以创建 Subprocess.pipe 并可以打印 ifconfig 的输出这是 Ref 的代码:

import os
import subprocess
from subprocess import *
subprocess.call(["ifconfig","en0”])
p=subprocess.Popen(["ifconfig","en0"],stdout=subprocess.PIPE)
for line in p.stdout:
    print line
于 2015-03-30T03:43:37.573 回答