python 进程不退出

发布于 2022-09-01 21:39:03 字数 5522 浏览 14 评论 0

写一个client程序,用于下载server段的程序并在client执行。
但是多次遇到问题就是,当server端down了以后,client执行会一直驻留在进程里不退出

我在最后加了sys.exit()也不管用。。。

请问这种情况如何解决?

完整代码如下

#! -*- coding:utf-8 -*-

import sys

reload(sys)
sys.setdefaultencoding('utf-8')

import logging
import os
import json
import codecs
import urllib
import urllib2
import commands
import subprocess
import time
import platform
import socket
import hashlib
import traceback
from datetime import datetime

_VERSION = 'v_3.0'
_SCRIPT_DIR, _SCRIPT = os.path.split(os.path.abspath(sys.argv[0]))

logging.basicConfig(level=logging.DEBUG,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='spider.log',
                filemode='w')

class FileUtil(object):
    """文件操作组件"""

    @classmethod
    def write_2_file(cls, file_path, file_name, content, encoding):
        try:
            if not os.path.exists(file_path):
                os.makedirs(file_path)
            file_path = '%s/%s' % (file_path, file_name)
            file = codecs.open(file_path, 'w', encoding)
            file.write(str(content).decode(encoding))
            file.close()
            return file_path
        except Exception, e:
            logging.debug(e)
            send_error_log(e)
            return None


class PyShell(object):
    """python 封装命令执行脚本"""

    @classmethod
    def new_progress(cls, command):
        """Create new progress to run the command"""
        status = subprocess.call(command, shell=True)
        return status

    @classmethod
    def get_output(cls, command):
        """Get the output of the command"""
        output = commands.getoutput(command)
        return output



def send_error_log(e):
    """发送一般性错误到服务器"""
    try:
        url = 'http://api.test.com/error-log'
        params = {
            'privateKey': get_private_key(),
            'script_name': _SCRIPT,
            'script_version': _VERSION,
            'client_ip': get_local_ip(),
            'host_name': platform.node(),
            'msg_type': type(e).__name__,
            'msg_body': e.__str__().replace('<', '').replace('>', '')
        }
        data = urllib.urlencode(params)
        req = urllib2.Request(url, data)
        response = urllib2.urlopen(req, timeout=10)
    except Exception:
        logging.debug(traceback.format_exc())
        pass


def do_post(url, data):
    """通过POST发包"""
    data = urllib.urlencode(data)
    req = urllib2.Request(url, data)
    for i in range(3):
        try:
            response = urllib2.urlopen(req, timeout=10)
            res = json.loads(response.read())
            return res
        except urllib2.URLError,e:
            logging.debug(e)
            if hasattr(e,"reason"):
                print "Failed to reach the server"
                print "The reason:",e
            elif hasattr(e,"code"):
                print "The server couldn't fulfill the request"
                print "Error code:",e
            if i == 3:
                send_error_log(e)
                sys.exit()

def get_private_key():
    """生成提交秘钥"""
    sys_time = datetime.now()
    now = sys_time.strftime('%Y-%m-%d %H:%M:%S')
    str_arr = now.split(' ')
    if len(str_arr) != 2:
        return None
    date_str_arr = str_arr[0].lstrip().rstrip().split('-')
    time_str_arr = str_arr[1].lstrip().rstrip().split(':')
    format_date = datetime(year=int(date_str_arr[0]), month=int(date_str_arr[1]), day=int(date_str_arr[2]), hour=int(time_str_arr[0]))
    result_time = format_date.__str__()
    temp_str = result_time[:str(result_time).index(':')] + ':00:00' + 'qsxdrgbhuk,lp'
    m = hashlib.md5()
    m.update(temp_str)
    private_key = m.hexdigest()
    return private_key

def get_local_ip():
    """获取本地ip"""
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("1.1.1.1",80))
        local_ip=s.getsockname()[0]
        s.close()
        return local_ip
    except Exception as e:
        logging.debug(traceback.format_exc())
        send_error_log(e)

def get_scripts():
    """从服务器下载脚本"""
    try:
        scripts = list()
        url = 'http://api.test.com/get-scripts'
        private_key = get_private_key()
        params = {'privateKey': private_key}
        response = do_post(url, params)
        if isinstance(response, dict):
            code = response.get('code')
            message = response.get('message')
            if int(code) == 200 and message:
                for url in message:
                    urllib.urlretrieve(url['url'], url['name'])
                    scripts.append(url['name'])
        return scripts
    except:
        logging.debug(traceback.format_exc())

def do_script():
    """Start working"""
    script_list = None
    for mark in range(3):
        try:
            # get scripts
            if not script_list:
                script_list = get_scripts()
            if script_list==None:
                continue
            for script in script_list:
                command_exec = 'chmod a+x %s' % script
                PyShell.new_progress(command_exec)
                PyShell.new_progress('./%s' % script)
                time.sleep(10)
            return
        except Exception as e:
            logging.debug(traceback.format_exc())
            if mark == 2:
                send_error_log(e)


if __name__ == '__main__':
    try:
        do_script()
    finally:
        sys.exit()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文