Python Forum
how to watch for file in folder
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how to watch for file in folder
#1
i have a video file landing in a folder (mp4) on my raspberry pi that im overlaying with an image with ffmpeg which i want to automate. i.e. mp4 arrives in folder and the autoscript sees the new file then runs the ffmpeg to convert that file.

ultimately a similar script will rclone/rsync the completed file to a windows share too.

any ideas how i can go about this?

thanks
Reply
#2
You have to keep the previous content of the folder somewhere so when you scan it again to know if there are new files.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
Take a look at: http://brunorocha.org/python/watching-a-...ython.html
Reply
#4
(Aug-21-2017, 02:32 PM)Larz60+ Wrote: Take a look at: http://brunorocha.org/python/watching-a-...ython.html

that looks pretty cool, expect follow ups 'with how do I?' haha

i was thinking of using a continuous while loop to look for *.mp4 in a directory and if it exists convert it, then delete original

just installing watchdog now so will give it a bash.

cheers
Reply
#5
ok, i've found another sample script based on the watchdog as i could really understand the first on, so it sees the file arriving, prints the filename and path to screen but wont carry through to ffmpeg.

ive now got the below script that ive tried various ways but i either get the file %s doesnt exist or an invalid sytnax error when i try and enclose the ffmpeg into a 'command?? on the 'terminal' running ffmpeg i have the overlay=0:0 in "" but in this it took it as the end of the command, so i removed them....not sure if that will break anything though??

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from subprocess import call


class Watcher:
    DIRECTORY_TO_WATCH = "/home/pi/Videos/test"

    def __init__(self):
        self.observer = Observer()

    def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)
        self.observer.start()
        try:
            while True:
                time.sleep(5)
        except:
            self.observer.stop()
            print "Error"

        self.observer.join()


class Handler(FileSystemEventHandler):

    @staticmethod
    def on_any_event(event):
        if event.is_directory:
            return None

        elif event.event_type == 'created':
            # Take any action here when a file is first created.
            print "Received created event - %s." % event.src_path
            command = "ffmpeg -i "%s" -s 1920x1080 -i /home/pi/Videos/tff_overlay_1920x1080.png -filter_complex overlay=0:0 -b 4000000 -q:v 1 /home/pi/Videos/output.mp4"
            call([command], shell=True)

if __name__ == '__main__':
    w = Watcher()
    w.run()
Reply
#6
You should upgrade to python 3.6.2
for many reasons other than 2.7 is getting so far out of date!
Don't get left out in the cold.

I always use the latest version.

I'm testing your code now.
Reply
#7
When I run using python 3.6.2, it works. At least up to the point where the command is created in the handler.
I didn't bother to change that code, so I expected it to fail here.
I did make a few changes.
  • added import of os
  • converted
    DIRECTORY_TO_WATCH
    to self.dir in the initialization
  • ran the dir through os.path.abspath to get a full path
  • Started to change command, but it's not right
Here's my mods:
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from subprocess import call
import os


class Watcher:
    def __init__(self):
        self.dir = os.path.abspath('data/')
        self.observer = Observer()

    def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.dir, recursive=True)
        self.observer.start()
        try:
            while True:
                time.sleep(5)
        except:
            self.observer.stop()
            print("Error")

        self.observer.join()


class Handler(FileSystemEventHandler):
    @staticmethod
    def on_any_event(event):
        if event.is_directory:
            return None

        elif event.event_type == 'created':
            # Take any action here when a file is first created.
            print("Received created event - %s." % event.src_path)
            command = "ffmpeg -i " % s
            " -s 1920x1080 -i f'{dir}.tff' _overlay_1920x1080.png -filter_complex overlay=0:0 -b 4000000 -q:v 1 /home/pi/Videos/output.mp4"
            call([command], shell=True)


if __name__ == '__main__':
    w = Watcher()
    w.run()
Reply
#8
I eventually found out how to install 3.6.2, but when I run it, it still references 2.7?
I've copied what you did and changed the self.dir to my path and I'm getting an error that 's' isn't defined. As well as the other errors below.

pi@autocam:~/scripts $ python watchfile.py
Received created event - /home/pi/Videos/test/2017-08-21_16:17:17_360Video.mp4.
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/usr/local/lib/python2.7/dist-packages/watchdog/observers/api.py", line 199, in run
    self.dispatch_events(self.event_queue, self.timeout)
  File "/usr/local/lib/python2.7/dist-packages/watchdog/observers/api.py", line 368, in dispatch_events
    handler.dispatch(event)
  File "/usr/local/lib/python2.7/dist-packages/watchdog/events.py", line 322, in dispatch
    self.on_any_event(event)
  File "watchfile.py", line 36, in on_any_event
    command = "ffmpeg -i " % s
NameError: global name 's' is not defined

ok, after a little bit of playing I've changed the command line to this:
command = "ffmpeg -i %s -s 1920x1080 -i /home/pi/Videos/tff_overlay_1920x1080.png -filter_complex overlay=0:0 -b 4000000 -q:v 1 /home/pi/Videos/output.mp4" % event.src_path
call([command], shell=True)


the ffmpeg does run now, and I presume still using python 2.7. but how can I get it to save to a new directory but using the same filename? if I use the '%s' it will obviously save it to the directory it came from?

thanks
Reply
#9
During the install, you have to explicitly select to update paths.
It's been so long since I did an installation, I'm not sure where that question is asked.
Snippsat has a tutorial on this in the tutorials section of this forum. I see the linux version here: https://python-forum.io/Thread-Basic-Par...nvironment
and I believe these is a windows version as well.

as to the error.
I don't see where s is defined, so the error is valid.
somewhere this variable needs to be defined, or was it a format command? if so there should be no space, it should be %s
Reply
#10
I changed it to what the line above was, it had the %s then at the end of the line it follows with '% event.src_path' and somehow that made it work. I was expecting a definition somewhere too, like s = event.scr_path or something. I need to see how I can define just the file name now so I can output the same filename from the conversion.

this is where I got the instructions for the install for the python upgrade too python upgrade on raspian
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare folder A and subfolder B and display files that are in folder A but not in su Melcu54 3 615 Jan-05-2024, 05:16 PM
Last Post: Pedroski55
  Reading a file name fron a folder on my desktop Fiona 4 985 Aug-23-2023, 11:11 AM
Last Post: Axel_Erfurt
  Function not executing each file in folder mathew_31 9 2,350 Aug-22-2022, 08:40 PM
Last Post: deanhystad
  Dynamic File Name to a shared folder with open command in python sjcsvatt 9 6,159 Jan-07-2022, 04:55 PM
Last Post: bowlofred
  Code to check folder and sub folders for new file and alert fioranosnake 2 1,987 Jan-06-2022, 05:03 PM
Last Post: deanhystad
  Compare filename with folder name and copy matching files into a particular folder shantanu97 2 4,571 Dec-18-2021, 09:32 PM
Last Post: Larz60+
  How to import file and function in another folder SriRajesh 1 3,226 Dec-18-2021, 08:35 AM
Last Post: Gribouillis
  How to run an exe file in the Scripts folder using py.exe? quazirfan 2 2,990 Sep-08-2021, 01:00 AM
Last Post: quazirfan
  Move file from one folder to another folder with timestamp added end of file shantanu97 0 2,508 Mar-22-2021, 10:59 AM
Last Post: shantanu97
  Writing to file in a specific folder evapa8f 5 3,501 Nov-13-2020, 10:10 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020