python subprocess 应用

通过 subprocess 模块管理应用程序的启停,重启等等;
通过 xml.etree.ElementTree 修改 xml 文件;
通过 get_ip_address 自动获取 eth0 的 ip 地址:

#!/usr/bin/python

# system func etc.
import time
import os
import sys
import signal

# wamp etc.
from twisted.internet.defer import inlineCallbacks
from autobahn.twisted.wamp import ApplicationSession
from autobahn.twisted.wamp import ApplicationRunner

# for subprocess bonefish (wamp router)
import subprocess

# for parse xml
import xml.etree.ElementTree as ET
#from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring

# for get eth0 ip addres
import socket
import fcntl
import struct


bonefish_bin = "/home/guowei/bonefish"
start_script_ops = "abc.sh"
wamp_config_file = "wamp.xml"


def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

class MyComponent(ApplicationSession):
    def onConnect(self):
        self.robot = None # init
        print('transport connected')
        self.join(u'realmxxx')

    def onChallenge(self, challenge):
        pass

    @inlineCallbacks
    def onJoin(self, details):
        print("session attached")
        def onEvent(msg):
            print("Got event: {}".format(msg))
        yield self.subscribe(onEvent, u'com.topic.xxx')

        def startRobot():
            if self.robot == None:
                print("starting...")
                os.environ['ABC'] = '/home/guowei/abc'
                os.environ['MYPATH'] = '/home/guowei/mypath'
                self.robot = subprocess.Popen(["/bin/bash", "-c", start_script_ops]) #, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            else:
                retcode = self.robot.poll()
                if retcode == None:
                    print("already started...")
                    return
        yield self.register(startRobot, u'com.guowei.start')

        def stopRobot():
            if self.robot == None:
                return
            try:
                print("stopping...")
                outs = self.robot.terminate()
                time.sleep(5) # wait 5s for the MainThread to exit
                retcode = self.robot.poll()
                if retcode == None:
                    print("kill robot...")
                    self.robot.send_signal(signal.SIGKILL)
            except OSError:
                print("kill robot...")
                self.robot.send_signal(signal.SIGKILL)
            self.robot.wait()
            print("robot stopped...")
            self.robot = None
        yield self.register(stopRobot, u'com.guowei.stop')

        def restartRobot():
            try:
                stopRobot()
                time.sleep(5)
            except OSError:
                self.robot.send_signal(signal.SIGKILL)
            startRobot()
        yield self.register(restartRobot, u'com.guowei.restart')

    def onDisconnect(self):
        print("disconnected")

class Bonefish:
    def __init__(self):
        try:
            self.router = subprocess.Popen([bonefish_bin, "-r", "realmxxx", "-t", "8888", "-w", "8889"])
            time.sleep(2)
            if self.router.poll() != None:
                raise OSError
        except OSError:
            p = subprocess.Popen(["pkill", "-9", "bonefish"])
            p.wait()
            self.router = subprocess.Popen([bonefish_bin, "-r", "realmxxx", "-t", "8090", "-w", "8091"])
    def run(self, ip):
        wamp_server_addr  = 'ws://'+ip+':8889/ws'  # wamp web socket port
        self.runner = ApplicationRunner(url=wamp_server_addr.decode('utf-8'), realm=u"realm1")
        self.runner.run(MyComponent)
    def __del__(self):
        retcode = self.router.poll()
        if retcode == None:
            self.router.terminate()


if __name__ == '__main__':
    ip = get_ip_address('eth0')
    # auto handle wamp client ip
    try:
        tree = ET.parse(wamp_config_file)
        root = tree.getroot()
        for simple_tag in root.findall('simple'):
            if simple_tag.attrib['name'] == 'wamp_server_ip':
                value_tag = simple_tag.find('value')
                if value_tag.text != ip:
                    print('Replace wamp config ip %s to server ip %s' % (value_tag.text, ip))
                    value_tag.text = ip
                    #value_tag.set('name', 'yes')
                    tree.write(wamp_config_file, encoding="utf-8", xml_declaration=True)
    except :
        print("edit wamp config file exception...")
        sys.exit(0)

    # auto handle wamp server ip
    bonefish = Bonefish()
    bonefish.run(ip)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值