store Os.system result in variable

自古美人都是妖i 提交于 2019-12-10 23:24:10

问题


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


来源:https://stackoverflow.com/questions/6276614/store-os-system-result-in-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!