Python Forum

Full Version: how to watch for file in folder
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
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
You have to keep the previous content of the folder somewhere so when you scan it again to know if there are new files.
(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
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()
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.
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()
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
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
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
Pages: 1 2