繁体   English   中英

可以优雅地从外部终止的 Python 脚本

[英]Python script that can be externally terminated in a graceful manner

我的服务器每分钟生成约 30 个 xml 文件,我想做一个 sftp 将文件从服务器传输到我的机器。 我想用 Paramiko 做一个 sftp,我得到了我想要的波纹管脚本:

import paramiko
import os
import time
filename = "addresses.text"
localpath= "******"
serverpath= "*******"


while True:
    try:
        current_time = time.time()
        with open(filename) as f:
            data = f.readlines()
        for ipAddr in data:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(ipAddr,username="root",password="root")
            sftp = ssh.open_sftp()
            for element in sftp.listdir(serverpath):
                if element.endswith(".xml"):
                    try:
                        print(os.stat(localpath+f))
                    except:
                        try:
                            creation_time = sftp.stat(serverpath+element).st_mtime
                            if (current_time+3400 - creation_time) / (3600) <= 1:
                                sftp.get(serverpath+element,localpath+element)
                        except:
                            print(Exception)
            sftp.close()
            ssh.close()
        for f in os.listdir(localpath):
            creation_time = os.path.getctime(localpath+f)
            print((3600+current_time - creation_time) / (3600))
            if (3600+current_time - creation_time) / (3600) >= 1.8:
                os.unlink(localpath+f)

    except OSError as e:
        print(OSError)

我想做一些类似start sftp.py ,然后在后台运行我的脚本。 当我想停止连接时,只需运行stop sftp.py

这通常是如何实现的,一个正在运行的进程将其 PID 存储到一个文件中。

然后您可以实现另一个脚本(或现有脚本的参数 - 就像我下面的示例那样),从文件中读取 PID 并终止该进程。

您甚至可以使终止优雅

import signal
import time
import os
import sys

pidfile = "sftp.pid"

if (len(sys.argv) > 1) and (sys.argv[1] == "stop"):
    if os.path.isfile(pidfile):
        with open(pidfile, "r") as f:
            pid = int(f.read())
        print("stopping sftp process {0}".format(pid))
        os.kill(pid, signal.SIGTERM)
    else:
        print("sftp is not running")
    sys.exit()

class GracefulKiller:
    kill_now = False
    def __init__(self):
        signal.signal(signal.SIGINT, self.exit_gracefully)
        signal.signal(signal.SIGTERM, self.exit_gracefully)

    def exit_gracefully(self,signum, frame):
        self.kill_now = True

if __name__ == '__main__':
    pid = os.getpid()
    print("sftp is starting with pid {0}".format(str(pid)))
    with open(pidfile, "w") as f:
        f.write(str(pid))

    killer = GracefulKiller()
    while True:
        time.sleep(1)
        print("doing something in a loop ...")
        if killer.kill_now:
            break

    print "End of the program. I was killed gracefully :)"

    os.remove(pidfile)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM