Python Subprocess checking whenever a new file is added

0

Need:

I need to "observe" a directory, with each new file inserted in this directory I need to make a copy of this file and forward it to an FTP server.

What I have:

I can send the file via FTP, and I can check the files in the directory.

What I need:

I need something Similar to the dropbox, a service "watching" the folder and trigger an action whenever a new file is created, preferably in real time with just the FTP upload delay.

I do not know if it has relevance but I will need to leave this service running on machines with windows 10, 8 and 7.

Is there any way to do this in Python ?

My attempt to resolve:

I thought about viewing the directory and retrieving a list of the existing files, so I would start an ifinito loop checking if the number of files would currently be the same as the first count, if the last count gives a value greater than the previous count is replaced the old list by the current one besides creating a list only with the items that were not in the old one, with the list of items that were not in the old list would send the files by FTP.

I do not know if my need was clear, I tried to put as much information as possible. I hope you can help me.

I created this code:

from ftplib import FTP
import os, subprocess
import time

f = open("lista.txt", "w")
f.writelines(os.listdir("C:\Users\Afonso\Desktop\nov2018\dirteste\"))
f.close()

def upload(filename, diretorio):
    print("Conectando ao servico FTP")
    ftp = FTP('host')
    print("Logando com Usuário de Senha")
    ftp.login('senha', 'senha')
    print("iniciando debug")
    ftp.set_debuglevel(3)
    print("trocando diretório")
    ftp.cwd('public_html')
    print("Preparando diretorio local e nome de arquivo.")
    file = "C:/Users/Afonso/Desktop/nov2018/dirteste/" + filename
    print("print conferindo se existe diretorio")
    try:
        print("Criando diretorio")
        ftp.mkd('/'+diretorio)
    except:
        pass
    print("enviando arquivo %s" %file)
    diretorio = "/"+diretorio+"/"
    ftp.storbinary("STOR " + diretorio + filename, open(file, 'rb'), 1024)


while True:
    nova_lista = os.listdir("C:\Users\Afonso\Desktop\nov2018\dirteste\")
    lista = open("lista.txt").readlines()
    print(type(lista))
    for file in nova_lista:
        if file not in lista:
            time.sleep(1)
            upload(file, "teste")
    del lista
    del nova_lista

The problem is my fear of the process consuming too much of the computer. Is there a way to improve or some technique that is not applied that improves the consumption of the program?

    
asked by anonymous 19.12.2018 / 22:18

1 answer

0

I decided to put a time.sleep(0.2) at the end of the while, the process went down from 98% to 0% of CPU usage and when there are many files to send to the server it varies between 3% and 0.2% / p>     

26.12.2018 / 17:46