store Os.system result in variable

2019-07-12 19:52发布

问题:

hello guys i'm wondering how to store os.system result in variable

as we know it's return 0

so i'm wondering what i should do to store the result

and second question : how to get ip in Linux [ somebody will suggest ifconfig] but ifconfig show so many result i just wana the IP

回答1:

import os
from subprocess import *

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

As for the second question, see http://www.cyberciti.biz/tips/read-unixlinux-system-ip-address-in-a-shell-script.html



回答2:

Since you're first question is a python question, here is how to get the IP address in linux using python:

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])


回答3:

Hi You can Create Subprocess.pipe and can print output of ifconfig Here is a code for 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