代码之家  ›  专栏  ›  技术社区  ›  C.med

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

  •  2
  • C.med  · 技术社区  · 7 年前

    我的服务器每分钟生成约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

    1 回复  |  直到 7 年前
        1
  •  2
  •   Martin Prikryl    7 年前

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

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

    你甚至可以 make the termination graceful .

    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)
    
    推荐文章