python 执行完不关闭_python,进程_python 进程不退出,python,进程,锁 - phpStudy

python 进程不退出

写一个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('', '')

}

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

相关阅读:

Yii2 ActiveRecord 数据库字段过滤问题

JS异步加载时,JS文件会同时下载吗?

如何用mock解决待测函数对于外部函数的参数依赖

linux下node项目报404错误

[os.system]支持变量不?

IOS怎么获取当前网速

FIN packe是什么东西啊?在看node的net模块时看到的

json数据修改

Shiro的注解授权不起作用

web.py文件上传

关于PHP提交数据库事务模式的设计

bower init 初始化 报错

Number()函数传入Object时的情况

scrapy有模拟登录网站的相关方法吗?

Laycher ps -aux中的time 的意思

需要一个java的开源视频处理工具

在即时聊天服务中, 服务端只开一个监听端口,如果一个客户端连接过来了,服务端要不要开启一个临时端口和客户端进行通信啊?

oc范型能用于适配iOS7 的代码吗?

IE9下不能在iframe中click()

面向对象问题,方法体中不能将对象设置为空吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值