python后台执行shell

3 篇文章 0 订阅
2 篇文章 0 订阅

osx: 10.15

python: 3.6.5

airetest  ios需要执行两部shell命令,且需要一直执行,借用python来后台执行

之前的功能是网上转载的,由于业务需求,读了下subprocess源码,新增了个kill功能,实现终止后台运行的shell

#coding:utf-8
import subprocess, time

class Shell(object):
    def __init__(self, cmd):
        self.cmd = cmd
        self.ret_code = None
        self.ret_info = None
        self.err_info = None

    def run_background(self):
        self._process = subprocess.Popen(self.cmd, shell=True,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    def get_status(self):
        retcode = self._process.poll()
        if retcode == None:
            status = "RUNNING"
        else:
            status = "FINISHED"
        return status

    def print_output(self):
        for _ in range(6):
            line = self._process.stdout.readline() # 这儿会阻塞
            if line:
                print ("output:",line)
            else: # 只有子进程结束后, 才会有readline返回""的情况
                print ("no ouput yet")
    def kill(self):
        self._process.kill()

shells = '/usr/bin/xcodebuild -project WebDriverAgent.xcodeproj -scheme WebDriverAgentRunner -destination id=`system_profiler SPUSBDataType | grep "Serial Number:.*" | sed s#".*Serial Number: "##` test'

keepprinting1 = Shell(shells) 
keepprinting1.run_background()
keepprinting1.print_output()
keepprinting2 = Shell("iproxy 8100 8100") # keepprint will print out one line every 2 seconds
keepprinting2.run_background()
keepprinting2.print_output()
count = 0
while True:
    print("====running===="+str(count))
    count+=1
    print(keepprinting1.get_status()) 
    print(keepprinting2.get_status())
    time.sleep(2)
    if count == 7:
        keepprinting1.kill()#终止后台线程1

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值